How about some syntactic sugar for " __name__ == '__main__' "?

Ethan Furman ethan at stoneleaf.us
Mon Dec 1 19:45:03 EST 2014


On 12/01/2014 03:19 PM, Ethan Furman wrote:
> 
> Well, I've tried this out, and it's only okay.  As soon as interesting things start happening, spurious errors about 
> thread IDs start printing, which really messes up the user experience [...]

So here's another thought:  Have a small python script that loads and runs the actual script -- here's a POC:

--- 8< py_main ------------------------------
    #!/usr/bin/env python

    import sys
    sys.argv.pop(0)

    try:
        execfile
    except NameError:
        def execfile(file_name, globals):
            with open(file_name) as fh:
                script = fh.read()
            exec(fh, globals)

    module = {}
    execfile(sys.argv[0], module)
    module['main']()
---------------------------------------------

Put the above somewhere in your path (e.g. /usr/local/bin), make it executable, and then instead of shebanging your
scripts with `/usr/local/bin/python` you can use `/usr/local/bin/py_main`, which will load and execute the script,
calling script.main as its last act.

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20141201/e831677a/attachment.sig>


More information about the Python-list mailing list