我正在尝试编写一个实用程序,它将在 Python 中无缝地将无限数量的命令组合在一起。到目前为止,这是我在 the documentation on piping in subprocess
之后得出的结论:
from subprocess import Popen, PIPE, STDOUT
def taskchain(argset, result=STDOUT):
lastprocess = None
for index, args in enumerate(argset): # expected to be a list containing lists
process = Popen(args, stdout=stdout if index == (len(argset)-1) else PIPE,
stdin=None if lastprocess is None else lastprocess.stdout)
if lastprocess is not None:
lastprocess.stdout.close()
lastprocess = process
if stdout == PIPE:
return lastprocess.communicate()[0]
else:
lastprocess.wait()
请注意,我没有使用 shell=True
来避免那里的安全问题。
不幸的是,这不起作用,因为我得到:
OSError: [Errno 9] Baf file descriptor
我不确定什么似乎失败了。有人可以帮我写一个方法来为无限数量的子流程实现流程链接吗?
(用例是这样的:taskchain([('ps', 'aux'), ('grep', 'python'), ('cut', '-b', '1') ])
.)
最佳答案
stdout=stdout if argset.index(args) == (len(args) - 1) else PIPE)
应该是这样
stdout=stdout if argset.index(args) == (len(argset) - 1) else PIPE)
你最好使用 enumerate
而不是 argset.index
。
此外,您需要将子流程相互连接:
..., stdin=None if lastprocess is None else lastprocess.stdout)
最后,STDOUT
仅作为 stderr
参数的参数有效;要通过标准输出,您应该通过 stdout=None
。
关于python - 在 Python 中解决进程链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733768/