A Newbie Question: How To Call Other Python Programs From A Main Python Program.

Tim Hochberg tim.hochberg at ieee.org
Mon Dec 11 11:21:22 EST 2000


<jbranthoover at my-deja.com> wrote:
> Hello All,
> I have written several small Python programs.  These programs
> are not just functions but complete programs with their own menuing
> systems.
>
>         My question is,  how do I (and is it a good idea) call these
> independent Python programs from one main program that selects which
> program to run from a main menu?  I tried to use the import command.
> This seems to work OK except that the programs only run once.  If the
> same program is selected from the menu,  nothing happens.  It seems to
> return immediately without running the program.

I suspect that your subprograms are organized like:

# subprogram_1
#....
fire_up_menus_and_get_going()

Modules that you import only get executed on the first import and are then
cached for speed reasons. This is why you see the behaviour you do. You
could get around this by playing tricks with reload, but that would not be
"the right thing to do"(TM). Instead, reorganize your subprograms as
follows:

# subprogram_1
#....
def run():
    fire_up_menus_and_get_going()
if __name__ == "__main__"
    run()

And then access them from your main program using:

import subprogram_1
subprogram_1.run()

This should run your program afresh everytime it is called. The 'if __name__
== "__main__"' line runs the subprogram only if invoked from the command
line.

-tim








More information about the Python-list mailing list