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

时间:2015-08-08 19:29:31

标签: python printing

我正在学习Python,并开始为2000-2005 MLB摊牌纸牌游戏创建棒球模拟游戏。这些程序包含棒球比赛的事件,作为单独代码片段中的打印语句(“杰夫击中单个”,“鲍比击出飞球出去”等)。如果我想一次运行很多游戏,我经常会删除打印语句。出于可行性的原因,我的目标是告诉Python不打印某些语句(例如,在特定的行间距内),即使代码显示为print“”。这可能吗?

示例:

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

然后:打印模拟结果

6 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

是的,您可以将所有打印语句放入if结构中,例如..

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

然后,如果您想要打印,请将printStuff设置为True,如果不打印则设置为False

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

您可以使用日志记录模块:

https://docs.python.org/3/library/logging.html

https://docs.python.org/3/howto/logging.html#logging-basic-tutorial

日志记录模块有几个不同的级别。

等级---------数值

关键--- 50

错误----- 40

警告--30

INFO --------- 20

DEBUG ----- 10

NOTSET ----- 0

您可以为某个级别分配消息。例如,logging.info("Debug")是INFO级别的消息,其中打印"Debug"。如果记录器的级别小于或等于消息的级别,则将打印该消息。

因此,如果您想关闭一堆打印语句,您只需将语句设置为相同级别,然后将记录器转到更高级别。

>>>import logging

>>>T=logging.getLogger()                 #create a new logger object
#Set the logger level to INFO - note basicConfig only works once!!!
#Then you must use setLevel method to change the level
>>>logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
>>>logging.info("INFO")                 #this prints because the logger is set to INFO
INFO:Info
>>>logging.warning("Warning")
WARNING:Warning

>>>T.setLevel(logging.WARNING)      #set the logger level to WARNING
>>>logging.info("Debug")            #Does not print since logger level WARNING is higher than message level INFO
>>>logging.warning("Warning")
WARNING:Warning

答案 4 :(得分:1)

Python的print输出到sys.stdout。您可以为STDOUT添加自己的缓冲区。

# assuming python3
import sys
import io

my_buffer = io.StringIO()
sys.stdout = my_buffer

# print some stuff
stuff_to_print = ['foo', 'word', 'test']
for word in stuff_to_print:
    print(word)

# all the other stuff your script does

# change stdout back to original so print is pointing back to original buffer
sys.stdout = sys.__stdout__

# now print everything out at once
print(my_buffer.get_value())

答案 5 :(得分: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?

最后,建议使用日志记录模块。虽然使用该模块可能很难使用。