python - 如何防止错误消息显示在屏幕上
问题描述
因此,我尝试了多种解决方案,并且能够减少错误消息的打印,但它仍然会打印,我似乎无法弄清楚如何隐藏由 Python 调用的某些 C 代码打印出的丑陋消息。我无法控制 C 代码,因此无法更改。
我尝试创建一个上下文管理器类来重定向我的所有输出并设置sys.tracebacklimit = 0
. trackbacklimit 减小了输出的大小,但我仍然收到以下消息:
Traceback (most recent call last):
AttributeError: 'SystemError' object has no attribute '_render_traceback_'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
AssertionError
Traceback (most recent call last):
AttributeError: 'SystemError' object has no attribute '_render_traceback_'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
AssertionError
Traceback (most recent call last):
AttributeError: 'SystemError' object has no attribute '_render_traceback_'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
AssertionError
该函数实际上并没有失败,它只是抛出错误的错误消息,所以我需要隐藏输出。
这是我所做的:
import sys
try:
old = sys.tracebacklimit
sys.tracebacklimit = 0
except:
sys.tracebacklimit = 0
old = 1000
def excepthook(*args, **kwargs):
pass
old_except = sys.excepthook# = excepthook
sys.excepthook = excepthook
class suppress_stdout_stderr(object):
'''
A context manager for doing a "deep suppression" of stdout and stderr in
Python, i.e. will suppress all print, even if the print originates in a
compiled C/Fortran sub-function.
This will not suppress raised exceptions, since exceptions are printed
to stderr just before a script exits, and after the context manager has
exited (at least, I think that is why it lets exceptions through).
'''
def __init__(self):
# Open a pair of null files
self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
# Save the actual stdout (1) and stderr (2) file descriptors.
self.save_fds = [os.dup(1), os.dup(2)]
def __enter__(self):
# Assign the null pointers to stdout and stderr.
os.dup2(self.null_fds[0],1)
os.dup2(self.null_fds[1],2)
def __exit__(self, *_):
# Re-assign the real stdout/stderr back to (1) and (2)
os.dup2(self.save_fds[0],1)
os.dup2(self.save_fds[1],2)
# Close all file descriptors
for fd in self.null_fds + self.save_fds:
os.close(fd)
我不想为我的方法打印任何内容。
解决方案
所以我终于想通了。我做了以下事情:
import os
from contextlib import ExitStack, redirect_stdout, redirect_stderr, suppress
from io import StringIO
err = None
with ExitStack() as stack, suppress(Exception) as s3, suppress(ValueError) as s2, suppress(SystemError) as s1:
null_stream = StringIO()
with redirect_stdout(null_stream) as s4:
try:
old = sys.tracebacklimit
sys.tracebacklimit = 0
except:
sys.tracebacklimit = 0
old = 1000
stack.enter_context(redirect_stdout(null_stream))
try:
print('problem code here')
except Exception as errmsg:
err = errmsg
finally:
stack.close()
sys.tracebacklimit = 1000
if err:
raise err
我将所有消息推送到 StringIO 并使用 ExitStack() 以及抑制上下文来阻止任何显示。这确实会导致问题,因此在 try/except/finally 中,我保存了任何真正的错误,如果不是 None 则引发该错误。
这不是一个很好的解决方案,但它有效。我无法按要求访问 C 代码。
推荐阅读
- html - 响应式表格 - 如何在表格中下拉而不是侧身
- php - 检查值是否存在大小写字母
- php - 防止从外部目录包含 PHP 文件
- javascript - 由于错误 TypeError 未发送通知:无法读取 null 的属性“描述”
- types - 记录判别式能否在 Ada 中间接确定数组长度?
- python - 在分布式张量流中涉及实例梯度时性能缓慢
- python - 无法从购物车中删除商品
- jsp - 如何对 jsp 页面和 wsdl 进行 OPTIONS Rest 调用
- postgresql - Postgres:如何优化使用多个 json_array_elements() 调用的查询
- r - R通过索引列表调用一组列