【问题标题】:Python -> Telling a program with print statements to "not print"Python -> 用打印语句告诉程序“不打印”
【发布时间】:2015-08-08 19:29:31
【问题描述】:

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

示例:

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

THEN:打印模拟结果

【问题讨论】:

  • 不能把打印行注释掉吗?
  • 对于可能发生的所有不同事件有很多打印行。我想知道是否有更简单的方法来告诉它停止打印行,然后单独通过并注释掉它们。
  • 使用logging 模块而不是print 语句来控制何时何地产生输出。
  • 我认为日志系统非常适合用于例如为开发人员准备的消息,但从消息示例看来,这些似乎应该在控制台上发送给用户,我会说某种形式的print 应该更适合。

标签: python printing


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我将使用这种方法,因为它提供了最大的灵活性来显示打印语句。大家的cmet和答案很有帮助,谢谢大家!
【解决方案2】:

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

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

如果你想打印,只需将printStuff设置为True,如果你不想打印,只需设置False即可。

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 当打印语句在我们无法触摸代码的第三方库中时非常有用的答案
    【解决方案4】:

    您可以使用 Replace All 将 print( 替换为 #print(

    当您准备好再次打印时,您可以执行相反的操作:将 #print( 替换为 print(

    【讨论】:

      【解决方案5】:

      当然是 hack,但为什么不暂时覆盖打印功能呢?

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

      最后,使用日志模块的建议很明确。尽管该模块很难很好地使用。

      【讨论】:

        【解决方案6】:

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

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

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

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

        级别 --------- 数值

        临界 ---50

        错误 ----- 40

        警告 --30

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

        调试 -----10

        NOTSET -----0

        您为消息分配一个级别。例如,logging.info("Debug") 是一个 INFO 级别的消息,它打印 "Debug"。如果logger的level小于等于message的level,就会打印message。

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-17
          • 2014-03-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多