I don't get why sys.exit(1) doesn't exit the while loop in the follow case

Ben Finney ben+python at benfinney.id.au
Mon Oct 4 22:57:11 EDT 2010


chad <cdalten at gmail.com> writes:

> while 1:

A minor point: this is more explanatory and less misleading if you write
it as ‘while True’.

>     try:
>         con = urllib2.urlopen("http://www.google.com")
>         data = con.read()
>         print "connected"
>         #The loop doesn't exit if I use sys.exit(1)
>         break
>     except:

Here's your problem. Don't ever use a bare ‘except’ unless you know
exactly why you're doing so. Rather, figure out what exception types you
want to catch, and catch *only* those types.

>         time.sleep(2)
>
> If I would replace 'break' with 'sys.exit(1)', the while loop will
> keep printing connected every 2 seconds? Why I this?> I thought exit
> meant exit.

Have a read of the documentation for ‘sys.exit’ to see how it exits;
you'll then see how you are foiling its purpose.

-- 
 \      “It is an interesting and demonstrable fact, that all children |
  `\   are atheists and were religion not inculcated into their minds, |
_o__)                           they would remain so.” —Ernestine Rose |
Ben Finney



More information about the Python-list mailing list