parted mklabel' 在Python子进程中引发错误
我想通过 Python 脚本来格式化一个硬盘,使用的是 subprocess.Popen 这个方法。
在命令行中输入下面的命令可以正常工作。不过,使用这个命令的时候要小心哦!
parted /dev/sdh mklabel gpt
Warning: The existing disk label on /dev/sda will be destroyed and all data on this disk will be lost. Do you want to continue?
Yes/No?
我输入“是”来确认,然后硬盘就被格式化成功了。
但是在 Python 的 subprocess 里运行这个命令时,Popen 返回了状态码 1,这表示出错了。
我甚至无法在标准输入的管道里写入“是”。
代码如下:
#test1
from subprocess import Popen, PIPE, STDOUT
p = Popen('parted /dev/sdh mklabel gpt', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print p.wait()
或者,
# test2
p = Popen('parted /dev/sdh mklabel gpt', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
p.stdin.write('Yes\n')
IOError: [Errno 32] Broken pipe
我不太确定 Popen 是否把这个警告当成错误,如果是的话,我该怎么改变它的行为呢?感谢任何建议。
1 个回答
0
通过在命令中添加 -s 这个选项(忽略输出),parted 就能成功退出了。
Popen('parted -s /dev/sdh mklabel gpt', shell=True)