我正在检查标准流的工作情况,目前我正在使用 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
保存到文件中。
可能是什么问题?
最佳答案
sys.stderr
似乎从未关闭过。当 testt()
出错时,程序退出——只是错误消息被重定向。所以文件是空白的。
https://stackoverflow.com/questions/33579238/
相关文章:
amazon-web-services - AWS CLI 工具 - 无法从 S3 递归下载
android - RecyclerView 不显示任何图像
android - 呈现问题 :Binary XML file line #-1: No start
python - NumPy 或 SciPy 计算加权中位数
email - 更改 TFS 2015 电子邮件警报中的主题
linq - 使用 select 模拟(最小起订量)GetAllAsync linq 查询
windows-services - Windows 服务的启动和停止超时是多少?