Idiom for running compiled python scripts?

irstas at irstas at
Sat Mar 24 15:21:21 CET 2007

On Mar 23, 9:30 am, Mark <markb... at> 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" 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.
''.rstrip('.py') == 'pyx'

Answering also to your later message:

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

Curiously enough, Python 2.5 has a module called runpy:

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__'
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 +
    import compiler
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
faster than running .py. The file had 600 lines (21kb) of code.

More information about the Python-list mailing list