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.
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.
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.
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.
_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.
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
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>.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With