1
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)

3
  • 2
    Why are you calling whole scripts like this? Why not import the 'inner' script, or the parts of it you need, and run those? Like why not call a function in the 'inner' script? Commented May 9, 2016 at 4:50
  • Use may use subprocess docs.python.org/2/library/subprocess.html#replacing-os-system Commented May 9, 2016 at 4:52
  • You could test sys.argv[0] to prevent running yourself, which could cause a horrible fork bomb (continually spawning process). Commented May 9, 2016 at 5:42

1 Answer 1

0

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.

1
  • It's not possible in my case because I have different options to give to the spawned script. Commented May 9, 2016 at 7:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.