[Tutor] Using sys.exit()

Alan Gauld alan.gauld at btinternet.com
Fri Nov 3 01:40:33 CET 2006


"Dick Moores" <rdm at rcblue.com> wrote
>>You can use an argument if you want to pass an error value
>>back to the OS. This is good practice if your script might be
>>used in a batch file or shell script
>
> So what should that value be?

Zero means no errors and is the default value.

But you can define any non zero values that you like and so
long as you document them users of tyour script can tell why
the script stopped.

Thus in MSDOS you could write a batch file:

PYTHON MYSCRIPT.PY
IF ERRORLEVEL == 1 ECHO 'NO INPUT'
IF ERRORLEVEL == 2 ECHO 'INVALID INPUTS'

etc etc.

> don't, because I don't (yet) use python to write either batch files
> or shell scripts.

Its not about using Python to write the scripts itcs about
*using* a python script inside a batch file/shell script

This also applies if you use a script from within an
os.system() call since os.system() returns the exit
value of the command that you execute. Thus

err = os.system("python myscript.py")
print err

err will contain the value passed out by myscript.py as
an exit code. The default will be zero which implies that
myscript ran successfully. But if you provide meaningful
exit codes you can test for those when using os.system().

>>break is not intended to quit programs, break is intended
>>to quit loops. To exit a program you should use sys.exit()
>>and if its an abnormal exit provide an argument.
>
> Of course, I've been using break to exit only when it works. Why is
> it wrong to do so?

Only in that there will be no error value passed back.

break sdoesn't really exit the program it just forces execution
to fall off the end of your script.

for n in range(10):
    pass

Will execute silently and end

n = 0
while True:
    if n > 9: break

will do exactly the same

Both programs exit when they run out of code to execute.

sys.exit() just provides a bit more control over how the script exits
and this makes it slightly easier to use the script within a batch
file etc..

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list