#! python3
from contextlib import redirect_stderr
import io
f = io.StringIO()
with redirect_stderr(f):
# simulates an error
erd
如上所述,我使用了redirect_stderr
函数将stderr重定向到StringIO
对象。但是,它不起作用,因为错误消息仍然会在命令提示符中打印出来:
Traceback (most recent call last):
File "C:\Users\max\testerr.py", line 8, in <module>
erd
NameError: name 'erd' is not defined
我在Python 3.5.1
64位和3.5.2
64位上测试了它,结果相同
A similar issue in this thread
我还尝试将错误写入链接线程中所述的文件,但运行脚本后该文件为空
您需要实际写入stderr,它不是捕获异常的工具
要捕获异常,您需要做更多的工作。您可以使用日志库(外部),或者编写自己的异常处理程序,然后使用自定义输出
下面是一些快速功能,它使用记录器实例帮助写入流:
这里
f
是上面相同的StringIO
实例。运行此代码后,您不应在控制台上看到任何回溯,但它将存储在stream对象中:相关问题 更多 >
编程相关推荐