python stdout_从Python函数抑制stdout / stderr打印

我有一个

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有关(我认为在我的上下文管理器退出之后).如果有人可以确认,我有兴趣听详细信息…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值