如何在写入文件时实时分析通过管道传输到文件的命令的输出?
这是我到目前为止所拥有的:
with open('output.log', 'w') as out:
command = ['pg_dump', 'myDB']
p = subprocess.Popen(cmd, stdout=out, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, b''):
sys.stdout.flush()
print(">>> " + line.rstrip())
Run Code Online (Sandbox Code Playgroud)
但这会产生以下错误:
Traceback (most recent call last):
File "pipe-to-file.py", line 95, in <module>
for line in iter(p.stdout.readline, b''):
AttributeError: 'NoneType' object has no attribute 'readline'
Run Code Online (Sandbox Code Playgroud)
为什么p.stdout等于None这里?
您必须使用subprocess.PIPEforstdout参数才能获取文件对象,否则它将是None. 这就是为什么p.stdoutequalsNone在你的代码中。
使用
communicate()而不是.stdin.write,.stdout.reador.stderr.read来避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。
如果您想stdout在分析输出时写入文件,那么您可以使用类似的东西。
with open('log', 'ab+') as out:
p = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out, std_error = p.communicate()
# Do something with std_out
# ...
# Write to the file
out.write( std_out )
# You can use `splitlines()` to iterate over the lines.
for line in std_out.splitlines():
print line
Run Code Online (Sandbox Code Playgroud)