禁止调用打印(python)

2024-05-17 05:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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


我正在使用^{}模块制作一个游戏。

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

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


Tags: 模块对象函数游戏get检查用户成员button
3条回答

正如@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.")

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()。如果要禁用全部打印,请在文件顶部开始阻塞。

基于@fakerainbrigan解决方案,我建议一个更安全的解决方案:

import os, sys

class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, 'w')

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._original_stdout

然后你可以这样使用它:

with HiddenPrints():
    print("This will not be printed")

print("This will be printed as before")

这更安全,因为您不能忘记重新启用stdout,这在处理异常时尤其重要。

# This is an example of not-so-good solution
# without 'with' context manager statement.
try:
    disable_prints()
    something_throwing()
    # enable_prints() This wouldn't be enough!
except ValueError:
    handle_error()
finally:
    enable_prints() # That's where it needs to go.

如果您忘记了finally子句,那么您的print调用将不再打印任何内容。使用with语句,这是不可能的。

使用sys.stdout = None是不安全的,因为有人可以调用sys.stdout.write()等方法

相关问题 更多 >