有没有办法阻止函数调用print
我正在为一个正在开发的游戏使用pygame.joystick
模块。
我创建了一个pygame.joystick.Joystick
对象,并在游戏的实际循环中调用其成员函数get_button
来检查用户输入。这个函数做了我需要它做的所有事情,但问题是它还调用了print
,这会大大降低游戏的速度。
我可以阻止此对print
的调用吗
发布于 2011-12-06 04:54:23
Python允许您使用任何文件对象覆盖标准输出(stdout)。这应该可以跨平台工作,并写入空设备。
import sys, os
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
print 'This will print'
blockPrint()
print "This won't"
enablePrint()
print "This will too"
如果您不希望打印该函数,请在该函数之前调用blockPrint()
,如果希望继续执行,则调用enablePrint()
。如果要禁用所有打印,请从文件顶部开始阻止。
发布于 2017-09-09 17:53:35
正如@Alexander Chzhen建议的那样,使用上下文管理器将比调用一对状态更改函数更安全。
但是,您不需要重新实现上下文管理器-它已经在标准库中。您可以使用contextlib.redirect_stdout
重定向stdout
( print
使用的文件对象),也可以使用contextlib.redirect_stderr
重定向stderr
。
import os
import contextlib
with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
print("This won't be printed.")
发布于 2018-10-02 17:22:15
如果您想阻止由特定函数进行的打印调用,有一个使用装饰器的更简洁的解决方案。定义以下装饰器:
# decorater used to block function printing to the console
def blockPrinting(func):
def func_wrapper(*args, **kwargs):
# block all printing to the console
sys.stdout = open(os.devnull, 'w')
# call the method in question
value = func(*args, **kwargs)
# enable all printing to the console
sys.stdout = sys.__stdout__
# pass the return value of the method back
return value
return func_wrapper
然后只需将@blockPrinting
放在任何函数之前。例如:
# This will print
def helloWorld():
print("Hello World!")
helloWorld()
# This will not print
@blockPrinting
def helloWorld2():
print("Hello World!")
helloWorld2()
https://stackoverflow.com/questions/8391411
复制相似问题