[英]Reading last error message in log file
在Python 2.7中,某些循环内有以下代码
file = open("log.txt", 'a+')
last_position = file.tell()
subprocess.Popen(["os_command_producing_error"], stderr = file)
file.seek(last_position)
error = file.read()
print(error) # example of some action with the error
目的是当file
保留整个记录时,由stderr
给出的stderr
会得到打印,例如打印出来。
我是Python的初学者,我不清楚stderr = file
会发生什么。
我的问题是,即使错误不断记录在file
, error
始终为空。
有人可以解释为什么吗?
我尝试再次添加关闭和打开文件,或者在subprocess
行之后添加file.flush()
。 但是效果还是一样。
编辑:下面答案中的代码对我来说很有意义,对于该帖子的作者来说似乎很有用。 对我来说(在Windows中),它不起作用。 它给出一个空的err
和一个空的文件log.txt
。 如果我逐行运行它(例如调试),它确实可以工作。 如何理解和解决这个问题?
编辑:我更改了Popen
与call
,现在可以使用了。 我想call
会等待subprocess
完成才能继续执行脚本。
error
为空,因为您在该过程有机会将任何内容写入文件之前读取得太早。 Popen()
开始一个新过程; 它不等待它完成。
call()
等同于Popen().wait()
,它确实等待子进程退出,这就是为什么在这种情况下您应该看到非空error
的原因(如果子进程确实向stderr
写入了任何内容)。
#!/usr/bin/env python
import subprocess
with open("log.txt", 'a+') as file:
subprocess.check_call(["os_command_producing_error"], stderr=file)
error = file.read()
print(error)
您应该注意混合使用缓冲( .read()
)和无缓冲I / O( subprocess
.read()
) 。
您不需要此处的外部文件即可读取错误:
#!/usr/bin/env python
import subprocess
error = subprocess.check_output(["os_command_producing_error"],
stderr=subprocess.STDOUT)
print(error)
它合并stderr和stdout并返回输出。
如果您不想捕获stdout,而仅获取stderr,则可以使用Popen.communicate()
:
#!/usr/bin/env python
import subprocess
p = subprocess.Popen(["os_command_producing_error"], stderr=subprocess.PIPE)
error = p.communicate()[1]
print(error)
您可以捕获stderr并将其附加到文件中:
#!/usr/bin/env python
import subprocess
error = bytearray()
p = subprocess.Popen(["os_command_producing_error"],
stderr=subprocess.PIPE, bufsize=1)
with p.stderr as pipe, open('log.txt', 'ab') as file:
for line in iter(pipe.readline, b''):
error += line
file.write(line)
p.wait()
print(error)
请尝试以下代码:
file = open("log.txt", 'a+')
sys.stderr = file
last_position = file.tell()
try:
subprocess.call(["os_command_producing_error"])
except:
file.close()
err_file = open("log.txt", 'r')
err_file.seek(last_position)
err = err_file.read()
print err
err_file.close()
sys.stderr
映射标准错误消息,例如sys.stdout
(映射标准输出)和sys.stdin
(映射标准输入)。
这会将标准错误映射到file
。 因此,所有标准错误都将写入文件log.txt
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.