iri*_*ent 2 python std stderr python-3.x
#! python3
from contextlib import redirect_stderr
import io
f = io.StringIO()
with redirect_stderr(f):
# simulates an error
erd
Run Code Online (Sandbox Code Playgroud)
如上所示,我使用该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
Run Code Online (Sandbox Code Playgroud)
我在 Python 3.5.164 位和3.5.264 位上对其进行了测试,结果相同。
我还尝试将错误写入链接线程中所述的文件,但运行脚本后该文件为空。
您需要实际写入 stderr,它不是捕获异常的工具。
>>> 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'
Run Code Online (Sandbox Code Playgroud)
要捕获异常,您需要做更多的工作。您可以使用日志库(外部),或编写您自己的异常处理程序,然后使用您的自定义输出。
这是一些快速的东西,它使用记录器实例来帮助写入流:
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')
Run Code Online (Sandbox Code Playgroud)
这f是StringIO上面的相同实例。运行此代码后,您不应在控制台上看到任何回溯,但它将存储在流对象中:
>>> f.seek(0)
0
>>> print(f.read())
Hello
Exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: foo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1690 次 |
| 最近记录: |