[英]Analyze output of subprocess.Popen when piping to file
How can I analyze the output of my command, which I pipe to file, in real-time while the file is written?如何在写入文件时实时分析通过管道传输到文件的命令的输出?
This is what I have so far:这是我到目前为止:
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())
But this generates the following error:但这会产生以下错误:
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'
Why is p.stdout
equal to None
here?为什么p.stdout
在这里等于None
?
You have to use subprocess.PIPE
for the stdout
argument in order to get a file object, else it'll be None
.您必须对stdout
参数使用subprocess.PIPE
才能获取文件对象,否则它将是None
。 That's why p.stdout
equals to None
in your code.这就是为什么p.stdout
在您的代码中等于None
的原因。
Use
communicate()
rather than.stdin.write
,.stdout.read
or.stderr.read
to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.使用communicate()
而不是.stdin.write
、.stdout.read
或.stderr.read
来避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。
If you want to write stdout
to a file while analyzing the output then you can use something like this.如果您想在分析输出时将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
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error=p.communicate()
Now you have your output,error.现在你有你的输出,错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.