A Newbie Question: How To Call Other Python Programs From A Main Python Program.
Trent Mick
trentm at ActiveState.com
Mon Dec 11 11:39:38 EST 2000
On Mon, Dec 11, 2000 at 04:01:52PM +0000, 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.
That is because an import call in Python will only execute (if that is the
correct term) the top-level Python code in that module the first time. The
module information is effectively cached after that. You *can* use the reload
function to force a reload of your modules, however the best way to set this
up is probably to change your Python programs so that their functionality is
in a function and then have you menu program run that function each time. So:
-------- func1.py ------------
def DoIt():
print "hello from func1.py"
if __name__ == "__main__":
# this is a magical way to get DoIt() to run only when func1.py
# is run from the command line, this block is *not* run when you
# "import func1" from another Python program.
DoIt()
------------------------------
-------- func2.py ------------
def DoIt():
print "hello from func2.py"
if __name__ == "__main__":
DoIt()
------------------------------
------------- menu.py ---------------------------------------
import func1, func2
import sys
if len(sys.argv) == 0:
print "error: must have one argument"
elif sys.argv[0] == "func1":
func1.DoIt()
elif sys.argv[0] == "func2":
func2.DoIt()
else:
print "error: unrecognized function name:", sys.argv[0]
------------------------------------------------------------
Then try running:
python func1.py
python menu.py func1
python menu.py func2
Hope that helps,
Trent
--
Trent Mick
TrentM at ActiveState.com
More information about the Python-list
mailing list