我想将Python脚本的标准错误和标准输出重定向到同一输出文件.从终端我可以使用
$python myfile.py &> out.txt
来完成我想要的任务,但是我需要从Python脚本本身开始.
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a"
正确地在文件out.txt中打印字母“ a”;但是,当我尝试以下操作时:
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.
更新:正如下面的答案和注释中指出的那样,SyntaxError将始终输出到屏幕,我替换了该行
print "a # missing end quote, will give error
通过
print 1/0 # Zero division error
ZeroDivisionError输出到文件,因为我想在我的问题中使用它.