我看到使用pycurl的例子,但不能确定这是否可以使用?一些例子会有所帮助.谢谢.
我想将 Python 脚本的标准错误和标准输出重定向到同一个输出文件。从我可以使用的终端
$ python myfile.py &> out.txt
Run Code Online (Sandbox Code Playgroud)
完成我想要的相同任务,但我需要从 Python 脚本本身完成它。
我调查了Redirect subprocess stderr to stdout,How to redirect stderr in Python? 和示例 10.10 从这里开始,然后我尝试了以下操作:
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a"
Run Code Online (Sandbox Code Playgroud)
它正确地在文件 out.txt 中打印了字母“a”;但是,当我尝试以下操作时:
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a # missing end quote, will give error
Run Code Online (Sandbox Code Playgroud)
我在终端上收到错误消息“SyntaxError ...”,但在文件 out.txt 中没有。我需要做什么才能将 SyntaxError 发送到文件 out.txt?我不想写异常,因为那样的话我必须在脚本中写太多异常。我正在使用 Python 2.7。
更新:正如下面的答案和评论中所指出的,SyntaxError 将始终输出到屏幕,我替换了该行
print "a # missing …Run Code Online (Sandbox Code Playgroud)