Python - >用打印语句告诉程序“不打印”

Python - >用打印语句告诉程序“不打印”

问题描述:

我目前正在学习Python,并开始了一个项目,为2000-2005 MLB对决牌游戏创建一个棒球模拟器。这些程序包含棒球比赛的事件,作为单独代码中间的打印语句(“杰夫命中一个单一”,“博比命中一个飞球”等)。如果我想一次运行很多游戏,我经常会拿出打印报表。出于可行性原因,我的目标是告诉Python不要打印某些语句(比如说,在特定的行范围内),即使代码显示为“”。这可能吗?Python - >用打印语句告诉程序“不打印”

例如:

while numberofgames < 1000: 
    [do not print any statements here] 
    ---baseball games--- 
end of while loop 

THEN:打印仿真结果

+0

难道你不能仅仅评论打印行吗? – Pikamander2

+0

所有可能发生的不同事件都有很多打印行。我想知道是否有一个简单的方法来告诉它停止打印行,然后单独进行并将它们评论出来。 –

+3

使用'logging'模块而不是'print'语句来控制何时何地产生输出。 – chepner

是的,你可以把所有的打印语句到if结构如..

if printStuff: 
    print 'I dont like baseball' 
    print 'I love it!' 

然后,它仅仅是一个如果您想打印,请将printStuff设置为True,如果您不打印,则设置为False

您可以使用全部替换来替换print(#print(

当您准备再次打印时,您可以做相反的事情:将#print(替换为print(

您可以创建一个全局变量,您可以检查以确定要打印多少?通过这样做,您可以根据需要控制日志记录的数量。

if printLevel > 3: 
     print("Bobby hits a fly ball for an out") 
+0

谢谢!我打算使用这种方法,因为它提供了用于显示打印语句的最大灵活性。每个人的评论和回答都很有帮助,所以大家都谢谢大家! –

一个黑客,当然,但为什么不重写一段时间的打印功能?

#the line below needs to be the first in the file 
#and is required on Python 2.7 
from __future__ import print_function 

def to_null(*args, **kwds): 
    pass 

def test1(x): 
    print ("test1(%s)" % (x)) 


#override the print 
old_print = __builtins__.print 
__builtins__.print = to_null 

test1("this wont print") 

#restore it 
__builtins__.print = old_print 

test1("this will print") 

输出:

test1(this will print) 

也参见Is it possible to mock Python's built in print function?

最后,建议使用记录模块是斑点上。尽管该模块使用起来可能会非常棘手。