Idiom for running compiled python scripts?

irstas at gmail.com irstas at gmail.com
Sat Mar 24 10:21:21 EDT 2007


On Mar 23, 9:30 am, Mark <markb... at mailinator.com> wrote:
> A small script called "python_compile_and_run" in "pseudo" code:
>
> #!/usr/bin/env python
> import sys
>
> # Following is invalid syntax unfortunately :(
> from sys.argv[1].rstrip('.py') import main
>
> sys.argv = sys.argv[1:]
> if __name__ == "__main__":
>     main()
>
> so I could just do a "python_compile_and_run myscript.py" and it would
> do what I want, i.e. run myscript.pyc if available and valid, generate
> and run it if necessary.

There's __import__ which allows you to do what you tried:

m = __import__(sys.argv[1].rstrip('.py'))

Also, rstrip doesn't work like you think it does.
'pyxyypp.py'.rstrip('.py') == 'pyx'

Answering also to your later message:

> So the general purpose invoking bash script e.g. "runpy" is merely something
like:

Curiously enough, Python 2.5 has a module called runpy:
http://docs.python.org/lib/module-runpy.html

which seems to almost do what you want. It doesn't compile the modules
but you could make a modification which does. The benefit over just
using __import__("module").main() would be
that your scripts wouldn't necessarily need a function called "main",
but would still work with scripts that use the __name__ == '__main__'
idiom.
A simple implementation that "works":


import imp, sys, os
c = sys.argv[1]
if not os.path.exists(c + 'c') or os.stat(c).st_mtime > os.stat(c +
'c').st_mtime:
    import compiler
    compiler.compileFile(c)
del sys.argv[0]
imp.load_compiled('__main__', c + 'c')


I timed it against running plain .py and running .pyc directly.
It seemed to be roughly on par with running .pyc directly, and about
18ms
faster than running .py. The file had 600 lines (21kb) of code.




More information about the Python-list mailing list