相关疑难解决方法(0)

从Python函数中抑制stdout/stderr打印

我有一个Python脚本,它使用我的雇主提供的一些闭箱Python函数(即我无法编辑这些函数).当我调用这些函数时,它们正在打印输出到我想要压制的linux终端.我尝试过重定向stdout/stderr;

orig_out = sys.stdout
sys.stdout = StringIO()
rogue_function()
sys.stdout = orig_out
Run Code Online (Sandbox Code Playgroud)

但这没有抓住输出.我认为我通过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 …
Run Code Online (Sandbox Code Playgroud)

python stdout

32
推荐指数
3
解决办法
2万
查看次数

如何在Python中抑制控制台输出?

我正在使用Pygame/SDL的操纵杆模块从游戏手柄获取输入.每当我调用它的get_hat()方法时,它就会打印到控制台.这是有问题的,因为我使用控制台来帮助我调试,现在它SDL_JoystickGetHat value:0:每秒被淹没60次.有没有办法可以禁用它?通过Pygame/SDL中的选项或在函数调用时抑制控制台输出?我在Pygame文档中没有提到这一点.

编辑:原来是由于在编译SDL库时打开了调试.

python pygame sdl

28
推荐指数
5
解决办法
5万
查看次数

标签 统计

python ×2

pygame ×1

sdl ×1

stdout ×1