Running a python script from another script
I wish to a run a python script which takes开发者_如何学Go options and arguments from another python script.
For example run C:\\code\\old_start_training_generic_depth.py -i 10 -l 2 from C:\\code\\start.py
You can do that using subprocess.Popen
, which can be used to run any external process from your Python code (including other Python programs).
That said, I would do it otherwise. Since both programs are in Python, I would package the one you want to call as a module which can be invoked programmatically (i.e. imported and then called), instead of calling it as a subprocess. This may incur some small development cost but in the end I believe it will pay for itself, since this method has many advantages.
import subprocess
subprocess.Popen(['C:\\code\\old_start_training_generic_depth.py', '-i', '10', '-l', '2']).wait()
import subprocess
def runscript():
'''
Run a script
'''
cmd_list = ["python", r"C:\code\old_start_training_generic_depth.py", \
"-i", "10", "-l", "2"]
pipe = subprocess.Popen(cmd_list, stdin=subprocess.PIPE, \
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = pipe.communicate()
retcode = pipe.poll()
return (retcode, stdout, stderr)
C:\code\start.py:
import subprocess
subprocess.Popen(["python", r"C:\code\old_start_training_generic_depth.py", "-i", "10", "-l", "2"])
# once upon a time somewhere in the start.py
os.system("python C:\\code\\old_start_training_generic_depth.py -i 10 -l 2")
精彩评论