Question

I am trying to make a program "main" that calls other programs that, when finished, return to main. I would like to be able to repeatedly call the same programs. The problem is if I called a program using "import" the first time it doesn't work when I do it a second time.

main:

main = input("What option would you like?")

if main == 1:
    import proga
elif main == 2:
    import progb
else:
    import probc

more = input("Would you like more?")
if more == 'y':
    import main
else:
    print "Have a nice day!"

proga: calculate this print this

progb: calculate that print that

etc.

When I respond 'y' to the "more" question it will reply the "main = input" part but if I choose an option I've already chosen it won't play it because it's already been imported. Is there another method I can do to play the programs again? Should I use execfile? os.system? Thank you!

Was it helpful?

Solution

Try execfile() for Python 2 and under:

execfile("proga.py", {})

For later versions (Python 3+), try this:

exec(compile(open(filename, "rb").read(), "proga.py", 'exec'))

OTHER TIPS

Repeatedly calling a program is not very efficient. As well, for something like your example, calling another program is completely unnecessary. The best way to do this is to write proga and progb as functions, and then import them into your main program. After that, call the functions.

More information here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top