简体   繁体   中英

Running a python script from another script

I wish to a run a python script which takes 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 (ie 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM