Reputation: 30735
I use subprocess to run a script. But that called script itself uses subprocess to execute some commands. The problem is that when I catch the exception in the outer script, it just says that there was an error in the called script.
So, my question is how can I propagate the error from the inner script to the outer script, so that I know the exact reason of what happened in the inner script.
This is how I catch exceptions and exit on error, with subprocess.
try:
output = subprocess.check_output(cmd)
except Exception as e:
print(str(e))
sys.exit(1)
Upvotes: 3
Views: 1559
Reputation: 5319
If you use the subprocess
python module, you are able to handle the STDOUT, STDERR and return code of command separately. You can see an example for the complete command caller implementation. Of course you can extend it with try..except
if you want.
The below function returns the STDOUT, STDERR and Return code so you can handle them in the other script.
import subprocess
def command_caller(command=None)
sp = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
out, err = sp.communicate()
if sp.returncode:
print(
"Return code: %(ret_code)s Error message: %(err_msg)s"
% {"ret_code": sp.returncode, "err_msg": err}
)
# You can raise an error if the return code of command is not zero.
# raise Exception(
# "Return code: %(ret_code)s Error message: %(err_msg)s"
# % {"ret_code": sp.returncode, "err_msg": err}
# )
return sp.returncode, out, err
Upvotes: 2