我有一个
Python脚本,正在使用我的雇主提供的一些封闭的Python函数(即我不能编辑这些函数).当我调用这些功能时,他们正在打印输出到我想要禁止的linux终端.我试过重定向stdout / stderr通过;
orig_out = sys.stdout
sys.stdout = StringIO()
rogue_function()
sys.stdout = orig_out
但这不能捕获输出.我认为我通过Python(rogue_function()从上面调用的函数)实际上是用于编译C代码的包装器,它们正在进行打印.
有没有人知道一种方式,我可以通过功能(以及任何功能调用的子功能)对stdout / stderr中的任何打印进行“深度捕获”?
更新:
我最后采取了下面所选答案中列出的方法,并编写了一个上下文管理器来抑制stdout和stderr:
# Define a context manager to suppress stdout and stderr.
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 the null files
os.close(self.null_fds[0])
os.close(self.null_fds[1])
使用这个你只是:
with suppress_stdout_stderr():
rogue_function()
这工作“相当不错”.它确实抑制了流氓功能的打印输出,这些功能使我的脚本变得混乱.我注意到在测试它,它允许通过提出的异常以及一些记录器打印,我不完全清楚为什么.我认为这些信息与这些消息发送到stdout / stderr有关(我认为在我的上下文管理器退出之后).如果有人可以确认,我有兴趣听详细信息…