Search code examples
pythoncallexternal

Python - how do I call external python programs?


I'll preface this by saying it's a homework assignment. I don't want code written out for me, just to be pointed in the right direction.

We're able to work on a project of our choice so I'm working on a program to be a mini portfolio of everything I've written so far. So I'm going to make a program that the user will input the name of a program (chosen from a given list) and then run the chosen program within the existing shell.

However, I can't really find information on how to call upon external programs. Can anyone point me in the right direction? I considered putting all the code in one long program with a bunch of if loops to execute the right code, but I'd like to make it a BIT more complicated than that.


Solution

  • If you want to call each as a Python script, you can do

    import subprocess
    subprocess.call(["python", "myscript.py"])
    subprocess.call(["python", "myscript2.py"])
    

    But a better way is to call functions you've written in other scripts, like this:

    import myscript
    import myscript2
    
    myscript.function_from_script1()
    myscript2.function_from_script2()
    

    Where function_from_script1() etc are defined in the myscript.py and myscript2.py files. See this page on modules for more information.