python calling python

Alex Martelli alex at magenta.com
Tue Aug 22 12:02:28 EDT 2000


"Larry Whitley" <ldw at us.ibm.com> wrote in message
news:8nu4i7$14hu$1 at news.rchland.ibm.com...
> I'm sure the answer to this is straightforward, but I can't find it in the
> documentation.
>
> How does one call python from python?  For example:  If the main() in
> myProgram1.py wants to call the main() in myProgram2.py with parameters,
> what incantation should it use?

I'm not quite sure what you mean.  If, by 'main()', you mean an
actual function thus called, then it will be something like:

-- myProgram1.py:

def main(some,parms):
    import myProgram2
    myProgram2.main('other','parameters')

-- myProgram2.py:

def main(someother, args):
    print someother, args

-- end

but, from what you say below, it doesn't seem that it's about this...:


> I'm trying to use ...
>
> os.system( "python /myPath/myProgram2.py -myparm1 xxx -myparm2 yyy" )
>
> ...from myProgram1 but it doesn't seem to work.  (It appears to re-enter
> main() in myProgram1 with myProgram2's parms).

This should run a completely different process and I don't see how
myProgram1.py's "main" could be re-entered, whatever exactly you mean
by this.

Anyway, the code that runs when you do "python pip.py" is the "free"
code that does not belong to any function or class; this code is also
run when you "import pip" from another Python program.  Sometimes,
one protects part of such code (and makes it easily executable from
the outside as above) with the idiom:

def main():
    pass
    # whatever you'd otherwise have as 'free code'...

if __name__=='__main__':
    main()

The 'if' is only satisfied if this is run directly from Python rather
than imported from another Python program.  But if you've used this
idiom, then import-then-call is the best way to run from the outside.

Program arguments are placed in the list sys.argv.  Just import sys,
save the sys.argv in some local variable if you will require it again,
then set it to whatever you want it to be for the purpose of calling
the other program, before you do the import-and-call-main thing.


Alex






More information about the Python-list mailing list