我有以下 python 脚本。如何单独记录每个命令的输出,即每个命令一个包含该命令输出的文件?
#!/usr/bin/env python
from subprocess import Popen
import sys
commands = [
'command1',
'command2',
'command3'
]
processes = [Popen(cmd, shell=True) for cmd in commands]
for p in processes:
p.wait()
最佳答案
只需将stdout
参数设置为相应的文件即可:
import shlex
from contextlib import ExitStack # $ pip install contextlib2 (on Python 2)
from subprocess import Popen
with ExitStack() as stack:
for i, cmd in enumerate(commands):
output_file = stack.enter_context(open('output%d.log' % i, 'w'))
stack.callback(Popen(shlex.split(cmd), stdout=output_file).wait)
要重定向子进程的 stderr 输出,您可以设置 stderr
参数。如果 stderr=subprocess.STDOUT
则 stdout 和 stderr 被合并。
ExitStack
用于关闭文件并等待已启动的子进程退出,即使 with
语句内发生异常,例如,如果某些命令无法启动。
关于python - 如何将并行子进程的输出写入不同的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23300242/