f



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

Given the following..

#!/usr/bin/python

import urllib2
import sys
import time

while 1:
    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:
        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.
0
chad
10/5/2010 2:38:45 AM
comp.lang.python 77058 articles. 6 followers. Post Follow

16 Replies
777 Views

Similar Articles

[PageSpeed] 49

your bare except is catching the SystemExit raised by sys.exit(1)
0
Justin
10/5/2010 2:57:07 AM
chad <cdalten@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
0
Ben
10/5/2010 2:57:11 AM
On 10/4/2010 10:38 PM, chad wrote:
> Given the following..
>
> #!/usr/bin/python
>
> import urllib2
> import sys
> import time
>
> while 1:
>      try:
>          con = urllib2.urlopen("http://www.google.com")
>          data = con.read()
>          print "connected"
>          #The loop doesn't exit if I use sys.exit(1)

Guess how sys.exit is implemented (or check the fine library manual 
chapter on the sys module, .exit entry, 2nd sentence).

>          break
>      except:

and guess what this does, and why bare excepts are not recommended 
unless you mean what you say...

>          time.sleep(2)

-- 
Terry Jan Reedy

0
Terry
10/5/2010 3:02:18 AM
Try to use sys.exit(0)
Maybe you should print out the error in your except block.


2010/10/5, chad <cdalten@gmail.com>:
> Given the following..
>
> #!/usr/bin/python
>
> import urllib2
> import sys
> import time
>
> while 1:
>     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:
>         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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
0
Von
10/5/2010 3:13:53 AM
On Tue, 05 Oct 2010 13:57:11 +1100, Ben Finney wrote:

> chad <cdalten@gmail.com> writes:
> 
>> while 1:
> 
> A minor point: this is more explanatory and less misleading if you write
> it as ‘while True’.

Why is it misleading? Is there some circumstance in Python where the 
literal 1 could have a false value?

"while 1" was the accepted idiom for infinite loops in Python for many 
years, before the introduction of bools in (I think) Python 2.2. "while 
1" is used used as a micro-optimization in versions of Python below (I 
think) 2.7. You might prefer "while True" as nicer or even more Pythonic, 
but I disagree that "while 1" is misleading.




-- 
Steven
0
Steven
10/5/2010 4:42:31 AM
Steven D'Aprano <steve-REMOVE-THIS@cybersource.com.au> writes:

> Why is it misleading? Is there some circumstance in Python where the 
> literal 1 could have a false value?

It's misleading as to the intent.

> "while 1" was the accepted idiom for infinite loops in Python for many 
> years, before the introduction of bools in (I think) Python 2.2.
[…]

Right. Now that we have boolean literals, they're semantically clearer
when the semantic value one is testing is boolean, not integer.

-- 
 \      “Nothing is more sacred than the facts.” —Sam Harris, _The End |
  `\                                                   of Faith_, 2004 |
_o__)                                                                  |
Ben Finney
0
Ben
10/5/2010 4:59:24 AM
In message <87iq1hz6rc.fsf@benfinney.id.au>, Ben Finney wrote:

> Don't ever use a bare ‘except’ unless you know exactly why you're doing
> so.

In other news, don’t ever put a loaded gun in your mouth and pull the 
trigger unless you know exactly why you’re doing so.

Some people have a problem. They say, “I know, I’ll use an exception”. Now 
they have Some people have a problem. They say, “I know, I’ll use an 
exception”. Now they have ...
0
Lawrence
10/5/2010 5:48:20 AM
On 2010-10-05, Lawrence D'Oliveiro <ldo@geek-central.gen.new_zealand> wrote:
> In message <87iq1hz6rc.fsf@benfinney.id.au>, Ben Finney wrote:
>> Don't ever use a bare ???except??? unless you know exactly why you're doing
>> so.

> In other news, don???t ever put a loaded gun in your mouth and pull the 
> trigger unless you know exactly why you???re doing so.

I don't think those are at all comparable, I've heard of people who had
plausible arguments for the gun.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nospam@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
0
Seebs
10/5/2010 6:07:13 AM
In message <slrnialg8v.28c5.usenet-nospam@guild.seebs.net>, Seebs wrote:

> On 2010-10-05, Lawrence D'Oliveiro <ldo@geek-central.gen.new_zealand>
> wrote:
>
>> In message <87iq1hz6rc.fsf@benfinney.id.au>, Ben Finney wrote:
>>
>>> Don't ever use a bare ‘except’ unless you know exactly why you're doing
>>> so.
>>
>> In other news, don’t ever put a loaded gun in your mouth and pull the 
>> trigger unless you know exactly why you’re doing so.
> 
> I don't think those are at all comparable, I've heard of people who had
> plausible arguments for the gun.

:)
0
Lawrence
10/5/2010 7:26:16 AM
On Tue, 05 Oct 2010 11:13:53 +0800, Von wrote:

> Try to use sys.exit(0)
> Maybe you should print out the error in your except block.

Not exiting with a status-code of 0 is no more helpful than not exiting 
with a status-code of 1.

It's actually *less* helpful, if the intention is actually to exit with a 
non-zero exit status.



-- 
Steven
0
Steven
10/5/2010 7:41:12 AM
On Tue, 05 Oct 2010 13:57:11 +1100, Ben Finney wrote:

> 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.

If I use a bare except, I usually have a good reason, namely that the
documentation doesn't actually mention which exceptions can be raised.
This is usually because the code doesn't actually know which exceptions
can be raised.

If a module defines:

	def foo(f):
	    f.bar()
	    ...

the set of exceptions which foo() can raise is limitless. The user can
pass whatever they like as "f", and its bar() method can raise anything.

Knowing which exceptions a function or method can raise is the exception
rather than the rule.

If I'm catching exceptions in order to perform clean-up, I'll use a bare
except and re-raise the exception afterwards. In that situation, a bare
except is usually the right thing to do.

If I'm not going to re-raise the exception, I'll either catch Exception or
add explicit catches for SystemExit and KeyboardInterrupt which re-raise
the exception.

0
Nobody
10/5/2010 8:45:12 PM
In message <pan.2010.10.05.20.44.49.109000@nowhere.com>, Nobody wrote:

> If I'm catching exceptions in order to perform clean-up, I'll use a bare
> except and re-raise the exception afterwards. In that situation, a bare
> except is usually the right thing to do.

Wrong way to do it.
0
Lawrence
10/11/2010 10:46:20 AM
Steven D'Aprano wrote:

> On Tue, 05 Oct 2010 13:57:11 +1100, Ben Finney wrote:
> 
>> chad <cdalten@gmail.com> writes:
>> 
>>> while 1:
>> 
>> A minor point: this is more explanatory and less misleading if you write
>> it as ‘while True’.
> 
> Why is it misleading? Is there some circumstance in Python where the
> literal 1 could have a false value?

Wrong question.

>>> while True:
....     print "forever"
....
>>> True
0

So, if I were to play advocatus diaboli I'd argue that 'while True: ...' is 
more likely to mislead because 'True' could be anything.

Peter

PS: The above is no longer possible in Python 3 where True and False have 
become keywords.
0
Peter
10/11/2010 12:13:37 PM
Lawrence D'Oliveiro wrote:
> In message <pan.2010.10.05.20.44.49.109000@nowhere.com>, Nobody wrote:
> 
>>If I'm catching exceptions in order to perform clean-up, I'll use a bare
>>except and re-raise the exception afterwards. In that situation, a bare
>>except is usually the right thing to do.
> 
> Wrong way to do it.

What, then, is the right way to do it?

~Ethan~
0
Ethan
10/11/2010 12:42:39 PM
On Mon, 11 Oct 2010 05:42:39 -0700, Ethan Furman wrote:

>>>If I'm catching exceptions in order to perform clean-up, I'll use a bare
>>>except and re-raise the exception afterwards. In that situation, a bare
>>>except is usually the right thing to do.
>> 
>> Wrong way to do it.
> 
> What, then, is the right way to do it?

I presume that he's referring to "finally". Which is reasonable enough
given what I wrote, but isn't always convenient.

My point was that bare excepts aren't a problem if you're going to
re-raise the exception.

0
Nobody
10/12/2010 12:18:37 AM
Nobody <nobody@nowhere.com> writes:

> On Mon, 11 Oct 2010 05:42:39 -0700, Ethan Furman wrote:
>
>>>>If I'm catching exceptions in order to perform clean-up, I'll use a bare
>>>>except and re-raise the exception afterwards. In that situation, a bare
>>>>except is usually the right thing to do.
>>> 
>>> Wrong way to do it.
>> 
>> What, then, is the right way to do it?
>
> I presume that he's referring to "finally". Which is reasonable enough
> given what I wrote, but isn't always convenient.
>
> My point was that bare excepts aren't a problem if you're going to
> re-raise the exception.

If I understand correctly, there is a big difference between bare except
and finally:

>>> def f(x):
....     try:
....         if x:
....             raise ValueError("x should be falsy")
....     except:
....         print("bare except")
....         raise
....     finally:
....         print("finally")
.... 
>>> f(0)
finally
>>> f(1)
bare except
finally
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
ValueError: x should be falsy

The finally: clause is always executed, whereas the bare except: clause
is only executed if an exception was raised in the try: clause.

-- 
Arnaud
0
Arnaud
10/13/2010 9:08:18 AM
Reply: