重定向_stderr不起作用(Python 3.5)
如上所述,我使用了重定向_stderr不起作用(Python 3.5),python,python-3.x,std,stderr,Python,Python 3.x,Std,Stderr,如上所述,我使用了redirect\u stderr函数将stderr重定向到StringIO对象。但是,它不起作用,因为错误消息仍然会在命令提示符中打印出来: #! python3 from contextlib import redirect_stderr import io f = io.StringIO() with redirect_stderr(f): # simulates an error erd 回溯(最近一次呼叫最后一次): 文件“C:\Users\max
redirect\u stderr
函数将stderr重定向到StringIO
对象。但是,它不起作用,因为错误消息仍然会在命令提示符中打印出来:
#! python3
from contextlib import redirect_stderr
import io
f = io.StringIO()
with redirect_stderr(f):
# simulates an error
erd
回溯(最近一次呼叫最后一次):
文件“C:\Users\max\testerr.py”,第8行,在
erd
NameError:未定义名称“erd”
我在Python3.5.1
64位和3.5.2
64位上测试了它,结果相同
我还尝试将错误写入链接线程中所述的文件,但运行脚本后该文件为空。您需要实际写入stderr,它不是捕获异常的工具
Traceback (most recent call last):
File "C:\Users\max\testerr.py", line 8, in <module>
erd
NameError: name 'erd' is not defined
要捕获异常,您需要做更多的工作。您可以使用日志库(外部),或者编写自己的异常处理程序,然后使用自定义输出
下面是一些快速功能,它使用记录器实例帮助写入流:
>>> from contextlib import redirect_stderr
>>> import io
>>> f = io.StringIO()
>>> import sys
>>> with redirect_stderr(f):
... print('Hello', file=sys.stderr)
...
>>> f.seek(0)
0
>>> f.read()
'Hello\n'
这里的f
与上面的StringIO
实例相同。运行此代码后,您不应在控制台上看到任何回溯,但它将存储在stream对象中:
log = logging.getLogger('TEST')
log.addHandler(logging.StreamHandler(stream=f))
def exception_handler(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
# Let the system handle things like CTRL+C
sys.__excepthook__(*args)
log.error('Exception: ', exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = exception_handler
raise RuntimeError('foo')
>f.seek(0)
0
>>>打印(f.read())
你好
例外情况:
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
运行时错误:foo
我认为erd是在初始化之前访问的。你能考虑定义变量还是检查它是否在函数调用和Reun中被传递?<代码> SysDRR= IO。StRIGIONE()/代码>,你应该知道错误仍然会被提升,所以存储在IO对象条中,你捕捉到的异常看起来是多余的,谢谢你的解释。我假设redirect\u stderr
可以隐式抑制stderr输出。变量args
从何处获取?(在系统中使用的一个。你知道这种方法在jupyter笔记本中是否有效吗?
>>> f.seek(0)
0
>>> print(f.read())
Hello
Exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: foo