1

In my python3 script, I am calling an external program with the subprocess module. When the called program exits with a non-zero status code, a CalledProcessError is thrown. In that case I print an error message and want to terminate the script in the exception handler.

My problem is, that exit() works by throwing a SystemExit exception itself, so I end up with:

During handling of the above exception, another exception occurred:

The script looks similar to this:

try:
    output = subprocess.check_output(["program"])
    return output
except subprocess.CalledProcessError as error:
    print("program returned non-zero exit status", file=sys.stderr)
    exit(error.returncode)

How can I terminate the script without throwing an exception?

2
  • Why are you passing the error.returncode to exit() if you don't want it to propagate? Commented Jul 23, 2014 at 19:27
  • @mdurant I want to signal the exit code to the shell (which called this script). Commented Jul 23, 2014 at 19:40

1 Answer 1

2

os._exit Would allow you to quit without raising an exception, but I wouldn't recommend that approach, because it exits ungracefully; no cleanup will be done.

You could also tweak your logic of subprocess a bit, so that sys.exit gets called outside of the except block:

try:
    output = subprocess.check_output(["programm"])
    return output
except subprocess.CalledProcessError as error:
    print("programm returned non-zero exit status", file=sys.stderr)
    returncode = error.returncode
exit(returncode)  # You'll only reach this if an exception occurred.

That way you shouldn't get a traceback (though I actually can't reproduce getting the message you get, even if I leave the exit inside the except block).

Sign up to request clarification or add additional context in comments.

3 Comments

That way I don't get a During handling of the above exception, another exception occurred:, but I get a traceback nonetheless (from exit()), but I guess that's what exit() does - raising SystemExit.
@WilhelmSchuster What environment are you executing this code in? I don't normally see a traceback for a call to exit or sys.exit.
I was running it via python3 -i script.py (makes debugging easier). You're right, with python3 script.py no traceback is shown. Thanks.

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.