Python - sys.stderr无法保存到.txt或.log文件中。

3

我正在检查标准流的工作方式,目前我正在使用Python处理stderr。为了更清楚地解释,以下是我的代码:

print("Python")
testt()

当我运行代码时,我得到以下结果:
Python
Traceback (most recent call last):
File "C:/Python34/s3.py", line 5, in <module>
testt()
NameError: name 'testt' is not defined

现在我想将错误信息保存到文本文件中,所以我的代码如下:

import sys

sys.stderr = open('err.txt', 'w') # I tried with 'err.log' also
print("Python")
testt()

sys.stderr.close()
sys.stderr = sys.__stderr__

现在当我运行程序时,错误信息既没有显示在Python shell中,也没有保存到err.txt文件中。
当我检查err.txt文件属性时,它显示该文件最近已被修改(即运行程序时的时间),但文件是空白的。可能出现了什么问题?我使用的是Windows和Python 3.4。
我安装了Python 3.5,但仍然遇到相同的问题。我还尝试使用contextlib,但仍然不成功。我的修改代码如下:contextlib
from contextlib import redirect_stdout, redirect_stderr

with open('C:/Users/Jeri_Dabba/Desktop/Shortcutz/test/outfile.txt', 'w') as file, redirect_stdout(file):
    help(pow)

with open('C:/Users/Jeri_Dabba/Desktop/Shortcutz/test/errfile.log', 'a') as file1, redirect_stderr(file1):
    testt()
redirect_stdout(file) 已经正常工作,它会将输出保存到文件中;而 redirect_stderr(file1) 没有将 stderr 保存到文件中。
可能出现了什么问题?

可以运行,你是在Python Shell中运行代码吗? - Remi Guan
相关链接:https://dev59.com/jW035IYBdhLWcg3wMM4G - edition
不,我将其作为单独的.py文件运行。 - Jeril
那么,如果你不在Python Shell中运行它,它可能会起作用。然而,我正在使用Python 3.5并且它可以工作。 - Remi Guan
еШњпЉМдєЯиЃЄеИ†йЩ§sys.stderr.close()еТМ sys.stderr = sys.__stderr__пЉЯ - Remi Guan
显示剩余3条评论
1个回答

0

看起来 sys.stderr 从未关闭。当 testt() 出错时,程序会退出 -- 只有错误消息被重定向了。因此文件是空的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接