Better solution than if __name__ == '__main__' twice in Python script

后端 未结 1 1476
梦如初夏
梦如初夏 2021-01-15 17:48

I have multiple Python scripts which use docopt.

My issue is that the available options for the two scripts differ slightly - one option is present in one script, bu

相关标签:
1条回答
  • 2021-01-15 18:27

    The clean solution is to refactor your code so it doesn't rely on a global, neither in main.py nor module1.py:

    """
    main.py
    
    Usage:
        main.py [--num=<num>] [--name=<name>]
        main.py -h | --help
        main.py --version
    
    Options:
        --num=<num>  A number
        --name=<name>  A name
        --version
    """
    from other_file import x, y
    from module1 import function
    
    
    def main(num):
        print 'In main()'
        function(num)
        print num
    
    
    if __name__ == '__main__':
        import docopt
    
        arguments = docopt.docopt(__doc__, version=0.1)
        NUM = arguments['--num']
    
        print '{} being executed directly'.format(__name__)
        main(NUM)
    

    And:

    """
    module1.py
    
    Usage:
        module1.py [--num=<num>]
        module1.py -h | --help
        module1.py --version
    
    Options:
        --num=<num>  A number
        --version
    """
    from other_file import z
    
    
    def main(num):
        print 'In main()'
        print num
    
    
    def function(num):
        print 'In function in {}'.format(__name__)
        print num
    
    
    if __name__ == '__main__':
        import docopt
    
        arguments = docopt.docopt(__doc__, version=0.1)
        NUM = arguments['--num']
    
        print '{} being executed directly'.format(__name__)
        main(NUM)
    
    0 讨论(0)
提交回复
热议问题