Reputation: 6186
I have the following code:
argpass = ['nohup']
argpass.append('/path/to/script')
log_output_err = open(log_file,'a+')
out = subprocess.Popen(argpass,
stdout = log_output_err,
stderr = log_output_err)
#if the script fails I need to have some logic here...
I just wonder how I can get the return code of the /path/to/script.
Maybe I just need to insert the logic in /path/to/script, any thoughts?
Thanks,
Upvotes: 1
Views: 5779
Reputation: 6007
The subprocess.Popen
object has a returncode
attribute you can access:
http://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode
You could also look at using the check_call
convenience function:
http://docs.python.org/2/library/subprocess.html#subprocess.check_call
It will only return if the return code was zero; otherwise, it will raise a CalledProcessError
(from which you may read the returncode
attribute).
Your example, with stdout and stderr pointing back at the invoking Python script rather than a log file:
>>> import subprocess
>>> argpass = ['echo']
>>> argpass.append('hello world')
>>> # I reroute to PIPE because I don't have a logfile
>>> log_output_err = subprocess.PIPE
>>> out = subprocess.Popen(argpass,
stdout = log_output_err,
stderr = log_output_err)
>>> output,error = out.communicate()
>>> print output
hello world
>>> # Check if child process has terminated.
>>> # If it has finished, will return returncode attribute.
>>> # Otherwise, it returns None
>>> out.poll()
0
>>> # Or we can read the returncode attribute directly:
>>> out.returncode # Direct
0
>>>
If your process will take a long time to finish, the returncode
value might not be set when you go to check it. If the value of the returncode
is None
that means your child process has not yet terminated. You can stop execution of your script until after the child process has terminated with the .wait()
method.
Upvotes: 4