Print controlled with global-var - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Print controlled with global-var (/thread-36250.html) |
Print controlled with global-var - fmr300 - Feb-01-2022 In a script I'm working on, sometimes I'd like to turn off some of the print statements that are informative, while leaving the true-warning print's on. Is there a simple way to define a 'myPrint' function that can be globally controlled, and use that for the informative print's (see below)? Obviously this code only works for printing strings, not vars for instance. global printFlag def myPrint(s): global printFlag if printFlag: print(s) printFlag = True print("low on memory", mem_size) # always prints warning myPrint("trace-point reached at time", time() ) # prints debug info IF printFlag is True RE: Print controlled with global-var - deanhystad - Feb-01-2022 I think you would like logging. https://docs.python.org/3/howto/logging.html Your trace-point message would be logged at info level and the memsize message as warning() or error(). RE: Print controlled with global-var - Gribouillis - Feb-01-2022 You could try myPrint = print if printFlag else (lambda *args, **kwargs: None) RE: Print controlled with global-var - fmr300 - Feb-05-2022 (Feb-01-2022, 11:15 PM)Gribouillis Wrote: You could try Nice. Works perfectly, and reminds me how weak my overall Python skills are!! |