0

So I have multiple Python files, each file being their own console application providing several options to the user. file1.py, file2.py, file3.py etc.

I have another file called menu.py. Within this file I want to offer the user the option to run one of the other python files i.e.

option = input("Enter file name to run: ")
if option == "file1": #Code to open file

My code would be a lot cleaner than this, but hopefully you understand the point I am trying to get to.

AJnzxv1
  • 13
  • 3
  • 1
    Would this answer your question? https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script – Phoenix Apr 16 '20 at 18:09

3 Answers3

0

I believe you are looking for os.system()

You can run a command by

command = 'python3 file1.py'
os.system(command)
Nicha Roj
  • 60
  • 1
  • 7
0

This answer is attributed to @balpha and @fantastory.
If you are using Python 2, use

execfile("test2.py")

If using Python 3, use

exec(open("test2.py").read())

You also might want to see the docs on how namespaces are handled.

Phoenix
  • 188
  • 1
  • 15
0

Adding to Josh's answer.

For the cleanest solution, you should use import statements to pull code from another file. The way to achieve this would be for each file to have a main function that will serve as an interface. In addition, I also recommend using argparse if the files are command line programs.

If there is only 1 file to be called at a time, the program could look something like:

import argparse

import file1
import file2

parser = argparse.ArgumentParser(description='Run some files')
parser.add_argument('--file', type=str, dest='file', help='file name', required=True)
parser.add_argument('--options', dest='options', nargs='+')

args = parser.parse_args()

print(args.file)

if args.file == 'file1':
    if args.options:
        file1.main(*args.options)
    else:
        file1.main()
elif args.file == 'file2':
    if args.options:
        file2.main(*args.options)
    else:
        file2.main()

file1.py might look like:


def main(*options):
    print('File 1', options)

And you call it like this: python3 menu.py --file file1 --options option1 option2