如何阻止调用打印? [英] How to block calls to print?

查看:45
本文介绍了如何阻止调用打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法阻止函数调用print?

Is there a way to stop a function from calling print?

我正在使用 pygame.joystick 模块我正在开发的游戏.

I am using the pygame.joystick module for a game I am working on.

我创建了一个 pygame.joystick.Joystick 对象,并在游戏的实际循环中调用其成员函数 get_button 来检查用户输入.该函数完成了我需要它做的所有事情,但问题是它还调用了 print,这大大减慢了游戏速度.

I created a pygame.joystick.Joystick object and in the actual loop of the game call its member function get_button to check for user input. The function does everything I need it to do, but the problem is that it also calls print, which slows down the game considerably.

我可以阻止这个对print的调用吗?

Can I block this call to print?

推荐答案

Python 允许您用任何文件对象覆盖标准输出 (stdout).这应该可以跨平台工作并写入空设备.

Python lets you overwrite standard output (stdout) with any file object. This should work cross platform and write to the null device.

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().如果您想禁用全部打印,请从文件顶部开始阻止.

If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.

这篇关于如何阻止调用打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆