切换 python 打印的最佳方法是什么? [英] What is the best way to toggle python prints?
问题描述
我在游戏引擎中运行 Python 2.4,如果需要,我希望能够关闭所有打印.例如,我想为调试版本打开打印,然后为发布版本关闭打印.它还必须尽可能透明.
I'm running Python 2.4 in a game engine and I want to be able to turn off all prints if needed. For example I'd like to have the prints on for a debug build, and then turned off for a release build. It's also imperative that it's as transparent as possible.
我在引擎的 C 代码中对此的解决方案是在 vararg
宏中包含 printf
函数,并将其定义为在发布版本中不执行任何操作.
My solution to this in the C code of the engine is having the printf
function inside a vararg
macro, and defining that to do nothing in a release build.
这是我目前的解决方案:
This is my current solution:
DebugPrints = True
def PRINT (*args):
global DebugPrints
if DebugPrints:
string = ""
for arg in args:
string += " " + str(arg)
print string
它可以轻松切换打印输出,但可能有更好的方法来格式化字符串.我的主要问题是这实际上是向程序添加了更多的函数调用.
It makes it easy to toggle print outs, but there is possibly a better way to format the string. My main issue is that this is actually adding a lot more function calls to the program.
我想知道您是否可以对 print 关键字的工作方式做些什么?
I'm wondering if there is anything you can do to how the print keyword works?
推荐答案
是的,您可以将 sys.stdout
分配给您想要的任何内容.用一个什么都不做的 write
方法创建一个小类:
yes, you can assign sys.stdout
to whatever you want. Create a little class with a write
method that does nothing:
class DevNull(object):
def write(self, arg):
pass
import sys
sys.stdout = DevNull()
print "this goes to nirvana!"
使用相同的技术,您还可以通过将 sys.stdout
设置为打开的文件对象来将打印记录记录到文件中.
With the same technique you can also have your prints logged to a file by setting sys.stdout
to an opened file object.
这篇关于切换 python 打印的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!