Is there a way to make a program which executes other programs? I was creating a project for school then I had an idea of creating a main program which will run different program according to my choice. I am using VS code and I created 2 programs in same folder(Here is the screenshot in case you are confused):
Here as you can see I have 2 programs(one is rockpaper.py and other is pass.py) inside of a folder named (ROCKPAPER) is there a way I can run both of these program by making another program inside of this same folder(ROCKPAPER)???? Is there a module for this?
CodePudding user response:
The best practice is to import the two programs in a 3rd one like
import pass
import rockpaper
which will execute those codes.
CodePudding user response:
No module is needed, this is basic functionality and you can simply import your sub-scripts into the main script.
import rockpaper
import pass
to run them, simply write
rockpaper
pass
CodePudding user response:
rock.py
def stone():
return ('This is rock')
paper.py Note here I have imported rock and assigned rock's result to a variable
import rock
def papyrus():
return ("This is paper")
scissors.py Note here, I got rock and paper imported and their return values are being printed from this file.
import rock
import paper
def sharp():
rocke = rock.stone()
papery = paper.papyrus()
print(f"{rocke} {papery} But I am a scissors")
if __name__ == "__main__":
sharp()
Output:
This is rock This is paper But I am a scissors
Process finished with exit code 0
You should really be studying these basics though.
CodePudding user response:
Here's a short "driver" program you can put in the same folder as the others. What it does is create menu of all the other Python script files it finds in the same folder as itself and asks the user to pick one. If the user enters number of on those listed, it then runs the script and quits.
from pathlib import Path
import subprocess
import sys
filepath = Path(__file__)
current_folder = filepath.parent
this_script = filepath.name
print(f'{this_script=}')
print(f'{current_folder=}')
scripts = [script for script in current_folder.glob('*.py') if script != filepath]
menu = sorted(script.stem for script in scripts)
print('Available programs:')
for i, script in enumerate(menu, start=1):
print(f' {i:2d}. {script}')
while True:
choice = input('Which program would you like to run (or 0 to quit)? ')
try:
choice = int(choice)
except ValueError:
print("Sorry, did not understand that.")
continue
if choice in range(len(menu) 1):
break
else:
print("Sorry, that not a valid response.")
continue
if choice:
print(f'Running program {menu[choice-1]}')
subprocess.run([sys.executable, f'{scripts[choice-1]}'])

