首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何阻止调用打印?

如何阻止调用打印?
EN

Stack Overflow用户
提问于 2011-12-06 04:26:55
回答 10查看 103.3K关注 0票数 102

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

我正在为一个正在开发的游戏使用pygame.joystick模块。

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

我可以阻止此对print的调用吗

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2011-12-06 04:54:23

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

代码语言:javascript
复制
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()。如果要禁用所有打印,请从文件顶部开始阻止。

票数 135
EN

Stack Overflow用户

发布于 2017-09-09 17:53:35

正如@Alexander Chzhen建议的那样,使用上下文管理器将比调用一对状态更改函数更安全。

但是,您不需要重新实现上下文管理器-它已经在标准库中。您可以使用contextlib.redirect_stdout重定向stdout ( print使用的文件对象),也可以使用contextlib.redirect_stderr重定向stderr

代码语言:javascript
复制
import os
import contextlib

with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
    print("This won't be printed.")
票数 55
EN

Stack Overflow用户

发布于 2018-10-02 17:22:15

如果您想阻止由特定函数进行的打印调用,有一个使用装饰器的更简洁的解决方案。定义以下装饰器:

代码语言:javascript
复制
# 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放在任何函数之前。例如:

代码语言:javascript
复制
# This will print
def helloWorld():
    print("Hello World!")
helloWorld()

# This will not print
@blockPrinting
def helloWorld2():
    print("Hello World!")
helloWorld2()
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8391411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档