如何在Python中捕获stderr?

2024-05-29 04:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想捕获从python模块A生成的错误消息。{< CD1> }是用C++和SWIG编写的,因此我不能捕获Python的^ {CD3}}。在

>>> import A
>>> A.func() # this prints an error message by C++ std::cerr.
this is an error message from module A

我要做的是抑制错误消息并根据错误类型更改脚本行为。但是A.func()不返回错误号。在


假设我对下面的contextlib的使用是正确的,这并没有帮助。在

^{pr2}$

Tags: 模块importan消息messageby错误error
1条回答
网友
1楼 · 发布于 2024-05-29 04:29:18

谢谢@PM2Ring

https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/#id1

只需稍作修改:将所有的stdout替换为stderr,并支持如下所示的macOS,它完全如预期的那样工作。在

if sys.platform == 'darwin':
    c_stderr = ctypes.c_void_p.in_dll(libc, '__stderrp')
else:
    c_stderr = ctypes.c_void_p.in_dll(libc, 'stderr')

相关问题 更多 >

    热门问题