我有一个管道方案subprocess
,其中一个进程p2
将另一个进程的输出p1
作为输入:
p1 = subprocess.Popen("ls -al", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen("grep mytext - ", shell=True, stdin=p1.stdout, stdout=subprocess.PIPE)
result = p2.communicate()
p1
或者p2
可能由于各种原因而失败,例如错误的输入或格式错误的命令。
此代码在p1
没有失败时工作正常。我怎样才能做到这一点,还要检查是否p1
特别或p2
特别失败?例子:
# p1 will fail since notafile does not exist
p1 = subprocess.Popen("ls notafile", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen("grep mytext - ", shell=True, stdin=p1.stdout, stdout=subprocess.PIPE)
result = p2.communicate()
我可以检查p2.returncode
并看到它不是0
,但这可能意味着p2
失败或 p1 失败。如果此管道出错,我如何专门检查是p1
失败还是失败?p2
我不知道如何使用p1.returncode
它,这将是理想且明显的解决方案。前任:
p1 = subprocess.Popen("ls foo", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen("grep mytext - ", shell=True, stdin=p1.stdout, stdout=subprocess.PIPE)
# here, p2.returncode not defined yet since we didn't communicate()
assert(p2 is None)
r = p2.communicate()
# now p2 has a returncode
assert(p2.returncode is not None)
# ... but p1 does not!
assert(p1.returncode is None)
所以我看不到 returncode 在这里有什么帮助?
感谢@abarnert 的完整解决方案是这样的:
p1 = subprocess.Popen("ls -al", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen("grep mytext - ", shell=True, stdin=p1.stdout, stdout=subprocess.PIPE)
result = p2.communicate()
if p2.returncode != 0:
# something failed
if p1.wait() != 0:
# p1 failed...
else:
# p2 failed...
ps 我知道shell=True
安全的注意事项。