使用 Python 将 stdout 和 stderr 重定向到同一个文件 [英] Redirect stdout and stderr to same file using Python
问题描述
我想将 Python 脚本的标准错误和标准输出重定向到同一个输出文件.从终端我可以使用
I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use
$ python myfile.py &> out.txt
执行我想要的相同任务,但我需要从 Python 脚本本身完成.
to do the same task that I want, but I need to do it from the Python script itself.
我调查了问题将子进程标准错误重定向到标准输出,如何在 Python 中重定向 stderr?,以及来自 这里,然后我尝试了以下操作:
I looked into the questions Redirect subprocess stderr to stdout, How to redirect stderr in Python?, and Example 10.10 from here, and then I tried the following:
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a"
在文件 out.txt 中正确打印字母a";但是,当我尝试以下操作时:
which rightly prints the letter "a" in the file out.txt; however, when I try the following:
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a # missing end quote, will give error
我在终端上收到错误消息SyntaxError ...",但在文件 out.txt 中没有.我需要做什么才能将 SyntaxError 发送到文件 out.txt?我不想写异常,因为那样的话我必须在脚本中写太多异常.我使用的是 Python 2.7.
I get the error message "SyntaxError ..." on the terminal, but not in the file out.txt. What do I need to do to send the SyntaxError to the file out.txt? I do not want to write an Exception, because in that case I have to write too many Exceptions in the script. I am using Python 2.7.
更新:正如下面的答案和评论中所指出的,SyntaxError 将始终输出到屏幕,我替换了该行
Update: As pointed out in the answers and comments below, that SyntaxError will always output to screen, I replaced the line
print "a # missing end quote, will give error
由
print 1/0 # Zero division error
ZeroDivisionError 输出到文件,因为我想在我的问题中使用它.
The ZeroDivisionError is output to file, as I wanted to have it in my question.
推荐答案
这个有效
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
这篇关于使用 Python 将 stdout 和 stderr 重定向到同一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!