0

Now Consider the following idea I'm declaring a if/elif type to run the program Such as :

number=int(input("Enter a number :"))

If number ==0
Run program.py

Elif number ==1
Run Program2.py

Else number ==2
Run Program3.py

Now clearly the command run program.py doesn't work so what should I do to make it execute program.py incase it is selected and close the main program where we are choosing the number?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

2 Answers2

2

There are several ways to run external code. There is subprocess and os.system() to run any other program on the disc, then there is exec to run a code you have as a string or code object, then there is eval that is kinda similar to exec but accepts only a string and allows to supply globals and locals. Those are all builtins.

But you probably don't really want to run external scripts as scripts. It creates all sorts of problems with correctly passing sys.argv to them, and making sure they get correct stdin/stdout and everything. Nine times out of ten you're better off creating a series of functions (perhaps in other files), importing them and calling those.

Synedraacus
  • 975
  • 1
  • 8
  • 21
0

You should consider to learn about subprocesses: https://docs.python.org/3/library/subprocess.html

Popen option is one of the most useful ones for stuff like that.

number=int(input("Enter a number :"))
If number == 0:
  subprocess.Popen([sys.argv[0], param]) 
Elif number ==1:
  subprocess.Popen([program2.py, param]) 
Else number ==2:
  subprocess.Popen([program3.py, param]) 

Note: Number 0 would open the same file you are using to call the new processes, just in case you ever need to "clone" your own program.

Edit: Linux and windows will require you to do this differently, as:

if platform.system() == "Linux":
  subprocess.Popen([sys.argv[0], param])
else:
  subprocess.Popen(["python", sys.argv[0], param])
Saelyth
  • 1,694
  • 2
  • 25
  • 42