How to prevent __main__ protection from starting when using execfile?

BDFL published an article in 2003 on how to write a basic Python function . His example is this:

import sys
import getopt

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
             raise Usage(msg)
        # more code, unchanged
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":
    sys.exit(main())

The reason for the optional argument argvto main()is: "We are changing main()to take an optional argument argvthat allows us to call it from an interactive Python prompt."

He explains the last line of his code as follows:

Now the challenges are sys.exit()annoying: when main()called sys.exit(), your interactive Python interpreter will exit! The tool is permission. The main()return value indicates the exit status. Thus, the code at the very end becomes

if __name__ == "__main__":
    sys.exit(main())

sys.exit(n) main() return n.

, Guido Spyder, . ? import, main(), execfile runfile? , , , , , , import foo reload(foo).

, SystemExit getopt , , Python , , BDFL.

+4
2

execfile __name__ :

execfile('test.py', {'__name__': 'test'})

script, , __name__ __main__.

, , import.

+9

, , , . , , , - :

if __name__ == "__main__":
    if 'PYTHONSTARTUP' in os.environ:
        try:
            main() # Or whatever you want to do here
        except SystemExit as se:
            logging.exception("")
    else:
        sys.exit(main())
0

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


All Articles