call one python script from within another

François Pinard pinard at iro.umontreal.ca
Fri Jul 11 19:38:44 EDT 2003


[Tubby Tudor]

> What is the best way to call one python script from within another python
> script?  For example: one.py finishes succesfully and calls two.py which
> finishes OK and then calls three.py

I do not know if my way is the best way :-), but the following goes fine for
us.  Each of our programs is installed (through `distutils') as a small
bootstrap, on the loader search path, looking like:

---------------------------------------------------------------------->
#!/usr/bin/env python
# [...]

"""\
SHORT_DESCRIPTION.
"""

import sys
from PACKAGE.MODULE import main
main(*sys.argv[1:])
----------------------------------------------------------------------<

and within the main MODULE for the PACKAGE holding the application, we have:

---------------------------------------------------------------------->
#!/usr/bin/env python
# [...]

"""\
LONGER_DESCRITPION.
"""

[...]

def main(*arguments):
    [...]

if __name__ == '__main__':
    main(*sys.argv[1:])
----------------------------------------------------------------------<

We often use this instead, when the complexity warrants it:

---------------------------------------------------------------------->
#!/usr/bin/env python
# [...]

"""\
LONGER_DESCRITPION.
"""

[...]

class Main:
    [...]

    def main(self, *arguments):
        [...]

run = Main()
main = run.main

[...]

if __name__ == '__main__':
    main(*sys.argv[1:])
----------------------------------------------------------------------<

So very systematically, one may call any `main' giving, as string arguments,
what would be successive arguments in a shell command calling that program.

When a Python program needs to "execute" another Python program, it often
does something like:

---------------------------------------------------------------------->
    [...]
    import PACKAGE.MODULE
    PACKAGE.MODULE.main(ARGUMENT1, ARGUMENT2, ...)
----------------------------------------------------------------------<

The only reason we would prefer to `exec' or `fork' another Python process
would be to reclaim the storage taken by the imported package modules code,
in the rather unusual cases it would matter.  As for the rest of the data,
we merely rely on the garbage collector.

If we were in your situation, it is likely that a small driver would
successively call the three programs as above, one after the other.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list