Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exit status code from Python, e.g. 0 or 1

Tags:

shell

exit

I have a Python script which will do some actions, and depending on the result, will exit with a code 0 (all right) or 1 (not good).

I want to catch this result, store it into a variable and send it over UDP. This cannot be done inside the Python script (requirement).

So let's say my script is something like:

import sys
# Do some stuff
sys.exit(0) # or sys.exit(1)

Which I run with python script.py.

How can I get this exit status code (0 or 1)?

I try to echo $errorlevel, but it only prints a blank line. I also try to use exit(0) instead of sys.exit() (see here) and some other unsuccessful attempts.

like image 287
Mornor Avatar asked Sep 14 '16 12:09

Mornor


People also ask

How do I return exit code 0 in Python?

Recall that the exit code is set to zero indicating a successful exit when a Python process exits normally. We can achieve this by updating the previous example to remove the call to sys. exit() from the task() function executed in a child process.

What is exit 0 and exit 1 Python?

exit(0) means a clean exit without any errors / problems. exit(1) means there was some issue / error / problem and that is why the program is exiting. This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was.

How do I get exit status code in Python?

Standard exit codes are received when python program executes. Successful execution returns 0 and unsuccessful execution returns 1. Custom exit codes can be passed using sys. exit() call in python.

What is exit () in Python?

_exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in the child process after os. fork() system call. The standard way to exit the process is sys. exit(n) method.


2 Answers

Since as per your answer you are using zsh

test.py

import sys
sys.exit(12)

in your console

python test.py
RC=$?
echo "Exit code $RC"
program_to_send $RC
like image 70
RedX Avatar answered Oct 06 '22 13:10

RedX


It's a script question, not a Python question, but in the Bash shell you use $? and since any command changes $?, it's usually a good idea to save a copy.

python script.py
RC=$?

echo $RC
[ $RC == 0 ] && echo Success || echo Failed
# Replace above lines by whatever you need to send $RC via UDP ...

If it's a Windows CMD script question, you should probably repost with the appropriate tags. (I don't do Windows any more, thank <deity>.)

like image 2
nigel222 Avatar answered Oct 06 '22 15:10

nigel222