有没有办法阻止函数调用 print
?
我正在使用 pygame.joystick
我正在开发的游戏的模块。
我创建了一个 pygame.joystick.Joystick
对象,并在游戏的实际循环中调用其成员函数 get_button
来检查用户输入。该函数完成了我需要它做的所有事情,但问题是它还调用了 print
,这大大降低了游戏速度。
我可以阻止这个对print
的调用吗?
最佳答案
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()
。如果您想禁用所有打印,请从文件顶部开始阻止。
关于python - 如何阻止调用打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8391411/