Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit code when python script has unhandled exception

I need a method to run a python script file, and if the script fails with an unhandled exception python should exit with a non-zero exit code. My first try was something like this:

import sys
if __name__ == '__main__':
    try:
        import <unknown script>
    except:
        sys.exit(-1)

But it breaks a lot of scripts, due to the __main__ guard often used. Any suggestions for how to do this properly?

like image 451
pehrs Avatar asked Mar 28 '11 08:03

pehrs


People also ask

How do you exit a Python script exception?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

How do you handle unhandled exception in Python?

An unhandled exception displays an error message and the program suddenly crashes. To avoid such a scenario, there are two methods to handle Python exceptions: Try – This method catches the exceptions raised by the program. Raise – Triggers an exception manually using custom exceptions.

What does exit 0 do in Python?

The function calls exit(0) and exit(1) are used to reveal the status of the termination of a Python program. The call exit(0) indicates successful execution of a program whereas exit(1) indicates some issue/error occurred while executing a program.

How do you write an exit code in Python?

Exit Codes in Python Using sys The sys module has a function, exit() , which lets us use the exit codes and terminate the programs based on our needs. The exit() function accepts a single argument which is the exit code itself. The default value of the argument is 0 , that is, a successful response.


1 Answers

Python already does what you're asking:

$ python -c "raise RuntimeError()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
RuntimeError
$ echo $?
1

After some edits from the OP, perhaps you want:

import subprocess

proc = subprocess.Popen(['/usr/bin/python', 'script-name'])
proc.communicate()
if proc.returncode != 0:
    # Run failure code
else:
    # Run happy code.

Correct me if I am confused here.

like image 99
Thanatos Avatar answered Sep 29 '22 19:09

Thanatos