From 90e206fe98d7c057316b272f651373376a2d3539 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Cardona?= Date: Wed, 16 Jul 2014 08:53:31 +0200 Subject: Use "except as" syntax (related to #264017) Requires python >= 2.6. --- changelog.py | 2 +- clcommands.py | 6 +++--- configuration.py | 2 +- corbautils.py | 4 ++-- daemon.py | 2 +- date.py | 2 +- modutils.py | 4 ++-- pyro_ext.py | 4 ++-- pytest.py | 16 ++++++++-------- shellutils.py | 4 ++-- test/data/module.py | 2 +- testlib.py | 20 ++++++++++---------- urllib2ext.py | 2 +- 13 files changed, 35 insertions(+), 35 deletions(-) diff --git a/changelog.py b/changelog.py index 74f5124..d912374 100644 --- a/changelog.py +++ b/changelog.py @@ -76,7 +76,7 @@ class Version(tuple): versionstr = versionstr.strip(' :') try: return [int(i) for i in versionstr.split('.')] - except ValueError, ex: + except ValueError as ex: raise ValueError("invalid literal for version '%s' (%s)"%(versionstr, ex)) def __str__(self): diff --git a/clcommands.py b/clcommands.py index 411931b..839ab96 100644 --- a/clcommands.py +++ b/clcommands.py @@ -132,13 +132,13 @@ class CommandLine(dict): self.usage_and_exit(1) try: sys.exit(command.main_run(args, rcfile)) - except KeyboardInterrupt, exc: + except KeyboardInterrupt as exc: print 'Interrupted', if str(exc): print ': %s' % exc, print sys.exit(4) - except BadCommandUsage, err: + except BadCommandUsage as err: print 'ERROR:', err print print command.help() @@ -261,7 +261,7 @@ class Command(Configuration): try: self.check_args(args) self.run(args) - except CommandError, err: + except CommandError as err: self.logger.error(err) return 2 return 0 diff --git a/configuration.py b/configuration.py index 55bce59..ae53b10 100644 --- a/configuration.py +++ b/configuration.py @@ -265,7 +265,7 @@ def _make_input_function(opttype): return None try: return _call_validator(opttype, optdict, None, value) - except optik_ext.OptionValueError, ex: + except optik_ext.OptionValueError as ex: msg = str(ex).split(':', 1)[-1].strip() print 'bad value: %s' % msg return input_validator diff --git a/corbautils.py b/corbautils.py index 8dfb2ba..65c301d 100644 --- a/corbautils.py +++ b/corbautils.py @@ -72,7 +72,7 @@ def register_object_name(object, namepath): name = [CosNaming.NameComponent(id, kind)] try: context = context.bind_new_context(name) - except CosNaming.NamingContext.AlreadyBound, ex: + except CosNaming.NamingContext.AlreadyBound as ex: context = context.resolve(name)._narrow(CosNaming.NamingContext) assert context is not None, \ 'test context exists but is not a NamingContext' @@ -81,7 +81,7 @@ def register_object_name(object, namepath): name = [CosNaming.NameComponent(id, kind)] try: context.bind(name, object._this()) - except CosNaming.NamingContext.AlreadyBound, ex: + except CosNaming.NamingContext.AlreadyBound as ex: context.rebind(name, object._this()) def activate_POA(): diff --git a/daemon.py b/daemon.py index 66a6960..f9f4971 100644 --- a/daemon.py +++ b/daemon.py @@ -77,7 +77,7 @@ def daemonize(pidfile=None, uid=None, umask=077): for i in range(3): try: os.dup2(null, i) - except OSError, e: + except OSError as e: if e.errno != errno.EBADF: raise os.close(null) diff --git a/date.py b/date.py index bd660c0..dfd81a8 100644 --- a/date.py +++ b/date.py @@ -292,7 +292,7 @@ def ustrftime(somedate, fmt='%Y-%m-%d'): return unicode(somedate.strftime(str(fmt)), encoding) else: return somedate.strftime(fmt) - except ValueError, exc: + except ValueError: if somedate.year >= 1900: raise # datetime is not happy with dates before 1900 diff --git a/modutils.py b/modutils.py index 247b164..1ccf09e 100644 --- a/modutils.py +++ b/modutils.py @@ -92,7 +92,7 @@ class LazyObject(object): def __getattribute__(self, attr): try: return super(LazyObject, self).__getattribute__(attr) - except AttributeError, ex: + except AttributeError as ex: return getattr(self._getobj(), attr) def __call__(self, *args, **kwargs): @@ -495,7 +495,7 @@ def is_standard_module(modname, std_path=(STD_LIB_DIR,)): modname = modname.split('.')[0] try: filename = file_from_modpath([modname]) - except ImportError, ex: + except ImportError as ex: # import failed, i'm probably not so wrong by supposing it's # not standard... return 0 diff --git a/pyro_ext.py b/pyro_ext.py index 0f4d279..5204b1b 100644 --- a/pyro_ext.py +++ b/pyro_ext.py @@ -118,7 +118,7 @@ def ns_unregister(nsid, defaultnsgroup=_MARKER, nshost=None): nsgroup, nsid = ns_group_and_id(nsid, defaultnsgroup) try: nsd = locate_ns(nshost) - except errors.PyroError, ex: + except errors.PyroError as ex: # name server not responding _LOGGER.error('can\'t locate pyro name server: %s', ex) else: @@ -159,7 +159,7 @@ def ns_get_proxy(nsid, defaultnsgroup=_MARKER, nshost=None): try: nsd = locate_ns(nshost) pyrouri = nsd.resolve('%s.%s' % (nsgroup, nsid)) - except errors.ProtocolError, ex: + except errors.ProtocolError as ex: raise errors.PyroError( 'Could not connect to the Pyro name server (host: %s)' % nshost) except errors.NamingError: diff --git a/pytest.py b/pytest.py index b30f50e..a84e6f4 100644 --- a/pytest.py +++ b/pytest.py @@ -382,10 +382,10 @@ class PyTester(object): try: restartfile = open(FILE_RESTART, "w") restartfile.close() - except Exception, e: + except Exception: print >> sys.__stderr__, "Error while overwriting \ succeeded test file :", osp.join(os.getcwd(), FILE_RESTART) - raise e + raise # run test and collect information prog = self.testfile(filename, batchmode=True) if exitfirst and (prog is None or not prog.result.wasSuccessful()): @@ -409,10 +409,10 @@ succeeded test file :", osp.join(os.getcwd(), FILE_RESTART) try: restartfile = open(FILE_RESTART, "w") restartfile.close() - except Exception, e: + except Exception: print >> sys.__stderr__, "Error while overwriting \ succeeded test file :", osp.join(os.getcwd(), FILE_RESTART) - raise e + raise modname = osp.basename(filename)[:-3] print >> sys.stderr, (' %s ' % osp.basename(filename)).center(70, '=') try: @@ -422,7 +422,7 @@ succeeded test file :", osp.join(os.getcwd(), FILE_RESTART) options=self.options, outstream=sys.stderr) except KeyboardInterrupt: raise - except SystemExit, exc: + except SystemExit as exc: self.errcode = exc.code raise except testlib.SkipTest: @@ -553,7 +553,7 @@ class DjangoTester(PyTester): return testprog except SystemExit: raise - except Exception, exc: + except Exception as exc: import traceback traceback.print_exc() self.report.failed_to_test_module(filename) @@ -788,7 +788,7 @@ Examples: else: self.testNames = (self.defaultTest, ) self.createTests() - except getopt.error, msg: + except getopt.error as msg: self.usageExit(msg) def runTests(self): @@ -837,7 +837,7 @@ Examples: removeSucceededTests(self.test, succeededtests) finally: restartfile.close() - except Exception, ex: + except Exception as ex: raise Exception("Error while reading succeeded tests into %s: %s" % (osp.join(os.getcwd(), FILE_RESTART), ex)) diff --git a/shellutils.py b/shellutils.py index 69ee1e4..b444e0e 100644 --- a/shellutils.py +++ b/shellutils.py @@ -115,7 +115,7 @@ def mv(source, destination, _action=shutil.move): destination = join(destination, basename(source)) try: _action(source, destination) - except OSError, ex: + except OSError as ex: raise OSError('Unable to move %r to %r (%s)' % ( source, destination, ex)) @@ -254,7 +254,7 @@ def acquire_lock(lock_file, max_try=10, delay=10, max_delay=3600): os.write(fd, str_to_bytes(str(os.getpid())) ) os.close(fd) return True - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST: try: fd = open(lock_file, "r") diff --git a/test/data/module.py b/test/data/module.py index 4e1abce..62de658 100644 --- a/test/data/module.py +++ b/test/data/module.py @@ -29,7 +29,7 @@ class YO: def __init__(self): try: self.yo = 1 - except ValueError, ex: + except ValueError as ex: pass except (NameError, TypeError): raise XXXError() diff --git a/testlib.py b/testlib.py index 1dd7064..8022d28 100644 --- a/testlib.py +++ b/testlib.py @@ -366,7 +366,7 @@ def _handleModuleTearDown(self, result): if tearDownModule is not None: try: tearDownModule() - except Exception, e: + except Exception as e: if isinstance(result, _DebugResult): raise errorName = 'tearDownModule (%s)' % previousModule @@ -394,7 +394,7 @@ def _handleModuleFixture(self, test, result): if setUpModule is not None: try: setUpModule() - except Exception, e: + except Exception as e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True @@ -529,7 +529,7 @@ class TestCase(unittest.TestCase): func(*args, **kwargs) except (KeyboardInterrupt, SystemExit): raise - except unittest.SkipTest, e: + except unittest.SkipTest as e: self._addSkip(result, str(e)) return False except: @@ -596,10 +596,10 @@ class TestCase(unittest.TestCase): restartfile.write(descr+os.linesep) finally: restartfile.close() - except Exception, ex: + except Exception: print >> sys.__stderr__, "Error while saving \ succeeded test into", osp.join(os.getcwd(), FILE_RESTART) - raise ex + raise result.addSuccess(self) finally: # if result.cvg: @@ -656,10 +656,10 @@ succeeded test into", osp.join(os.getcwd(), FILE_RESTART) return 1 except KeyboardInterrupt: raise - except InnerTestSkipped, e: + except InnerTestSkipped as e: result.addSkip(self, e) return 1 - except SkipTest, e: + except SkipTest as e: result.addSkip(self, e) return 0 except: @@ -835,7 +835,7 @@ succeeded test into", osp.join(os.getcwd(), FILE_RESTART) parser = make_parser() try: parser.parse(stream) - except SAXParseException, ex: + except SAXParseException as ex: if msg is None: stream.seek(0) for _ in xrange(ex.getLineNumber()): @@ -876,7 +876,7 @@ succeeded test into", osp.join(os.getcwd(), FILE_RESTART) ParseError = ExpatError try: parse(data) - except (ExpatError, ParseError), ex: + except (ExpatError, ParseError) as ex: if msg is None: if hasattr(data, 'readlines'): #file like object data.seek(0) @@ -1155,7 +1155,7 @@ succeeded test into", osp.join(os.getcwd(), FILE_RESTART) return _assert(excClass, callableObj, *args, **kwargs) try: callableObj(*args, **kwargs) - except excClass, exc: + except excClass as exc: class ProxyException: def __init__(self, obj): self._obj = obj diff --git a/urllib2ext.py b/urllib2ext.py index 08797a4..3e7a36d 100644 --- a/urllib2ext.py +++ b/urllib2ext.py @@ -62,7 +62,7 @@ class HTTPGssapiAuthHandler(urllib2.BaseHandler): if result < 1: raise GssapiAuthError("HTTPGssapiAuthHandler: step 2 failed with %d" % result) return server_response - except GssapiAuthError, exc: + except GssapiAuthError as exc: logging.error(repr(exc)) finally: self.clean_context() -- cgit v1.2.1