Python - how do I call external python programs?

2019-01-26 04:03发布

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.

3条回答
劳资没心,怎么记你
2楼-- · 2019-01-26 04:32

Check out the subprocess documentation.

查看更多
甜甜的少女心
3楼-- · 2019-01-26 04:33

Also if you need to pass additional arguments do this:

import subprocess
subprocess.call(["python", "myscript.py", "arg1", "arg2", "argN"])
查看更多
迷人小祖宗
4楼-- · 2019-01-26 04:36

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.

查看更多
登录 后发表回答