Is there a better way to print only when run as a script, when __name__ == '__main__'?
I have some scripts that I also import and use.
Something like below will work, but it will be ugly and needs to be defined in each script separately:
def printif(s):
if globals()['__name__'] == '__main__':
print (s)
return
I looked briefly at some python protocol libraries, but would prefer two lighter solutions ...
edit:
I ended up doing something like this:
# mylog.py
import sys
import logging
log = logging.getLogger()
#default logging level
log.setLevel(logging.WARNING)
log.addHandler(logging.StreamHandler(sys.stdout))
And from the script:
import log from mylog
...
log.info(...)
log.warning(...)
...
if __name__ == '__main__':
log.setLevel(logger.INFO)
This scheme has minimal code duplication, per script log levels and default level for the whole project ... which is exactly what I wanted.
source
share