exit a program gracefully
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon May 4 18:33:51 EDT 2009
En Mon, 04 May 2009 19:14:53 -0300, Chris Rebert escribió:
> On Mon, May 4, 2009 at 3:02 PM, <Robert.T.Lynch at seagate.com> wrote:
>> In a python program I ask if the user wants to continue. If they answer
>> 'no', what options do I have to halt execution? I can put the rest of
>> the
>> code inside an "if bContinue:" block, but that seems awkward. I have
>> looked
>> at raising an exception, and perhaps this is the preferred method, but
>> it
>> seems daunting to my non-OOP eyes. Thanks -- Rob
>
> There's the C-like:
> from sys import exit
> exit(return_code)
>
> Or if you prefer exceptions, the standard way is:
> raise SystemExit
I prefer to put the code inside a function, and just `return` earlier.
Having a sys.exit() in the middle of a function means that it's not
reusable; I usually have a single exit() at the end.
def do_work():
do some work
ask the user
if not continue:
return 0
do more work
return 0
if __name__=='__main__':
try: sts = do_work()
except: sts = 1, log exception
sys.exit(sts)
--
Gabriel Genellina
More information about the Python-list
mailing list