Does python have an EXIT_SUCCESS constant?

I return 0 all over the place in the python script, but prefer something more semantic, something more readable. I do not like this magic number. Is there an idea in python similar to how in C you can return EXIT_SUCCESS instead of 0?

I could not find it here: https://docs.python.org/3.5/library/errno.html

+5
source share
2 answers

I'm coming back 0

return is not how you set the script exit code in Python. If you want to exit with exit code 0, just let your script complete normally. The exit code will be automatically set to 0. If you want to exit with a different exit code, sys.exit is the tool to use.

If you use 0 or 1 return values ​​in your code to indicate whether functions were successful or unsuccessful, this is a bad idea. You should raise an appropriate exception if something goes wrong.

+5
source

Since you are discussing return here, it seems that you can program Python, for example C. Most Python functions should ideally be written to throw an exception if they fail, and the calling code can determine how to handle the exceptional conditions. For validation functions, it is best to return True or False - not as literals, usually, but as the result of some expression like s.isdigit() .

Speaking about the return value of a process in its environment, you can use return , because the module is not a function, so the return at the top level will be marked as a syntax error. You should use sys.exit instead.

Python may seem a bit minimalistic in this regard, but calling sys.exit with no default arguments for success (i.e. return code 0). Thus, the easiest way to simplify your program may be to stop its encoding with an argument in which you do not want to indicate a failure!

As the documentation reminds us, integer arguments are passed back, and string arguments lead to return code 1 , and the string is printed on stderr .

As far as I know, the language does not contain any constants (although it has functions specific to some environments, if it provided exit codes, their values ​​may be required for implementation or for the platform, and the language developers prefer to avoid this whenever possible .

0
source

Source: https://habr.com/ru/post/1244496/


All Articles