Does printing only work with a script?

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__':
    #override when script is run..
    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.

+3
source share
3 answers

:

import logging

log = logging.getLogger('myscript')

def dostuff(...):
    ....
    log.info('message!')
    ...

if __name__ == '__main__':
    import sys
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler(sys.stdout))
    ...

- ": , myscript", , ( script) . Python 3.2. Python 2.7 ,

log.addHandler(logging.NullHandler())

, NullHandler :

class NullHandler(logging.Handler):
    def emit(self, record):
        pass    

, : . , .

0
run_as_script = False  

def printif(s):  
    if run_as_script:  
        print (s)
    return

if __name__ == '__main__':  
    run_as_script = True
+5

318904 ( , " " ).
:

import sys

def printif(s):
    if sys.argv[0] != '':
        print (s)
+1

Source: https://habr.com/ru/post/1780126/


All Articles