以这段代码为例(tar可以用-z-J-J压缩,我知道有一个tarfile特定的模块,但它代表了一个长时间运行的进程)
from subprocess import Popen, PIPE
with open('tarball.tar.gz', 'w+') as tarball:
tarcmd = Popen(['tar', '-cvf', '-', '/home'], stdout=PIPE)
zipcmd = Popen(['gzip', '-c'], stdin=tarcmd.stdout, stdout=tarball)
tarcmd.stdout.close()
zipcmd.communicate()
# added a while loop that breaks when tarcmd gets a
# proper return value. Can it be considerate a good
# solution?
while tarcmd.poll() is None:
print('waiting...')
# test the values and do stuff accordingly
这是在python子进程中管道化两个命令的典型示例。现在检查zipcmd的返回码很容易,但是如何检查tarcmd是否失败?如果我检查它的返回码,我总是一个也得不到(我想是因为stdout关闭了)。基本上,如果两个命令中的一个失败,我想引发一个异常。在bash中有$PIPESTATUS,如何在python中实现?在
如果值是
None
,则表示相应的子进程仍然是活动的。顺便说一句,不需要在循环中调用tarcmd.poll()
。您可以使用tarcmd.wait()
阻止它直到它退出。在模拟shell管道不容易出错:
通过颠倒进程初始化顺序:
^{pr2}$使用} )来运行管道,而不是直接在
shell=True
(如果命令是从源文件中的字符串文本等可信输入构造的)或使用库(如^{Popen
上实现它,可能会更容易。在见How do I use subprocess.Popen to connect multiple processes by pipes?
相关问题 更多 >
编程相关推荐