Python Forum
Print controlled with global-var
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Print controlled with global-var
#1
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
Reply
#2
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().
Reply
#3
You could try
myPrint = print if printFlag else (lambda *args, **kwargs: None)
BashBedlam likes this post
Reply
#4
(Feb-01-2022, 11:15 PM)Gribouillis Wrote: You could try
myPrint = print if printFlag else (lambda *args, **kwargs: None)

Nice. Works perfectly, and reminds me how weak my overall Python skills are!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Global variable does not seem to be global. Columbo 6 3,617 Jul-15-2019, 11:00 PM
Last Post: Columbo
  How to print a global dictionary class properly 3dimensions 2 3,185 Apr-18-2018, 05:45 PM
Last Post: nilamo
  If/ Or if/ temp controlled fan. clueless 5 3,989 Dec-25-2017, 03:21 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020