简体   繁体   中英

Python run another script from a python script

def run_cmd(self, cmd):
    print cmd 

    status = os.system(cmd)
    print 'Command ran with Status: %s' % status

    if status:
        s = 'Command Failed: Status: %s for %s' % (status, cmd)
        print s
        sys.exit(status)
    else:
        s = 'Command Success: %s' % cmd 

    return status

I am using this function to run a python script from another script.

Ex:

command_to_exec = 'python script_b.py'
run_cmd(command_to_exec)

Now if script_b.py fails script_a.py exits with the status.

That's okay.

Case 2 :

command_to_exec = 'python script_a.py --options'
rum_cmd(command_to_exec)

This case is script_a.py running 'python script_a.py' from itself. In this case, if newly spawned script_a.py fails, the outer script_a.py is still a success, because it wasn't able to catch the failure of inner script_a.py (because of sys.exit(status))

Now, how do I handle this situation? (If inner script_a fails, outer script_a should exit)

You can just run your other script as a module. Let's say you have the folder:
dir
|---main.py
|---imported.py
And you want to run the second from the first. Just use import , like that:

import imported #the file name without the extension

It will run that file, and you will be able to use it's vars and functions in your main script.

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