Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64822 > unrolled thread

buggy python interpretter or am I missing something here?

Started byme <noone@all.net>
First post2014-01-27 03:42 +0000
Last post2014-01-27 10:52 -0700
Articles 20 on this page of 41 — 17 participants

Back to article view | Back to comp.lang.python


Contents

  buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 03:42 +0000
    buggy python interpretter or am I missing something here? - "TCdaemon.py"  yEnc me <noone@all.net> - 2014-01-27 03:42 +0000
    Re: buggy python interpretter or am I missing something here? Gary Herron <gary.herron@islandtraining.com> - 2014-01-26 21:04 -0800
      Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 06:17 +0000
        Re: buggy python interpretter or am I missing something here? Gary Herron <gary.herron@islandtraining.com> - 2014-01-26 23:03 -0800
          Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 07:20 +0000
    Re:buggy python interpretter or am I missing something here? Dave Angel <davea@davea.name> - 2014-01-27 00:36 -0500
      Re:buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 06:02 +0000
        Re: buggy python interpretter or am I missing something here? Zachary Ware <zachary.ware+pylist@gmail.com> - 2014-01-27 00:47 -0600
          Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 07:17 +0000
            Re: buggy python interpretter or am I missing something here? Alister <alister.ware@ntlworld.com> - 2014-01-27 12:19 +0000
            Re: buggy python interpretter or am I missing something here? Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-27 13:48 +0000
            Re: buggy python interpretter or am I missing something here? Zachary Ware <zachary.ware+pylist@gmail.com> - 2014-01-27 10:23 -0600
              Re: buggy python interpretter or am I missing something here? Dan Sommers <dan@tombstonezero.net> - 2014-01-27 16:38 +0000
            Re: buggy python interpretter or am I missing something here? Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-27 16:45 +0000
    Re: buggy python interpretter or am I missing something here? Terry Reedy <tjreedy@udel.edu> - 2014-01-27 01:21 -0500
      Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 06:42 +0000
        Re: buggy python interpretter or am I missing something here? Ethan Furman <ethan@stoneleaf.us> - 2014-01-26 23:08 -0800
    Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 06:46 +0000
      Re: buggy python interpretter or am I missing something here? Zachary Ware <zachary.ware+pylist@gmail.com> - 2014-01-27 00:55 -0600
      Re: buggy python interpretter or am I missing something here? Gary Herron <gary.herron@islandtraining.com> - 2014-01-26 23:12 -0800
        Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 07:30 +0000
          Re: buggy python interpretter or am I missing something here? Peter Otten <__peter__@web.de> - 2014-01-27 09:45 +0100
      Re: buggy python interpretter or am I missing something here? Ethan Furman <ethan@stoneleaf.us> - 2014-01-26 23:17 -0800
        Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 07:44 +0000
          Re: buggy python interpretter or am I missing something here? Chris Angelico <rosuav@gmail.com> - 2014-01-27 20:01 +1100
            Re: buggy python interpretter or am I missing something here? me <noone@all.net> - 2014-01-27 09:32 +0000
              Re: buggy python interpretter or am I missing something here? Neil Cerutti <neilc@norwich.edu> - 2014-01-27 12:56 +0000
              Re: buggy python interpretter or am I missing something here? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-27 13:56 +0000
              Re: buggy python interpretter or am I missing something here? Rick Johnson <rantingrickjohnson@gmail.com> - 2014-01-27 07:33 -0800
                Re: buggy python interpretter or am I missing something here? Chris Angelico <rosuav@gmail.com> - 2014-01-28 02:53 +1100
                  Re: buggy python interpretter or am I missing something here? Rick Johnson <rantingrickjohnson@gmail.com> - 2014-01-27 12:22 -0800
                    Re: buggy python interpretter or am I missing something here? Chris Angelico <rosuav@gmail.com> - 2014-01-28 07:29 +1100
                    Re: buggy python interpretter or am I missing something here? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-27 22:25 +0000
                      Re: buggy python interpretter or am I missing something here? Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-01-30 18:13 +1300
                        Re: buggy python interpretter or am I missing something here? Terry Reedy <tjreedy@udel.edu> - 2014-01-30 04:44 -0500
                        Re: buggy python interpretter or am I missing something here? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-31 04:06 +0000
                          Re: buggy python interpretter or am I missing something here? Kushal Kumaran <kushal.kumaran@gmail.com> - 2014-01-31 10:37 +0530
                          Re: buggy python interpretter or am I missing something here? Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-01-31 19:59 +1300
                Re: buggy python interpretter or am I missing something here? Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-27 16:22 +0000
              Re: buggy python interpretter or am I missing something here? Michael Torrie <torriem@gmail.com> - 2014-01-27 10:52 -0700

Page 1 of 3  [1] 2 3  Next page →


#64822 — buggy python interpretter or am I missing something here?

Fromme <noone@all.net>
Date2014-01-27 03:42 +0000
Subjectbuggy python interpretter or am I missing something here?
Message-ID<pan$57cb8$37426877$4ff183f7$e46f1ba0$1@all.net>
I'm writing a linux daemon in python 2.x to process batches of GPS/GIS 
data and I'm running into something that seems to break the expected 
program flow in a REALLY BAD WAY.

Consider the attached template script and execute it with the -h option.  
It is falling through to the except: clause even though try to manually 
exit with sys.exit(0).  However, if I insert a "raise" into the except 
clause then the sys.exit(0) executes properly. 

See the attached code and output from when I run it.

Not interested in work-arounds.  I want to understand why it doesn't work 
as expected.

Thanks!

TCdaemon.py ----

#! /usr/bin/python

import sys


# 
------------------------------------------------------------------------------

defaultparams={ \
    "basedir": "/process", \
    "inpipe": "/tmp/TCdaemonIN", \
    "maxjobs":8, \
    "outpipe": "/tmp/TCdaemonOUT", \
    "ZZZ": 0
    }

# 
------------------------------------------------------------------------------

def parse_args(a,d):
    l=len(a)
    idx=1
    try:
        while (idx<l):
            if (a[idx]=="-#"):
                idx=idx+1
                d["maxjobs"]=int(a[idx])
            elif (a[idx]=="-d"):
                idx=idx+1
                d["basedir"]=a[idx]
            elif (a[idx]=="-h"):
                print "help goes here"
                sys.exit(0)
            elif (a[idx]=="-i"):
                idx=idx+1
                d["inpipe"]=a[idx]
            elif (a[idx]=="-o"):
                idx=idx+1
                d["outpipe"]=a[idx]
            idx=idx+1
    except:
        # raise # -- WTF!!!??? required for -h to not fall through to 
here?
        print "%s: error in command line - %s"%(a[0],a[idx:])
        sys.exit(1)

    
# 
------------------------------------------------------------------------------
# 
------------------------------------------------------------------------------
# 
------------------------------------------------------------------------------

if (__name__=="__main__"):
    print defaultparams
    parse_args(sys.argv,defaultparams)
    print defaultparams
    




output.txt ---
[@blackbox new]$ ./TCdaemon.py -h
{'ZZZ': 0, 'basedir': '/process', 'outpipe': '/tmp/TCdaemonOUT', 
'maxjobs': 8, 'inpipe': '/tmp/TCdaemonIN'}
help goes here
./TCdaemon.py: error in command line - ['-h']
[@blackbox new]$ echo $?
1
[@blackbox new]$ 
[@blackbox new]$ 
[@blackbox new]$ # editing to add "raise" at line 40
[@blackbox new]$ 
[@blackbox new]$ 
[@blackbox new]$ 
[@blackbox new]$ ./TCdaemon.py -h
{'ZZZ': 0, 'basedir': '/process', 'outpipe': '/tmp/TCdaemonOUT', 
'maxjobs': 8, 'inpipe': '/tmp/TCdaemonIN'}
help goes here
[@blackbox new]$ echo $?
0
[@blackbox new]$ 

[toc] | [next] | [standalone]


#64823 — buggy python interpretter or am I missing something here? - "TCdaemon.py" yEnc

Fromme <noone@all.net>
Date2014-01-27 03:42 +0000
Subjectbuggy python interpretter or am I missing something here? - "TCdaemon.py" yEnc
Message-ID<52e5d5c2$0$29626$862e30e2@ngroups.net>
In reply to#64822
=ybegin part=1 line=128 size=1474 name=TCdaemon.py
=ypart begin=0 end=5
MKJY�
=yend size=5 part=1 pcrc32=52f391ac

[toc] | [prev] | [next] | [standalone]


#64825

FromGary Herron <gary.herron@islandtraining.com>
Date2014-01-26 21:04 -0800
Message-ID<mailman.6018.1390799500.18130.python-list@python.org>
In reply to#64822
On 01/26/2014 07:42 PM, me wrote:
> I'm writing a linux daemon in python 2.x to process batches of GPS/GIS
> data and I'm running into something that seems to break the expected
> program flow in a REALLY BAD WAY.
>
> Consider the attached template script and execute it with the -h option.
> It is falling through to the except: clause even though try to manually
> exit with sys.exit(0).  However, if I insert a "raise" into the except
> clause then the sys.exit(0) executes properly.
>
> See the attached code and output from when I run it.
>
> Not interested in work-arounds.  I want to understand why it doesn't work
> as expected.
>
> Thanks!
>
> TCdaemon.py ----
>
> #! /usr/bin/python
>
> import sys
>
>
> #
> ------------------------------------------------------------------------------
>
> defaultparams={ \
>      "basedir": "/process", \
>      "inpipe": "/tmp/TCdaemonIN", \
>      "maxjobs":8, \
>      "outpipe": "/tmp/TCdaemonOUT", \
>      "ZZZ": 0
>      }
>
> #
> ------------------------------------------------------------------------------
>
> def parse_args(a,d):
>      l=len(a)
>      idx=1
>      try:
>          while (idx<l):
>              if (a[idx]=="-#"):
>                  idx=idx+1
>                  d["maxjobs"]=int(a[idx])
>              elif (a[idx]=="-d"):
>                  idx=idx+1
>                  d["basedir"]=a[idx]
>              elif (a[idx]=="-h"):
>                  print "help goes here"
>                  sys.exit(0)
>              elif (a[idx]=="-i"):
>                  idx=idx+1
>                  d["inpipe"]=a[idx]
>              elif (a[idx]=="-o"):
>                  idx=idx+1
>                  d["outpipe"]=a[idx]
>              idx=idx+1
>      except:
>          # raise # -- WTF!!!??? required for -h to not fall through to
> here?
>          print "%s: error in command line - %s"%(a[0],a[idx:])
>          sys.exit(1)

Never *ever* have a bare except like that.  If it gets invoked, you have 
no idea why.   A simple typo like ixd instead of idx or a(idx) instead 
of a[idx] would raise an exception but give you no idea why.

Do
   try:
       ...
   except Exception,e:
       print e
at the absolute minimum.
(Python 3 syntax would differ slightly, but the advice is the same.)

Perhaps printing a traceback along with the exception would help. Add
     traceback.print_exc()


Gary Herron


>
>      
> #
> ------------------------------------------------------------------------------
> #
> ------------------------------------------------------------------------------
> #
> ------------------------------------------------------------------------------
>
> if (__name__=="__main__"):
>      print defaultparams
>      parse_args(sys.argv,defaultparams)
>      print defaultparams
>      
>
>
>
>
> output.txt ---
> [@blackbox new]$ ./TCdaemon.py -h
> {'ZZZ': 0, 'basedir': '/process', 'outpipe': '/tmp/TCdaemonOUT',
> 'maxjobs': 8, 'inpipe': '/tmp/TCdaemonIN'}
> help goes here
> ./TCdaemon.py: error in command line - ['-h']
> [@blackbox new]$ echo $?
> 1
> [@blackbox new]$
> [@blackbox new]$
> [@blackbox new]$ # editing to add "raise" at line 40
> [@blackbox new]$
> [@blackbox new]$
> [@blackbox new]$
> [@blackbox new]$ ./TCdaemon.py -h
> {'ZZZ': 0, 'basedir': '/process', 'outpipe': '/tmp/TCdaemonOUT',
> 'maxjobs': 8, 'inpipe': '/tmp/TCdaemonIN'}
> help goes here
> [@blackbox new]$ echo $?
> 0
> [@blackbox new]$
>
>

[toc] | [prev] | [next] | [standalone]


#64829

Fromme <noone@all.net>
Date2014-01-27 06:17 +0000
Message-ID<52e5fa05$0$29727$862e30e2@ngroups.net>
In reply to#64825
On Sun, 26 Jan 2014 21:04:57 -0800, Gary Herron wrote:

> 
> Never *ever* have a bare except like that.  If it gets invoked, you have
> no idea why.   A simple typo like ixd instead of idx or a(idx) instead
> of a[idx] would raise an exception but give you no idea why.
> 
> Do
>    try:
>        ...
>    except Exception,e:
>        print e
> at the absolute minimum.
> (Python 3 syntax would differ slightly, but the advice is the same.)
> 
> Perhaps printing a traceback along with the exception would help. Add
>      traceback.print_exc()


So here's the clencher without debating the merits bare except: since a 
bare catch(...) is totally acceptable in the c++ world.

When I have except: by itself the program fails...but simply adding the 
"except Exception,e: " causes the program to work correctly.  

To me that signifies an undefined behavior of the python specification, 
or at least bad behavior of the python interpreter I'm using.  If you can 
syntactically use a bare except: without generating an invalid syntax 
error then it should have a well defined and predictable outcome.  

If in fact the "except Exception, e:" is what's required then a bare 
except shouldn't be considered valid syntax at all, right?

kind regards

[toc] | [prev] | [next] | [standalone]


#64838

FromGary Herron <gary.herron@islandtraining.com>
Date2014-01-26 23:03 -0800
Message-ID<mailman.6027.1390806238.18130.python-list@python.org>
In reply to#64829
On 01/26/2014 10:17 PM, me wrote:
> On Sun, 26 Jan 2014 21:04:57 -0800, Gary Herron wrote:
>
>> Never *ever* have a bare except like that.  If it gets invoked, you have
>> no idea why.   A simple typo like ixd instead of idx or a(idx) instead
>> of a[idx] would raise an exception but give you no idea why.
>>
>> Do
>>     try:
>>         ...
>>     except Exception,e:
>>         print e
>> at the absolute minimum.
>> (Python 3 syntax would differ slightly, but the advice is the same.)
>>
>> Perhaps printing a traceback along with the exception would help. Add
>>       traceback.print_exc()
>
> So here's the clencher without debating the merits bare except: since a
> bare catch(...) is totally acceptable in the c++ world.
>
> When I have except: by itself the program fails...but simply adding the
> "except Exception,e: " causes the program to work correctly.

Doubtful.   We've been doing this kind of stuff for decades without 
hitting your supposed bug.  Much more likely is that you've 
misinterpreted the results.  Ii don't know how, but I'm quite confident 
that you have.

Your contention that the raise goes back to the sys.exit() is certainly 
a mis-interpretation also.  The re-raise of the original exception is 
now an uncaught exception, and the interpreter's response to an uncaught 
exception is to kill the program.   Nearly the same result as the 
sys.exit(), but via a different pathway.

>
> To me that signifies an undefined behavior of the python specification,
> or at least bad behavior of the python interpreter I'm using.  If you can
> syntactically use a bare except: without generating an invalid syntax
> error then it should have a well defined and predictable outcome.

It is well defined.  Slow down a bit, rerun your two tests, show is the 
code *and* the results, and we'll get to the bottom of this.

>
> If in fact the "except Exception, e:" is what's required then a bare
> except shouldn't be considered valid syntax at all, right?

Bare excepts are perfectly legal valid syntax and have their uses, 
however it's just extremely dangerous programming to allow a simple typo 
(or any of an infinite number of possible errors) in your try section to 
masquerade as a "error in command line" (to quote your print at that 
point).    Python's dynamic typing makes bare except extremely 
dangerous.  In Python, unlike C, any number of typos can be 
syntactically correct, but meaningless, exception-raising actions at run 
time.  Things like misspelling a variable/function name, substituting a 
comma for a decimal point, indexing something that is not indexable, 
applying a function to the wrong parameters or wrong number of 
parameters, ...  All these are *not* syntax errors (as they would be in 
C), but will cause a run-time exception -- and you'd never know why with 
that bare except blindly catching them all and claiming "command line 
error".

Gary Herron

>
> kind regards

[toc] | [prev] | [next] | [standalone]


#64841

Fromme <noone@all.net>
Date2014-01-27 07:20 +0000
Message-ID<52e608d7$0$29681$862e30e2@ngroups.net>
In reply to#64838
On Sun, 26 Jan 2014 23:03:51 -0800, Gary Herron wrote:

found the part I was missing based on another response.  Didn't realize 
that sys.exit() triggered an instance of "BaseException" and that 
explains the weird behavior.

thx!

[toc] | [prev] | [next] | [standalone]


#64827

FromDave Angel <davea@davea.name>
Date2014-01-27 00:36 -0500
Message-ID<mailman.6020.1390800839.18130.python-list@python.org>
In reply to#64822
 me <noone@all.net> Wrote in message:
> I'm writing a linux daemon in python 2.x to process batches of GPS/GIS 
> data and I'm running into something that seems to break the expected 
> program flow in a REALLY BAD WAY.
> 
> Consider the attached template script and execute it with the -h option.  
> It is falling through to the except: clause even though try to manually 
> exit with sys.exit(0).  However, if I insert a "raise" into the except 
> clause then the sys.exit(0) executes properly. 
> 
> See the attached code and output from when I run it.
> 
> Not interested in work-arounds.  I want to understand why it doesn't work 
> as expected.
> 

sys.exit() raises an exception,  and you're deliberately eating
 that exception. 

> 
> ------------------------------------------------------------------------------
> 
> def parse_args(a,d):
>     l=len(a)
>     idx=1
>     try:
>         while (idx<l):
>             if (a[idx]=="-#"):
>                 idx=idx+1
>                 d["maxjobs"]=int(a[idx])
>             elif (a[idx]=="-d"):
>                 idx=idx+1
>                 d["basedir"]=a[idx]
>             elif (a[idx]=="-h"):
>                 print "help goes here"
>                 sys.exit(0)
>             elif (a[idx]=="-i"):
>                 idx=idx+1
>                 d["inpipe"]=a[idx]
>             elif (a[idx]=="-o"):
>                 idx=idx+1
>                 d["outpipe"]=a[idx]
>             idx=idx+1
>     except:

Bare except is almost never a good idea. It's going to intercept
 the exit exception, plus control C, syntax errors and others.
 Which you'd have known if you printed the exception code.
 

If you're going to catch an exception,  be specific. Otherwise
 expect the unexpected. 


There is a hierarchy of exception classes,  so you could catch a
 fairly generic class. But you do need to distinguish.
 

-- 
DaveA

[toc] | [prev] | [next] | [standalone]


#64828

Fromme <noone@all.net>
Date2014-01-27 06:02 +0000
Message-ID<52e5f658$0$29583$862e30e2@ngroups.net>
In reply to#64827
On Mon, 27 Jan 2014 00:36:20 -0500, Dave Angel wrote:

> sys.exit() raises an exception,  and you're deliberately eating
>  that exception.
> 

I can buy that sys.exit (may) be throwing an exception...My point of 
contention isn't that I may be throwing one, but why would a subsequent 
"raise" in the except: clause cause the point of program execution to 
jump back up to the sys.exit(0) and then function correctly.  This seems 
to be a violation of the programming semantics of python as I understand 
them...coming from an old fart c++ programmer where bare catch() is 
totally acceptable and common form.


> 
> Bare except is almost never a good idea. It's going to intercept
>  the exit exception, plus control C, syntax errors and others.
>  Which you'd have known if you printed the exception code.
>  
>  
> If you're going to catch an exception,  be specific. Otherwise
>  expect the unexpected.
> 
> 
> There is a hierarchy of exception classes,  so you could catch a
>  fairly generic class. But you do need to distinguish.

I'll take your point of "almost a never good idea" under consideration 
and agree that if I was writing something for production use I'd be more 
comprehensive, but I really don't care what exceptions are raised at this 
point ... until I've tested with bunches of input data and see that it 
does break and under what circumstances.  But...it still doesn't explain 
why/how a raise in the except: clause can recover the point of program 
execution back to the sys.exit(0) that threw the exception.


Are you saying that the programming semantics of try/except are different 
in python than they are in c++?  My expectation being that when an 
exception occurs program control jumps to the except: and then continues 
below without ever going back to the code that threw the exception in the 
first place...because that's exactly what it appears to be doing?

Are except: clauses in python more synonymous with the old BASIC "GOSUB" 
or "ON ERROR GOSUB" statement rather than following the c++ semantics?

kind regards

[toc] | [prev] | [next] | [standalone]


#64836

FromZachary Ware <zachary.ware+pylist@gmail.com>
Date2014-01-27 00:47 -0600
Message-ID<mailman.6025.1390805261.18130.python-list@python.org>
In reply to#64828
On Mon, Jan 27, 2014 at 12:02 AM, me <noone@all.net> wrote:
> On Mon, 27 Jan 2014 00:36:20 -0500, Dave Angel wrote:
>
>> sys.exit() raises an exception,  and you're deliberately eating
>>  that exception.
>>
>
> I can buy that sys.exit (may) be throwing an exception...My point of
> contention isn't that I may be throwing one, but why would a subsequent
> "raise" in the except: clause cause the point of program execution to
> jump back up to the sys.exit(0) and then function correctly.

You've missed the point here.  sys.exit() *does* raise an exception:
SystemExit, a subclass of BaseException.  In fact, you can implement
sys.exit in pure Python like so:

def exit(status):
    raise SystemExit(status)

Your bare 'except:' catches that SystemExit along with any other
possible exception; the bare 'raise' in the except clause just
re-raises the same SystemExit, which then does what you meant for it
to do in the first place.

Exception classes form a hierarchy, with BaseException being the base
(obviously :)), "except:" is really just shorthand for "except
BaseException:", and is very rarely a good idea.  Deriving from
BaseException are SystemExit, KeyboardInterrupt, and Exception.
SystemExit is the exception raised by sys.exit(), which if left
unhandled, the interpreter takes as a sign to shut down gracefully.
KeyboardInterrupt is raised by Ctrl+C, or (more accurately, if I'm not
mistaken) by sending SIGINT to the process.  Exception is the base
class for all other exceptions, such as TypeError, ValueError,
OSError, etc., and is what you actually want to catch if you really
don't care what exception is raised but want to handle it (though in
most cases, you either should care, or should at least report what the
exception was, preferably with a traceback...which is easiest to do by
not trying to catch the exception at all).

I would suggest skimming through the Python tutorial and/or language
reference if you haven't before, there's a lot of good information in
there that will make your life with Python much easier.

And, please take this positively, but from your posted code it's
fairly apparent that Python is not your native tongue :).  For
instance, you don't need the backslashes in your defaultparams
assignment; the parser knows it needs to keep looking on subsequent
lines when it hasn't found the closing '}' yet.  Also, you can iterate
over a (sys.argv) in a for loop, replacing 'l', 'idx', and the while
loop; something like

for arg in a:
    if arg == '-h':
        print help # help being defined elsewhere...
    elif arg == '-hh':
        # no really, print help
        print 'help'

And the big one, argument parsing is a solved problem in Python.
Check out the argparse module in the standard library (or if you're
using an older version of Python, try either optparse or getopt.  It's
really a thrice-solved problem ;)).

I hope I've been of some help,

--
Zach

[toc] | [prev] | [next] | [standalone]


#64840

Fromme <noone@all.net>
Date2014-01-27 07:17 +0000
Message-ID<52e60817$0$29774$862e30e2@ngroups.net>
In reply to#64836
On Mon, 27 Jan 2014 00:47:13 -0600, Zachary Ware wrote:

> You've missed the point here.  sys.exit() *does* raise an exception:
> SystemExit, a subclass of BaseException.  In fact, you can implement
> sys.exit in pure Python like so:
> 
> def exit(status):
>     raise SystemExit(status)
> 
> Your bare 'except:' catches that SystemExit along with any other
> possible exception; the bare 'raise' in the except clause just re-raises
> the same SystemExit, which then does what you meant for it to do in the
> first place.

Well that does change things a bit and makes perfect sense now.  Thx!


 
> And, please take this positively, but from your posted code it's fairly
> apparent that Python is not your native tongue :).  

Correct.  The barbarians invaded my homeland and forced me to speak their 
wicked incantations.  I'm a c/c++ guy through and through with a 
sprinkling of the ancient tongues like algol, LSI-11 and Z80 assembler, 
fortran-4, etc.

My python stuff is all rapid application development for personal 
projects.  If I need to do anything serious I take the time to do it in C+
+.


> For instance, you
> don't need the backslashes in your defaultparams assignment; the parser
> knows it needs to keep looking on subsequent lines when it hasn't found
> the closing '}' yet.  

It's the intendation specific requirements that throw me.  I haven't seen 
such a hork since RPG. ;^)


> Also, you can iterate over a (sys.argv) in a for
> loop, replacing 'l', 'idx', and the while loop; something like
> 
> for arg in a:
>     if arg == '-h':
>         print help # help being defined elsewhere...
>     elif arg == '-hh':
>         # no really, print help print 'help'

Understood, except that some parameters take multiple elements...thus why 
I manually reference the indexes.


> And the big one, argument parsing is a solved problem in Python. Check
> out the argparse module in the standard library (or if you're using an
> older version of Python, try either optparse or getopt.  It's really a
> thrice-solved problem ;)).

Yup.  Every language and platform has multiple arg parsing libraries.  
Didn't feel like taking the time to research any since most of my python 
ramblings are usually pyQT4 bindings to QT4 gui and postgresql apps.

> 
> I hope I've been of some help,

Pointing out that sys.exit() raises a low level exception was the point I 
was missing.  Thx!

[toc] | [prev] | [next] | [standalone]


#64855

FromAlister <alister.ware@ntlworld.com>
Date2014-01-27 12:19 +0000
Message-ID<r9sFu.35$fx7.5@fx16.am4>
In reply to#64840
O 
> My python stuff is all rapid application development for personal
> projects.  If I need to do anything serious I take the time to do it in
> C+
> +.

Many people "Prototype" in python & then re-factor into a compiled 
language later if needed (often it turns out there is not really any 
need :-) ) 
> 
> It's the intendation specific requirements that throw me.  I haven't
> seen such a hork since RPG. ;^)
> 
But i bet you almost certainly indent your C++ cod in a similar manor on 
a voluntary basis, don't worry you will soon get used to it & quite 
probably start to like it.


-- 
Hempstone's Question:
	If you have to travel on the Titanic, why not go first class?

[toc] | [prev] | [next] | [standalone]


#64860

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-01-27 13:48 +0000
Message-ID<mailman.6040.1390830522.18130.python-list@python.org>
In reply to#64840
On 27/01/2014 07:17, me wrote:
> My python stuff is all rapid application development for personal
> projects.  If I need to do anything serious I take the time to do it in C+
> +.
>

For me at least you'll fit in extremely well here with a sense of humour 
like that.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#64876

FromZachary Ware <zachary.ware+pylist@gmail.com>
Date2014-01-27 10:23 -0600
Message-ID<mailman.6050.1390839851.18130.python-list@python.org>
In reply to#64840
On Mon, Jan 27, 2014 at 1:17 AM, me <noone@all.net> wrote:
> It's the intendation specific requirements that throw me.  I haven't seen
> such a hork since RPG. ;^)

Best I can tell, the only thing RPG and Python have in common is the
fact that they're "programming languages", though I'm being a little
generous to RPG there.  I'll note that RPG (IV) is the only language
I've ever been formally trained in, unfortunately.  I've mostly
forgotten it though, so that's a plus :)

Python's significant indentation is really quite nice and intuitive.
The basic rule of thumb is if a line ends in a colon, the next line
needs to be indented one more level.  If you're continuing the same
logical block, keep the same indention level.  When a logical block is
finished (whether by a raise, continue, break, or return statement, or
just by "falling off the end" of the block), indent the next line one
level less.  Parentheses () (and brackets [] and braces {}) create
what amounts to a 'virtual line', \n characters are basically ignored
until the closing parenthesis is found (as long as they aren't in a
non-triple-quoted string literal).

As long as you don't try to mix tabs and spaces for your indentation
(either is fine on its own, but spaces are generally preferred), it's
very straightforward and allows you to better see the flow of the
program with no question as to whether there is anything hidden within
a block.  I've been using C more in the past two weeks than I really
expected to all this year, and have been bitten more than once by
missing braces.  Indenting intentionally is just a much cleaner,
clearer way to do things (in my opinion, of course).

>> Also, you can iterate over a (sys.argv) in a for
>> loop, replacing 'l', 'idx', and the while loop; something like
>>
>> for arg in a:
>>     if arg == '-h':
>>         print help # help being defined elsewhere...
>>     elif arg == '-hh':
>>         # no really, print help
>>         print 'help'
>
> Understood, except that some parameters take multiple elements...thus why
> I manually reference the indexes.

Try this on for size, then:

a_iter = iter(a)
for arg in a_iter:
    print('current', arg)
    if arg == '-#':
        print('next', next(a_iter))

> Yup.  Every language and platform has multiple arg parsing libraries.
> Didn't feel like taking the time to research any since most of my python
> ramblings are usually pyQT4 bindings to QT4 gui and postgresql apps.

As with most modules in the standard library, I would bet you can get
started using argparse in probably 15 minutes or less.  The online
documentation of the language and standard library is already quite
good, and there is constant effort going into improving it.  You might
also want to play around with the 'help()' function in the interactive
interpreter, it may have answered your original question without ever
having had to ask here:

>>> help(sys.exit)
Help on built-in function exit in module sys:

exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is numeric, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

> Pointing out that sys.exit() raises a low level exception was the point I
> was missing.  Thx!

You're welcome, I'm glad I could help :)


As a general reply to the 'attitude' portion of this thread: "mutual
respect" is the name of the game here.  If you show respect (whether
you've already received it or not), you're likely to receive respect.
If not, don't be surprised by heated responses.  This applies equally
to everyone, I'm not pointing fingers at anyone in particular.

Regards,

-- 
Zach

[toc] | [prev] | [next] | [standalone]


#64877

FromDan Sommers <dan@tombstonezero.net>
Date2014-01-27 16:38 +0000
Message-ID<lc622j$fnl$1@dont-email.me>
In reply to#64876
On Mon, 27 Jan 2014 10:23:49 -0600, Zachary Ware wrote:

>> Understood, except that some parameters take multiple elements...thus
>> why I manually reference the indexes.
> 
> Try this on for size, then:
> 
> a_iter = iter(a)
> for arg in a_iter:
>     print('current', arg)
>     if arg == '-#':
>         print('next', next(a_iter))

And check out add_argument's "nargs" option:

    http://docs.python.org/3/library/argparse.html#nargs

HTH,
Dan

[toc] | [prev] | [next] | [standalone]


#64878

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-01-27 16:45 +0000
Message-ID<mailman.6051.1390841140.18130.python-list@python.org>
In reply to#64840
On 27/01/2014 07:17, me wrote:
> It's the intendation specific requirements that throw me.  I haven't seen
> such a hork since RPG. ;^)
>

Programming with a rocket propelled grenade is vastly superior to 
programming in C++.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#64830

FromTerry Reedy <tjreedy@udel.edu>
Date2014-01-27 01:21 -0500
Message-ID<mailman.6021.1390803712.18130.python-list@python.org>
In reply to#64822
On 1/27/2014 12:04 AM, Gary Herron wrote:

> Do
>    try:
>        ...
>    except Exception,e:
>        print e
> at the absolute minimum.
> (Python 3 syntax would differ slightly, but the advice is the same.)

The 'python 3' syntax
   except Exception as e:
works in 2.7 and perhaps 2.6. So use it unless you need compatibility 
with even earlier versions.

-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#64834

Fromme <noone@all.net>
Date2014-01-27 06:42 +0000
Message-ID<52e5ffcd$0$29510$862e30e2@ngroups.net>
In reply to#64830
On Mon, 27 Jan 2014 01:21:41 -0500, Terry Reedy wrote:

> On 1/27/2014 12:04 AM, Gary Herron wrote:
> 
>> Do
>>    try:
>>        ...
>>    except Exception,e:
>>        print e
>> at the absolute minimum.
>> (Python 3 syntax would differ slightly, but the advice is the same.)
> 
> The 'python 3' syntax
>    except Exception as e:
> works in 2.7 and perhaps 2.6. So use it unless you need compatibility
> with even earlier versions.


My point of contention isn't so much about what specific syntax I should 
be using as much as it is about being allowed to use a syntax that gives 
erroneous results without triggering a syntax violation.  If the bare 
except: clause is syntactically legal then it should yield deterministic 
results based on a well defined language specification, right?  It's 
looking very much like "except:" is undefined behaviour.

kind regards

[toc] | [prev] | [next] | [standalone]


#64843

FromEthan Furman <ethan@stoneleaf.us>
Date2014-01-26 23:08 -0800
Message-ID<mailman.6029.1390807885.18130.python-list@python.org>
In reply to#64834
On 01/26/2014 10:42 PM, me wrote:
>
> My point of contention isn't so much about what specific syntax I should
> be using as much as it is about being allowed to use a syntax that gives
> erroneous results without triggering a syntax violation.  If the bare
> except: clause is syntactically legal then it should yield deterministic
> results based on a well defined language specification, right?  It's
> looking very much like "except:" is undefined behaviour.

There is nothing undefined about it.  `except:` catches everything.  Occasionally there is a good reason to do it that 
way, but under typical circumstances you tell 'except' which exceptions you are prepared to deal with.

--
~Ethan~

[toc] | [prev] | [next] | [standalone]


#64835

Fromme <noone@all.net>
Date2014-01-27 06:46 +0000
Message-ID<52e600ab$0$29542$862e30e2@ngroups.net>
In reply to#64822
In any case, thanks for the answers guys.  I'm satisfied that the except: 
syntax yields undefined behavior, and in my mind it shouldn't be 
syntactically allowed then.

Updating to Exception,e or Exception as e fixes the problem.

[toc] | [prev] | [next] | [standalone]


#64837

FromZachary Ware <zachary.ware+pylist@gmail.com>
Date2014-01-27 00:55 -0600
Message-ID<mailman.6026.1390806119.18130.python-list@python.org>
In reply to#64835
On Mon, Jan 27, 2014 at 12:46 AM, me <noone@all.net> wrote:
>
> In any case, thanks for the answers guys.  I'm satisfied that the except:
> syntax yields undefined behavior, and in my mind it shouldn't be
> syntactically allowed then.

It's not undefined, though; it is explicitly defined.  See my other
message, and here are a couple other places to skim through:
http://docs.python.org/2/tutorial/errors.html and
http://docs.python.org/2/library/exceptions.html

-- 
Zach

[toc] | [prev] | [next] | [standalone]


Page 1 of 3  [1] 2 3  Next page →

Back to top | Article view | comp.lang.python


csiph-web