Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-09 Thread Jon Ribbens via Python-list
On 2024-09-08, Greg Ewing wrote: > On 8/09/24 9:20 am, Karsten Hilbert wrote: >> try: >> do something >> except: >> log something >> finally: >> .commit() >> >> cadence is fairly Pythonic and elegant in that it ensures the >> the .commit() wil

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-09 Thread Karsten Hilbert via Python-list
Am Mon, Sep 09, 2024 at 01:48:32PM +1200 schrieb Greg Ewing via Python-list: > That code doesn't inspire much confidence in me. It's far too > convoluted with too much micro-management of exceptions. It is catching two exceptions, re-raising both of them, except for re-raising one of them as anot

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-09 Thread Karsten Hilbert via Python-list
Am Mon, Sep 09, 2024 at 01:48:32PM +1200 schrieb Greg Ewing via Python-list: > That code doesn't inspire much confidence in me. It's far too > convoluted with too much micro-management of exceptions. > > I would much prefer to have just *one* place where exceptions are > caught and logged. I am o

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-08 Thread Greg Ewing via Python-list
On 9/09/24 2:13 am, Karsten Hilbert wrote: For what it's worth here's the current state of code: That code doesn't inspire much confidence in me. It's far too convoluted with too much micro-management of exceptions. I would much prefer to have just *one* place where exceptions are caught and l

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-08 Thread Greg Ewing via Python-list
On 8/09/24 11:03 pm, Jon Ribbens wrote: On 2024-09-08, Greg Ewing wrote: try: do something .commit() except: log something .rollback() What if there's an exception in your exception handler? I'd put the rollback in the 'finally' handler, so it's always called.

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-08 Thread Karsten Hilbert via Python-list
> >Boring and repetitive and safe(r): > > > > try: > > do something > > except: > > log something > > try: > > .commit() > > except: > > log something > > > >I even

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-08 Thread Rob Cliffe via Python-list
itive and safe(r): try: do something except: log something try: .commit() except: log something I eventually opted for the last version, except for factoring out the second try: except: block. Best, Ka

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-08 Thread Karsten Hilbert via Python-list
Am Sun, Sep 08, 2024 at 12:48:50PM +1200 schrieb Greg Ewing via Python-list: > On 8/09/24 9:20 am, Karsten Hilbert wrote: > > try: > > do something > > except: > > log something > > finally: > > .commit() > > > >cadence is fairly Pythonic and elegant

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-08 Thread Karsten Hilbert via Python-list
Am Sun, Sep 08, 2024 at 12:48:50PM +1200 schrieb Greg Ewing via Python-list: > On 8/09/24 9:20 am, Karsten Hilbert wrote: > > try: > > do something > > except: > > log something > > finally: > > .commit() > > > >cadence is fairly Pythonic and elegant

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-07 Thread Greg Ewing via Python-list
On 8/09/24 9:20 am, Karsten Hilbert wrote: try: do something except: log something finally: .commit() cadence is fairly Pythonic and elegant in that it ensures the the .commit() will always be reached regardless of exception

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-07 Thread Karsten Hilbert via Python-list
something Boring and repetitive and safe(r): try: do something except: log something try: .commit() except: log something I eventually opted for the last version, except for factoring out the second try: exc

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-07 Thread Karsten Hilbert via Python-list
Am Sat, Sep 07, 2024 at 01:03:34PM -0700 schrieb Adrian Klaver: > In the case you show you are doing commit() before the close() so any errors > in the > transactions will show up then. My first thought would be to wrap the > commit() in a > try/except and deal with error the

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-07 Thread Karsten Hilbert via Python-list
Am Sat, Sep 07, 2024 at 09:46:03AM -0700 schrieb Adrian Klaver: > >unto now I had been thinking this is a wise idiom (in code > >that needs not care whether it fails to do what it tries to > >do^1): > > > > conn = psycopg2.connection(...) > > In the above do you have: > > https://www.psycopg.o

Re: psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-07 Thread Rob Cliffe via Python-list
would put the curs.execute and the conn.commit in separate try...except blocks.  That way you know which one failed, and can put appropriate info in the log, which may help trouble-shooting. (The general rule is to keep try...except blocks small.  And of course only catch the exceptions you are

psycopg2: proper positioning of .commit() within try: except: blocks

2024-09-07 Thread Karsten Hilbert via Python-list
Dear all, unto now I had been thinking this is a wise idiom (in code that needs not care whether it fails to do what it tries to do^1): conn = psycopg2.connection(...) curs = conn.cursor() try: curs.execute(SOME_SQL) except PSYCOPG2-Exception:

Re: try/except in loop

2020-11-27 Thread Cameron Simpson
I had to do this with a different API the toehr year, and made this method: def auth_token(self): ''' Obtain a current auth token [...] Refreshes the cached token if stale. ''' while True: with self._auth_token_lock: token = self

Re: try/except in loop

2020-11-27 Thread Jason Friedman
nt.folder('0').get_items(): >> logger.debug("Using existing access token.") >> return access_token >> >> # So I use try/except >> try: >> for _ in client.folder('0').get_items(): >> logger.debug("Using exist

Re: try/except in loop

2020-11-27 Thread Bob Gailer
or _ in client.folder('0').get_items(): > > logger.debug("Using existing access token.") > > return access_token > > > # So I use try/except > > try: > > for _ in client.folder('0').get_items(): > > logger.debug("Using exi

try/except in loop

2020-11-27 Thread Jason Friedman
have an expired access token. # This next line does not throw an error: client.folder('0').get_items() # But iteration does (maybe this is a lazy fetch?) for _ in client.folder('0').get_items(): logger.debug("Using existing access token.") return access_token

Re: try..except or type() or isinstance()?

2020-08-16 Thread Alexa Oña
n-list@python.org Asunto: Re: try..except or type() or isinstance()? On Sun, 16 Aug 2020 09:40:12 +0200 Manfred Lotz wrote: > On Sat, 15 Aug 2020 12:20:48 -0400 > Dennis Lee Bieber wrote: > > > On Sat, 15 Aug 2020 15:31:56 +0200, Manfred Lotz > > declaimed the following: &

Re: try..except or type() or isinstance()?

2020-08-16 Thread Manfred Lotz
On Sun, 16 Aug 2020 09:40:12 +0200 Manfred Lotz wrote: > On Sat, 15 Aug 2020 12:20:48 -0400 > Dennis Lee Bieber wrote: > > > On Sat, 15 Aug 2020 15:31:56 +0200, Manfred Lotz > > declaimed the following: > > > > >On Sat, 15 Aug 2020 11:47:03 +0200 > > >Sibylle Koczian wrote: > > > > >

Re: try..except or type() or isinstance()?

2020-08-16 Thread Manfred Lotz
On 15 Aug 2020 14:49:48 GMT r...@zedat.fu-berlin.de (Stefan Ram) wrote: > Manfred Lotz writes: > >Here a minimal example > > main.py > > source=""" > sehr gut > 1 > """[ 1: -1 ].split( "\n" ) > > class grades: > names =[ "sehr gut" ] > @staticmethod > def is_numeric( text ): >

Re: try..except or type() or isinstance()?

2020-08-16 Thread Manfred Lotz
On Sat, 15 Aug 2020 12:20:48 -0400 Dennis Lee Bieber wrote: > On Sat, 15 Aug 2020 15:31:56 +0200, Manfred Lotz > declaimed the following: > > >On Sat, 15 Aug 2020 11:47:03 +0200 > >Sibylle Koczian wrote: > > > > >> if the value comes from a file, isn't it a > >> string in any case? A string

Re: try..except or type() or isinstance()?

2020-08-15 Thread Manfred Lotz
On Sat, 15 Aug 2020 11:47:03 +0200 Sibylle Koczian wrote: > Am 15.08.2020 um 10:14 schrieb Manfred Lotz: > > Hi Chris, > > Thanks a lot for you advice. > > > > On Sat, 15 Aug 2020 16:15:29 +1000 > > Chris Angelico wrote: > > > >> On Sat, Aug 15, 2020 at 3:36 PM Manfred Lotz > >> wrote: > >>

Re: try..except or type() or isinstance()?

2020-08-15 Thread Sibylle Koczian
Am 15.08.2020 um 10:14 schrieb Manfred Lotz: Hi Chris, Thanks a lot for you advice. On Sat, 15 Aug 2020 16:15:29 +1000 Chris Angelico wrote: On Sat, Aug 15, 2020 at 3:36 PM Manfred Lotz wrote: I have an object which I could initialize providind an int or a str. ... For my use case I do

Re: try..except or type() or isinstance()?

2020-08-15 Thread Manfred Lotz
. > >> > >> I am not sure which of the following is best to use > >> - try/except > >> - if type(int)... > >> - if isinstance(v, int) > >> > >> Here a minimal example > >> > >> def get_id(fromname): > >&g

Re: try..except or type() or isinstance()?

2020-08-15 Thread Manfred Lotz
f the following is best to use > > - try/except > > - if type(int)... > > - if isinstance(v, int) > > > > Here a minimal example > > > > def get_id(fromname): > > # do something with `fromname` > > return 0 > > > > def get_name

Re: try..except or type() or isinstance()?

2020-08-14 Thread Peter Otten
Chris Angelico wrote: > On Sat, Aug 15, 2020 at 3:36 PM Manfred Lotz wrote: >> >> I have an object which I could initialize providind an int or a str. >> >> I am not sure which of the following is best to use >> - try/except >> - if type(int)... >>

Re: try..except or type() or isinstance()?

2020-08-14 Thread Chris Angelico
On Sat, Aug 15, 2020 at 3:36 PM Manfred Lotz wrote: > > I have an object which I could initialize providind an int or a str. > > I am not sure which of the following is best to use > - try/except > - if type(int)... > - if isinstance(v, int) > > Here a minimal exam

try..except or type() or isinstance()?

2020-08-14 Thread Manfred Lotz
I have an object which I could initialize providind an int or a str. I am not sure which of the following is best to use - try/except - if type(int)... - if isinstance(v, int) Here a minimal example def get_id(fromname): # do something with `fromname` return 0 def get_name(fromid

Re: try except inside a with open

2018-07-21 Thread Cameron Simpson
Please try to preserve the attribution lines of previous authors. The inner quote below comes from Steven D'Aprano. On 21Jul2018 15:13, Ganesh Pal wrote: (1) Since this function always returns True (if it returns at all), what is the point? There's no point checking the return result, since it

Re: try except inside a with open

2018-07-21 Thread Ganesh Pal
> > > > (1) Since this function always returns True (if it returns at all), what > is the point? There's no point checking the return result, since it's > always true, so why bother returning anything? > > If I don't return anything from a function it returns None. But would it be better if for

Re: try except inside a with open

2018-07-20 Thread Steven D'Aprano
ror occurs, you get the benefit of the full traceback not just the abbreviated error message. Tracebacks are printed to standard error, not standard out, so they can be redirected to a log file more easily. Or you can set an error handler for your entire application, so that in production any uncaug

Re: try except inside a with open

2018-07-20 Thread MRAB
On 2018-07-20 18:59, Ganesh Pal wrote: Dear python Friends, I need a quick suggestion on the below code. def modify_various_line(f): """ Try modifiying various line """ try: f.write('0123456789abcdef') f.seek(5) # Go to the 6th byte in the file print f.

try except inside a with open

2018-07-20 Thread Ganesh Pal
Dear python Friends, I need a quick suggestion on the below code. def modify_various_line(f): """ Try modifiying various line """ try: f.write('0123456789abcdef') f.seek(5) # Go to the 6th byte in the file print f.read(1) f.seek(-3, 2) # Go to the 3rd

Re: variable scope in try ... EXCEPT block.

2018-07-13 Thread Chris Angelico
On Fri, Jul 13, 2018 at 10:43 PM, Ed Kellett wrote: > On 2018-07-12 18:00, Chris Angelico wrote: >> What do you mean by "fix"? Make the 'x' bind eagerly? That would break >> basically every other use of closures. > > No. I mean make each x a new variable--closures would work as before, > for-loops

Re: variable scope in try ... EXCEPT block.

2018-07-13 Thread Ed Kellett
On 2018-07-12 18:00, Chris Angelico wrote: > What do you mean by "fix"? Make the 'x' bind eagerly? That would break > basically every other use of closures. No. I mean make each x a new variable--closures would work as before, for-loops would change. If we have subscopes, it seems natural that ent

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Chris Angelico
.err.1", ".err.2"), so they won't conflict with each other. >> >> ChrisA > > Simpler is better. The point is that something like this would accomplish > both: > > 1. Break the reference cycle. > > 2. Avoid what is (IMHO) an unexpected behavior of a

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread codewizard
> thus cannot ever conflict.) Once you exit the except block, the > previous value will magically reappear, because it didn't go anywhere. > Multiple except blocks - nested or separate - would have separate > names (".err.1", ".err.2"), so they won't conflict with each other. > > ChrisA Simpler is better. The point is that something like this would accomplish both: 1. Break the reference cycle. 2. Avoid what is (IMHO) an unexpected behavior of a variable declared prior to try/except disappearing after getting shadowed by "except as". Regards, Igor. -- https://mail.python.org/mailman/listinfo/python-list

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread aleiphoenix
kind of problem in Python3. On Thursday, July 12, 2018 at 6:02:27 PM UTC+8, Steven D'Aprano wrote: > > You can work around this by explicitly assigning to another local > variable: > > try: > ... > except Exception as e: > err = e # only &q

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Chris Angelico
On Fri, Jul 13, 2018 at 8:10 AM, wrote: > On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote: >> aleiphoenix writes: >> >> [snip] >> >> When an exception has been assigned using as target, it is cleared at >> the end of the except clause. This is as if >> >> except E as N:

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Ben Bacarisse
Just word on quoting... codewiz...@gmail.com writes: > On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote: >> >> [snip] You cut everything I wrote. What you left is what I quoted from the Python documentation. In fairness to the authors you should probably have cut the attrib

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread codewizard
On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote: > aleiphoenix writes: > > [snip] > > When an exception has been assigned using as target, it is cleared at > the end of the except clause. This is as if > > except E as N: > foo > > was translated to > > excep

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Chris Angelico
On Thu, Jul 12, 2018 at 11:23 PM, Ed Kellett wrote: > Could we fix: > > for x in something: > blah(lambda a: a + x) > > while we're at it? What do you mean by "fix"? Make the 'x' bind eagerly? That would break basically every other use of closures. ChrisA -- https://mail.python.org/mailma

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Ed Kellett
On 2018-07-12 14:03, Chris Angelico wrote: > Dealing with reference cycles is generally done *periodically* rather > than immediately (CPython disposes of unreferenced objects immediately > upon last deref). You can avoid having a dedicated cycle detection > pass by using a mark-and-sweep GC, but t

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Chris Angelico
ed) is implicitly >> deleted. >> >> You can work around this by explicitly assigning to another local >> variable: >> >> try: >> ... >> except Exception as e: >> err = e # only "e" will be deleted when we exit t

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Ed Kellett
, it is not a new scope, and yes, it is intentional. It's a nasty hack, > but a *necessary* nasty hack: when the except block exits, the "err" > local variable (or whatever it happens to be called) is implicitly > deleted. > > You can work around th

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Steven D'Aprano
t a *necessary* nasty hack: when the except block exits, the "err" local variable (or whatever it happens to be called) is implicitly deleted. You can work around this by explicitly assigning to another local variable: try: ... except Exception as e: err = e

Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Ben Bacarisse
aleiphoenix writes: > suppose following code running with Python-3.4.8 and Python-3.6.5 > > > # -*- coding: utf-8 -*- > > > def hello(): > err = None > print('0: {}'.format(locals())) > try: > b = 2 > print('1: {}'.format(locals())) > raise ValueError() >

variable scope in try ... EXCEPT block.

2018-07-12 Thread aleiphoenix
suppose following code running with Python-3.4.8 and Python-3.6.5 # -*- coding: utf-8 -*- def hello(): err = None print('0: {}'.format(locals())) try: b = 2 print('1: {}'.format(locals())) raise ValueError() print('2: {}'.format(locals())) except

Re: try-except syntax

2018-04-06 Thread ElChino
Steven D'Aprano wrote: imp.find_module is deprecated and should not be used in new code. ... try: block except (ImportError, RuntimeError): block Thanks Steven and others who replied. Looks more elegant. By the way, RuntimeError is almost never something you want t

Re: try-except syntax

2018-04-05 Thread Steven D'Aprano
On Thu, 05 Apr 2018 23:04:18 +0200, ElChino wrote: > I'm trying to simplify a try-except construct. E.g. how come this: >try: > _x, pathname, _y = imp.find_module (mod, mod_path) > return ("%s" % pathname) imp.find_module is deprecated and should not be

Re: try-except syntax

2018-04-05 Thread Gregory Ewing
Ben Bacarisse wrote: Anyway, to coalesce two or more exception handlers, you are probably looking for except (ImportError, RuntimeError): To the OP: Are you sure you really want to mask RuntimeError here? Usually it means something has gone seriously wrong, and is a symptom that shouldn't be

Re: try-except syntax

2018-04-05 Thread Ben Bacarisse
ElChino writes: > I'm trying to simplify a try-except construct. E.g. how come > this: > try: > _x, pathname, _y = imp.find_module (mod, mod_path) > return ("%s" % pathname) > except ImportError: > pass > except RuntimeError: >

Re: try-except syntax

2018-04-05 Thread Ian Kelly
On Thu, Apr 5, 2018 at 3:04 PM, ElChino wrote: > I'm trying to simplify a try-except construct. E.g. how come > this: > try: > _x, pathname, _y = imp.find_module (mod, mod_path) > return ("%s" % pathname) > except ImportError: > pass

Re: try-except syntax

2018-04-05 Thread Rob Gaddi
On 04/05/2018 02:04 PM, ElChino wrote: I'm trying to simplify a try-except construct. E.g. how come this:   try:     _x, pathname, _y = imp.find_module (mod, mod_path)     return ("%s" % pathname)   except ImportError:     pass   except RuntimeError:     pass     return

try-except syntax

2018-04-05 Thread ElChino
I'm trying to simplify a try-except construct. E.g. how come this: try: _x, pathname, _y = imp.find_module (mod, mod_path) return ("%s" % pathname) except ImportError: pass except RuntimeError: pass return ("") Cannot be simplified into this:

Re: Aw: Try: Except: evaluates to True every time

2017-11-05 Thread Steve D'Aprano
On Sun, 5 Nov 2017 09:53 pm, Karsten Hilbert wrote: > On Sun, Nov 05, 2017 at 11:28:44AM +1100, Steve D'Aprano wrote: > >> > Try in an interactive interpreter: >> > >> >python> "a string" is True >> >> Did you try that yourself? > > Yes, eventually, which is why I corrected myself publicly

Re: Aw: Try: Except: evaluates to True every time

2017-11-05 Thread Karsten Hilbert
On Sun, Nov 05, 2017 at 11:28:44AM +1100, Steve D'Aprano wrote: > > Try in an interactive interpreter: > > > >python> "a string" is True > > Did you try that yourself? Yes, eventually, which is why I corrected myself publicly. However, while it doesn't return True (as I mistakenly suggeste

Re: Aw: Try: Except: evaluates to True every time

2017-11-04 Thread Steve D'Aprano
On Sun, 5 Nov 2017 03:07 am, Karsten Hilbert wrote: > Try in an interactive interpreter: > >python> "a string" is True Did you try that yourself? -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailm

Re: Try: Except: evaluates to True every time

2017-11-04 Thread Karsten Hilbert
On Sat, Nov 04, 2017 at 05:07:26PM +0100, Karsten Hilbert wrote: > Try in an interactive interpreter: > >python> "a string" is True Or, rather, python> if 'a string': print 'success' Sorry, Karsten -- GPG key ID E4071346 @ eu.pool.sks-keyservers.net E167 67FD A291 2BEA 73BD 4537

Aw: Try: Except: evaluates to True every time

2017-11-04 Thread Karsten Hilbert
Try in an interactive interpreter: python> "a string" is True Karsten > Gesendet: Samstag, 04. November 2017 um 16:31 Uhr > Von: "brandon wallace" > An: python-list@python.org > Betreff: Try: Except: evaluates to True every time > > > I have t

Re: Try: Except: evaluates to True every time

2017-11-04 Thread Steve D'Aprano
On Sun, 5 Nov 2017 02:31 am, brandon wallace wrote: > > I have this code that tests a server to see if it is listening on port 123 > runs and evaluates to True every time. Even if the server does not exist but > it is not supposed to do that. I am getting no error message at all. What is > going

Try: Except: evaluates to True every time

2017-11-04 Thread brandon wallace
I have this code that tests a server to see if it is listening on port 123 runs and evaluates to True every time. Even if the server does not exist but it is not supposed to do that. I am getting no error message at all. What is going on with this code?     #!/usr/bin/env python import socket

Re: Try: Except: evaluates to True every time

2017-11-04 Thread Chris Angelico
On Sun, Nov 5, 2017 at 2:31 AM, brandon wallace wrote: > > I have this code that tests a server to see if it is listening on port 123 > runs and evaluates to True every time. Even if the server does not exist but > it is not supposed to do that. I am getting no error message at all. What is > g

Re: Issues with in try except and excel spreadsheet

2017-03-14 Thread Rhodri James
On 14/03/17 14:26, padawanweb...@gmail.com wrote: As an example, If I have the excel file open and there is data that needs to be written to the excel file than the exception will catch this error: IOError: [Errno 13] Permission denied: 'C:\\Users\\Administrator\\Desktop\\Version5.0\\DeviceTra

Re: Issues with in try except and excel spreadsheet

2017-03-14 Thread padawanwebdev
On Tuesday, March 14, 2017 at 4:42:39 AM UTC-7, Rhodri James wrote: > On 13/03/17 20:37, padawanweb...@gmail.com wrote: > > On Monday, March 13, 2017 at 11:10:36 AM UTC-7, Rhodri James wrote: > >> On 13/03/17 17:40, padawanweb...@gmail.com wrote: > >>> Hello, I'm

Re: Issues with in try except and excel spreadsheet

2017-03-14 Thread Rhodri James
On 13/03/17 20:37, padawanweb...@gmail.com wrote: On Monday, March 13, 2017 at 11:10:36 AM UTC-7, Rhodri James wrote: On 13/03/17 17:40, padawanweb...@gmail.com wrote: Hello, I'm having a problem with a try except inside a while loop. The problem I see occuring has to do with an excel

Re: Issues with in try except and excel spreadsheet

2017-03-13 Thread padawanwebdev
On Monday, March 13, 2017 at 11:10:36 AM UTC-7, Rhodri James wrote: > On 13/03/17 17:40, padawanweb...@gmail.com wrote: > > Hello, I'm having a problem with a try except inside a while loop. The > > problem I see occuring has to do with an excel file the script tries to &g

Re: Issues with in try except and excel spreadsheet

2017-03-13 Thread Rhodri James
On 13/03/17 17:40, padawanweb...@gmail.com wrote: Hello, I'm having a problem with a try except inside a while loop. The problem I see occuring has to do with an excel file the script tries to write to while the excel file is open. The exception captures and gives an error: OError: [Err

Issues with in try except and excel spreadsheet

2017-03-13 Thread padawanwebdev
Hello, I'm having a problem with a try except inside a while loop. The problem I see occuring has to do with an excel file the script tries to write to while the excel file is open. The exception captures and gives an error: OError: [Errno 13] Permission denied:'C:\\Users\\Adm

Re: try-except with no exceptions

2016-10-15 Thread Nobody
On Thu, 13 Oct 2016 15:06:25 +0100, Daiyue Weng wrote: > I know that such try-catch usage is generally a bad practice, since it > can't locate the root of the exceptions. > > I am wondering how to correct the code above Either identify the specific exceptions you're expecting, or if you're inter

Re: try-except with no exceptions

2016-10-13 Thread Ben Finney
statements which will encounter those conditions. Move everything else outside the ‘try … except …’ altogether. -- \ “In prayer, it is better to have a heart without words than | `\ words without heart.” —Moh

Re: try-except with no exceptions

2016-10-13 Thread Peter Otten
Daiyue Weng wrote: > Hi, I have seen code using try_except with no exceptions, > > from dateutil import parser > > try: > from_date = datetime.datetime.strptime(parameters['from_date'], > '%Y-%m-%d %H:%M:%S.%f') > to_date = datetime.datetime.strptime(parameters['to_date'], > '%Y-%m-%d %H

Re: try-except with no exceptions

2016-10-13 Thread Jussi Piitulainen
Daiyue Weng writes: > Hi, I have seen code using try_except with no exceptions, > > from dateutil import parser > > try: > from_date = datetime.datetime.strptime(parameters['from_date'], > '%Y-%m-%d %H:%M:%S.%f') > to_date = datetime.datetime.strptime(parameters['to_date'], > '%Y-%m-%d %H:

try-except with no exceptions

2016-10-13 Thread Daiyue Weng
Hi, I have seen code using try_except with no exceptions, from dateutil import parser try: from_date = datetime.datetime.strptime(parameters['from_date'], '%Y-%m-%d %H:%M:%S.%f') to_date = datetime.datetime.strptime(parameters['to_date'], '%Y-%m-%d %H:%M:%S.%f') except: from_date = pa

Re: Possible to capture cgitb style output in a try/except section?

2016-07-26 Thread Malcolm Greene
Hi Steven and Peter, Steven: Interestingly (oddly???) enough, the output captured by hooking the cgitb handler on my system appears to be shorter than the default cgitb output. You can see this yourself via this tiny script: import cgitb cgitb.enable(format='text') x = 1/0 The solution I came up

Re: Possible to capture cgitb style output in a try/except section?

2016-07-26 Thread Peter Otten
Malcolm Greene wrote: > Is there a way to capture cgitb's extensive output in an except clause > so that cgitb's detailed traceback output can be logged *and* the except > section can handle the exception so the script can continue running? > > My read of the cgitb documentation leads me to beli

Re: Possible to capture cgitb style output in a try/except section?

2016-07-26 Thread Steven D'Aprano
On Tue, 26 Jul 2016 08:11 pm, Malcolm Greene wrote: > Is there a way to capture cgitb's extensive output in an except clause > so that cgitb's detailed traceback output can be logged *and* the except > section can handle the exception so the script can continue running? Anything that cgitb captur

Possible to capture cgitb style output in a try/except section?

2016-07-26 Thread Malcolm Greene
Is there a way to capture cgitb's extensive output in an except clause so that cgitb's detailed traceback output can be logged *and* the except section can handle the exception so the script can continue running? My read of the cgitb documentation leads me to believe that the only way I can get c

Re: AttributeError into a bloc try-except AttributeError

2016-06-12 Thread Vincent Vande Vyvre
Le 12/06/16 09:20, Vincent Vande Vyvre a écrit : Hi, I have a strange behaviour in my code. In an interactive session, the result is as expected: Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = No

AttributeError into a bloc try-except AttributeError

2016-06-12 Thread Vincent Vande Vyvre
Hi, I have a strange behaviour in my code. In an interactive session, the result is as expected: Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = None >>> try: ... _ = a.value ... except Attribu

Re: usage of try except for review.

2016-03-01 Thread Steven D'Aprano
On Mon, 29 Feb 2016 07:13 pm, Ganesh Pal wrote: > def run_cmd_and_verify(cmd, timeout=1000): > try: > out, err, ret = run(cmd, timeout=timeout) > assert ret ==0,"ERROR (ret %d): " \ > " \nout: %s\nerr: %s\n" % (ret, out, err) Do not use assert for error checki

Re: usage of try except for review.

2016-03-01 Thread Steven D'Aprano
On Tue, 1 Mar 2016 04:38 am, Chris Angelico wrote: > On Tue, Mar 1, 2016 at 4:34 AM, Ganesh Pal wrote: >> On Mon, Feb 29, 2016 at 10:10 PM, Dennis Lee Bieber >> wrote: >> >>> Ask yourself: Will my program still work if I remove all the >>> assert >>> statements. If the answer is

Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
> I have tried down the code to Read "I have tried down the code to " as I have trimmed down the code as below Ganesh -- https://mail.python.org/mailman/listinfo/python-list

Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
> No, Dennis was correct. You should assume that "assert" can > potentially be replaced with "pass" and your program will continue to > work. Thanks Chris for clarifying Dennis point of view , >>try: >>if not run_cmd_and_verify(cmd, timeout=3600): > > Since your vers

Re: usage of try except for review.

2016-02-29 Thread Chris Angelico
On Tue, Mar 1, 2016 at 4:34 AM, Ganesh Pal wrote: > On Mon, Feb 29, 2016 at 10:10 PM, Dennis Lee Bieber > wrote: > >> Ask yourself: Will my program still work if I remove all the assert >> statements. If the answer is "No", then you should not be using an assert. > > You meant if the answ

Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
e for loop because in the actual program there are 100 of command and putting them in a list is quite easy and running over with the same operation saves many lines of code , Cam I modify it something like a try except with pass in the except ? or any suggestions for cmd in [

Re: usage of try except for review.

2016-02-29 Thread Ganesh Pal
ption as e: logging.error("Failed to run %s got %s" % (cmd, e)) return False return True #script_10.py Failed to run mount /nfs got ERROR (ret 1): out: host-44-3 exited with status 1 err: host-44-3: mount_efs: on /nfs: efs is already mounted 3. my function def has 1000 but Iam using 3600 in the calling fnx etc , Time out value are overwritten ? 4. Any further improvement particularly on try -except ? Regards, Ganesh -- https://mail.python.org/mailman/listinfo/python-list

usage of try except for review.

2016-02-29 Thread Ganesh Pal
: %s\nerr: %s\n" % (ret, out, err) except Exception as e: logging.error("Failed to run %s got %s" % (cmd, e)) return False return True #script_10.py Failed to run mount /nfs got ERROR (ret 1): out: host-44-3 exited with status 1 err: hos

Re: Try Except Specific Error Messages

2015-05-02 Thread Gary Herron
On 04/30/2015 04:27 PM, brandon wallace wrote: Hi, I am try to get more specific error messages using try/except. I ran this code with the cable unplugged to see the error message. I got #!/usr/bin/env python3 import urllib.request webpage = urllib.request.urlopen("http://fakewebsit

Try Except Specific Error Messages

2015-05-02 Thread brandon wallace
Hi,   I am try to get more specific error messages using try/except. I ran this code with the cable unplugged to see the error message. I got #!/usr/bin/env python3 import urllib.request webpage = urllib.request.urlopen("http://fakewebsite.com/";) text = webpage.read().decode("

Re: try..except with empty exceptions

2015-04-12 Thread Cameron Simpson
On 12Apr2015 17:00, Chris Angelico wrote: On Sun, Apr 12, 2015 at 4:33 PM, Cameron Simpson wrote: [...] That's what try/finally is for. You can do your cleanup without caring exactly what was raised. Hmm, yes. [...] However, my Asynchron class really is a little special. I use Asynchron t

Re: try..except with empty exceptions

2015-04-12 Thread Chris Angelico
On Sun, Apr 12, 2015 at 4:33 PM, Cameron Simpson wrote: > On 12Apr2015 09:21, Chris Angelico wrote: >> Fair enough. Do you know how often you actually catch stuff that >> wouldn't be caught by "except BaseException:"? > > > I don't know and I'm not sure I care (but discussion below). I would need

Re: try..except with empty exceptions

2015-04-11 Thread Cameron Simpson
On 12Apr2015 14:18, Steven D'Aprano wrote: On Sun, 12 Apr 2015 09:08 am, Cameron Simpson wrote: Also, IMO, a bare "except:" syntax is far more pleasing to the eye than "except magic_exception_name_that+gets_everything:". And that is exactly what makes bare excepts an attractive nuisance! I'

Re: try..except with empty exceptions

2015-04-11 Thread Cameron Simpson
On 12Apr2015 16:33, Cameron Simpson wrote: Finally, if we were to expunge support for "except:", one would also need a cast iron guarrentee that no exception could possibly occur which was not a subclass of BaseException. I'd expect that to mean that "raise" of a non-instance of BaseException

Re: try..except with empty exceptions

2015-04-11 Thread Cameron Simpson
On 12Apr2015 09:21, Chris Angelico wrote: On Sun, Apr 12, 2015 at 9:08 AM, Cameron Simpson wrote: Catching all exceptions isn't terribly common, _except_ in service routines that wrap "unknown" operations. Classic example from my Asynchron class: [...] try: r = func(*a, **kw)

Re: try..except with empty exceptions

2015-04-11 Thread Steven D'Aprano
On Sun, 12 Apr 2015 09:08 am, Cameron Simpson wrote: > Also, IMO, a bare "except:" syntax is far more pleasing to the eye than > "except magic_exception_name_that+gets_everything:". And that is exactly what makes bare excepts an attractive nuisance! I'm going to channel a newbie, cowboy or just

Re: try..except with empty exceptions

2015-04-11 Thread Steven D'Aprano
quot;. Life is tough for library authors who want to support old code :-( The solution, as I see it, would be to extract only the bits of your code that does the exception handling, and split it into two separate files: # catcher2.py from common import dostuff try: ... except BaseExce

Re: try..except with empty exceptions

2015-04-11 Thread Chris Angelico
On Sun, Apr 12, 2015 at 9:08 AM, Cameron Simpson wrote: > Catching all exceptions isn't terribly common, _except_ in service routines > that wrap "unknown" operations. Classic example from my Asynchron class: > >def call(self, func, *a, **kw): > ''' Have the Asynchron call `func(*a,**kw)`

  1   2   3   4   5   6   >