[Tutor] Exit from program early

Kent Johnson kent37 at tds.net
Fri Nov 4 12:07:26 CET 2005


Johan Geldenhuys wrote:
> Try using 'sys.exit()' where you want the script to stop if you haven't 
> supplied enough arguments.
> in you example, it looks like it will go on to the else anyway AND print 
> the string at the end.
> 
> Roy Bleasdale wrote:
>>In the example below I would like the program to stop if I forgot to 
>>provide an argument . Though I could do all my processing indented under 
>>the else statement, I was wondering if there was a command that would allow 
>>me to halt the program execution early.

Another way to do this is to structure your program with functions. For example you could write it as

def doSomeStuff():
    # Looking good so go do some stuff

if len(sys.argv) < 2:
    print "opps missing an argument"
    # Nice if I could stop and exit program here
else:
    print "Argument provided!!"
    doSomeStuff()
    print "Done some stuff"

Breaking your program up into small functions will generally make it more readable, testable and maintainable that using long stretches of straight-line code.

Kent

>>
>>Regards,
>>
>>Roy
>>
>>
>># Example program - Test for valid argument
>>
>>import sys
>>
>>if len(sys.argv) < 2:
>>    print "opps missing an argument"
>>    # Nice if I could stop and exit program here
>>else:
>>    print "Argument provided!!"
>>    # Looking good so go do some stuff
>>
>>print "Done some stuff"
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>> 
>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list