What is the best way to toggle python prints?

前端 未结 6 1106
一个人的身影
一个人的身影 2021-01-12 06:28

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 turn

6条回答
  •  长发绾君心
    2021-01-12 07:11

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

    With the same technique you can also have your prints logged to a file by setting sys.stdout to an opened file object.

提交回复
热议问题