簡體   English   中英

Python - >將帶有打印語句的程序告訴“不打印”

[英]Python -> Telling a program with print statements to “not print”

我正在學習Python,並開始為2000-2005 MLB攤牌紙牌游戲創建一個棒球模擬游戲。 這些程序包含棒球比賽的事件,作為單獨代碼片段中的打印語句(“傑夫擊中單個”,“鮑比擊出飛球出去”等)。 如果我想一次運行很多游戲,我經常會刪除打印語句。 出於可行性的原因,我的目標是告訴Python不打印某些語句(例如,在特定的行間距內),即使代碼顯示為print“”。 這可能嗎?

例:

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

那么:打印模擬結果

你能創建一個全局變量,你可以檢查它來決定你想要打印多少? 通過這樣做,您可以根據需要控制日志記錄量。

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

是的,您可以將所有打印語句放入if結構中,例如..

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

那么只需將printStuff設置為True即可打印,如果不打印則設置為False

您可以使用全部替換來替換print(使用#print(

當你准備再次打印時,你可以做相反的事情:替換#print(print(

您可以使用日志記錄模塊:

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

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

日志記錄模塊有幾個不同的級別。

等級---------數值

關鍵--- 50

錯誤----- 40

警告--30

信息--------- 20

DEBUG ----- 10

注意----- 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

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())

黑客,當然,但為什么不暫時覆蓋打印功能?

#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)

另請參見模擬Python的內置打印功能嗎?

最后,建議使用日志記錄模塊。 雖然該模塊使用起來可能很棘手。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM