My code goes like this:
if (not Y):
print ("Can't print")
sys.exit(-1)
I am unable to understand what does the argument (-1
) returns?
My code goes like this:
if (not Y):
print ("Can't print")
sys.exit(-1)
I am unable to understand what does the argument (-1
) returns?
sys.exit(-1)
tells the program to quit. It basically just stops the python code from continuing execution. -1 is just the status code that is passed in. Generally 0 denotes successful execution, any other number (usually 1) means something broke.
The call sys.exit(n)
tells the interpreter to stop the execution and return n
to the OS. What this value is depends on the operating system.
For example on UNIX ($?
is the last exit status):
$ python -c "import sys; sys.exit(-1)"
$ echo $?
255
This is because it treats the return value as an unsigned 8bit value (see here). On Windows the value would be an unsigned 32bit value (from here) and thus be 4294967295
.
As you can see in the first link, the convention is to return 0
on a successful exit and a non-zero value otherwise. Sometimes you'll see that an application has a certain convention for its status codes.
For example the program wget
has a section in its man page that tells you why an error occurred:
EXIT STATUS
Wget may return one of several error codes if it encounters problems.
0 No problems occurred.
1 Generic error code.
2 Parse error---for instance, when parsing command-line options, the .wgetrc or .netrc...
3 File I/O error.
4 Network failure.
5 SSL verification failure.
6 Username/password authentication failure.
7 Protocol errors.
8 Server issued an error response.
The convention of returning 0
on a success is very helpful for writing scripts:
$ if python -c "import sys; sys.exit(-1)"; then echo "Everything fine"; else echo "Not good"; fi
Not good
$ if python -c "import sys; sys.exit(0)"; then echo "Everything fine"; else echo "Not good"; fi
Everything fine