Commit 7a856d1b authored by Nicolas Chauvat's avatar Nicolas Chauvat
Browse files

[toward-py3k] rewrite to "except AnException as exc:" (part of #2711624)

The older form is not necessary since we dropped python 2.5 compability. This
will help Python 3.3 experimentation.
parent d901c36bcfce
......@@ -100,7 +100,7 @@ class Unauthorized(SecurityError):
if self.args:
return ' '.join(self.args)
return self.msg
except Exception, ex:
except Exception as ex:
return str(ex)
class Forbidden(SecurityError):
......
......@@ -473,7 +473,7 @@ this option is set to yes",
try:
parent = __import__('cubes.%s.__pkginfo__' % cube)
return getattr(parent, cube).__pkginfo__
except Exception, ex:
except Exception as ex:
raise ConfigurationError(
'unable to find packaging information for cube %s (%s: %s)'
% (cube, ex.__class__.__name__, ex))
......@@ -580,7 +580,7 @@ this option is set to yes",
if dep in cubes)
try:
return ordered_nodes(graph)
except UnorderableGraph, ex:
except UnorderableGraph as ex:
raise ConfigurationError('cycles in cubes dependencies: %s'
% ex.cycles)
......@@ -614,7 +614,7 @@ this option is set to yes",
if exists(join(CW_SOFTWARE_ROOT, ctlfile)):
try:
load_module_from_file(join(CW_SOFTWARE_ROOT, ctlfile))
except ImportError, err:
except ImportError as err:
cls.error('could not import the command provider %s: %s',
ctlfile, err)
cls.info('loaded cubicweb-ctl plugin %s', ctlfile)
......@@ -643,7 +643,7 @@ this option is set to yes",
for cube in cls.available_cubes():
try:
__import__('cubes.%s' % cube)
except Exception, ex:
except Exception as ex:
cls.warning("can't init cube %s: %s", cube, ex)
cubicweb_appobject_path = set(['entities'])
......@@ -1055,7 +1055,7 @@ the repository',
self.info('creating %s directory', path)
try:
os.makedirs(path)
except OSError, ex:
except OSError as ex:
self.warning('error while creating %s directory: %s', path, ex)
return
if self['uid']:
......@@ -1074,14 +1074,14 @@ the repository',
self.info('giving ownership of %s directory to %s', path, self['uid'])
try:
os.chown(path, uid, os.getgid())
except OSError, ex:
except OSError as ex:
self.warning('error while giving ownership of %s directory to %s: %s',
path, self['uid'], ex)
if not (fstat.st_mode & stat.S_IWUSR):
self.info('forcing write permission on directory %s', path)
try:
os.chmod(path, fstat.st_mode | stat.S_IWUSR)
except OSError, ex:
except OSError as ex:
self.warning('error while forcing write permission on directory %s: %s',
path, ex)
return
......@@ -1191,7 +1191,7 @@ the repository',
try:
try:
smtp = SMTP(server, port)
except Exception, ex:
except Exception as ex:
self.exception("can't connect to smtp server %s:%s (%s)",
server, port, ex)
return False
......@@ -1199,7 +1199,7 @@ the repository',
for msg, recipients in msgs:
try:
smtp.sendmail(heloaddr, recipients, msg.as_string())
except Exception, ex:
except Exception as ex:
self.exception("error sending mail to %s (%s)",
recipients, ex)
smtp.close()
......@@ -1314,7 +1314,7 @@ def register_stored_procedures():
fpath = source.binary_to_str(value)
try:
return Binary(fpath)
except OSError, ex:
except OSError as ex:
source.critical("can't open %s: %s", fpath, ex)
return None
......
......@@ -165,11 +165,11 @@ class InstanceCommand(Command):
cmdmeth = getattr(self, '%s_instance' % self.name)
try:
status = cmdmeth(appid)
except (ExecutionError, ConfigurationError), ex:
except (ExecutionError, ConfigurationError) as ex:
sys.stderr.write('instance %s not %s: %s\n' % (
appid, self.actionverb, ex))
status = 4
except Exception, ex:
except Exception as ex:
import traceback
traceback.print_exc()
sys.stderr.write('instance %s not %s: %s\n' % (
......@@ -234,7 +234,7 @@ class ListCommand(Command):
try:
cubesdir = pathsep.join(cwcfg.cubes_search_path())
namesize = max(len(x) for x in cwcfg.available_cubes())
except ConfigurationError, ex:
except ConfigurationError as ex:
print 'No cubes available:', ex
except ValueError:
print 'No cubes available in %s' % cubesdir
......@@ -245,7 +245,7 @@ class ListCommand(Command):
tinfo = cwcfg.cube_pkginfo(cube)
tversion = tinfo.version
cfgpb.add_cube(cube, tversion)
except (ConfigurationError, AttributeError), ex:
except (ConfigurationError, AttributeError) as ex:
tinfo = None
tversion = '[missing cube information: %s]' % ex
print '* %s %s' % (cube.ljust(namesize), tversion)
......@@ -266,7 +266,7 @@ class ListCommand(Command):
print
try:
regdir = cwcfg.instances_dir()
except ConfigurationError, ex:
except ConfigurationError as ex:
print 'No instance available:', ex
print
return
......@@ -281,7 +281,7 @@ class ListCommand(Command):
print '* %s (%s)' % (appid, ', '.join(modes))
try:
config = cwcfg.config_for(appid, modes[0])
except Exception, exc:
except Exception as exc:
print ' (BROKEN instance, %s)' % exc
continue
else:
......@@ -365,7 +365,7 @@ class CreateInstanceCommand(Command):
try:
templdirs = [cwcfg.cube_dir(cube)
for cube in cubes]
except ConfigurationError, ex:
except ConfigurationError as ex:
print ex
print '\navailable cubes:',
print ', '.join(cwcfg.available_cubes())
......@@ -466,7 +466,7 @@ class DeleteInstanceCommand(Command):
# remove instance data directory
try:
rm(config.appdatahome)
except OSError, ex:
except OSError as ex:
import errno
if ex.errno != errno.ENOENT:
raise
......@@ -561,7 +561,7 @@ class StopInstanceCommand(InstanceCommand):
else:
try:
wait_process_end(pid)
except ExecutionError, ex:
except ExecutionError as ex:
sys.stderr.write('%s\ntrying SIGKILL\n' % ex)
try:
kill(pid, signal.SIGKILL)
......@@ -905,7 +905,7 @@ directly give URI as instance id instead',
try:
login, pwd = manager_userpasswd(msg=None)
cnx = connect(appuri, login=login, password=pwd, mulcnx=False)
except AuthenticationError, ex:
except AuthenticationError as ex:
print ex
except (KeyboardInterrupt, EOFError):
print
......@@ -1013,10 +1013,10 @@ def run(args):
cwcfg.load_cwctl_plugins()
try:
CWCTL.run(args)
except ConfigurationError, err:
except ConfigurationError as err:
print 'ERROR: ', err
sys.exit(1)
except ExecutionError, err:
except ExecutionError as err:
print err
sys.exit(2)
......
......@@ -816,10 +816,10 @@ class CWRegistryStore(RegistryStore):
for key, val in propvalues:
try:
values[key] = self.typed_value(key, val)
except ValueError, ex:
except ValueError as ex:
self.warning('%s (you should probably delete that property '
'from the database)', ex)
except UnknownProperty, ex:
except UnknownProperty as ex:
self.warning('%s (you should probably delete that property '
'from the database)', ex)
......
......@@ -216,7 +216,7 @@ def mk_entity(row, map):
res[dest] = func(res[dest])
if res[dest] is None:
break
except ValueError, err:
except ValueError as err:
raise ValueError('error with %r field: %s' % (src, err)), None, sys.exc_info()[-1]
return res
......@@ -744,7 +744,7 @@ class CWImportController(object):
txuuid = self.store.commit()
if txuuid is not None:
self.tell('Transaction commited (txuuid: %s)' % txuuid)
except QueryError, ex:
except QueryError as ex:
self.tell('Transaction aborted: %s' % ex)
self._print_stats()
if self.errors:
......
......@@ -107,7 +107,7 @@ def get_repository(uri=None, config=None, vreg=None):
return _get_repository(uri, config, vreg)
except ConnectionError:
raise
except Exception, exc:
except Exception as exc:
raise ConnectionError('cause: %r' % exc)
def _get_repository(uri=None, config=None, vreg=None):
......
......@@ -35,7 +35,7 @@ try:
import windmill
from windmill.dep import functest
from windmill.bin.admin_lib import configure_global_settings, setup, teardown
except ImportError, ex:
except ImportError:
windmill = None
from cubicweb.devtools.httptest import CubicWebServerTC, CubicWebServerConfig
......
......@@ -386,7 +386,7 @@ def update_cubes_catalogs(cubes):
continue
try:
toedit = update_cube_catalogs(cubedir)
except CalledProcessError, exc:
except CalledProcessError as exc:
print '\n*** error while updating catalogs for cube', cubedir
print 'cmd:\n%s' % exc.cmd
print 'stdout:\n%s\nstderr:\n%s' % exc.data
......@@ -606,7 +606,7 @@ layout, and a full featured cube with "full" layout.',
print "-> creating cubes directory", cubesdir
try:
mkdir(cubesdir)
except OSError, err:
except OSError as err:
self.fail("failed to create directory %r\n(%s)"
% (cubesdir, err))
cubedir = osp.join(cubesdir, cubename)
......@@ -694,7 +694,7 @@ class ExamineLogCommand(Command):
for filepath in args:
try:
stream = file(filepath)
except OSError, ex:
except OSError as ex:
raise BadCommandUsage("can't open rql log file %s: %s"
% (filepath, ex))
for lineno, line in enumerate(stream):
......@@ -711,7 +711,7 @@ class ExamineLogCommand(Command):
clocktime = float(chunks[0][1:])
cputime = float(chunks[-3])
req.append( (clocktime, cputime) )
except Exception, exc:
except Exception as exc:
sys.stderr.write('Line %s: %s (%s)\n' % (lineno, exc, line))
stat = []
for rql, times in requests.iteritems():
......
......@@ -37,7 +37,7 @@ class Validator(object):
try:
data = self.preprocess_data(data)
return PageInfo(data, etree.fromstring(data, self.parser))
except etree.XMLSyntaxError, exc:
except etree.XMLSyntaxError as exc:
def save_in(fname=''):
file(fname, 'w').write(data)
new_exc = AssertionError(u'invalid xml %s' % exc)
......
......@@ -50,7 +50,7 @@ def get_available_port(ports_scan):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = s.connect(("localhost", port))
except socket.error, err:
except socket.error as err:
if err.args[0] in (111, 106):
return port
finally:
......@@ -179,7 +179,7 @@ class CubicWebServerTC(CubicWebTC):
def tearDown(self):
try:
self.stop_server()
except error.ReactorNotRunning, err:
except error.ReactorNotRunning as err:
# Server could be launched manually
print err
super(CubicWebServerTC, self).tearDown()
......
......@@ -82,7 +82,7 @@ class FirefoxHelper(object):
check_call(self.firefox_cmd + ['-CreateProfile',
'%s %s' % (self._profile_name, self._tmp_dir)],
stdout=stdout, stderr=stderr)
except CalledProcessError, cpe:
except CalledProcessError as cpe:
stdout.seek(0)
stderr.seek(0)
raise VerboseCalledProcessError(cpe.returncode, cpe.cmd, stdout.read(), stderr.read())
......
......@@ -155,7 +155,7 @@ class RQLGeneratorTC(TestCase):
if cls.backend is not None:
try:
cls.dbhelper = get_db_helper(cls.backend)
except ImportError, ex:
except ImportError as ex:
raise SkipTest(str(ex))
def setUp(self):
......
......@@ -132,7 +132,7 @@ def run(args):
opts, args = getopt.getopt(args, 'hn:t:u:p:P:o:', ['help', 'user=', 'password=',
'nb-times=', 'nb-threads=',
'profile', 'report-output=',])
except Exception, ex:
except Exception as ex:
print ex
usage(1)
repeat = 100
......
......@@ -28,7 +28,7 @@ class TwistedCWAnonTC(CubicWebServerTC):
def test_response(self):
try:
response = self.web_get()
except httplib.NotConnected, ex:
except httplib.NotConnected as ex:
self.fail("Can't connection to test server: %s" % ex)
def test_response_anon(self):
......
......@@ -315,7 +315,7 @@ class CubicWebTC(TestCase):
try:
self._init_repo()
self.addCleanup(self._close_cnx)
except Exception, ex:
except Exception as ex:
self.__class__._repo_init_failed = ex
raise
resume_tracing()
......@@ -720,7 +720,7 @@ class CubicWebTC(TestCase):
"""
try:
callback(req)
except Redirect, ex:
except Redirect as ex:
return self._parse_location(req, ex.location)
else:
self.fail('expected a Redirect exception')
......@@ -1087,7 +1087,7 @@ class AutoPopulateTest(CubicWebTC):
for rql, args in q:
try:
cu.execute(rql, args)
except ValidationError, ex:
except ValidationError as ex:
# failed to satisfy some constraint
print 'error in automatic db population', ex
self.session.commit_state = None # reset uncommitable flag
......
......@@ -169,7 +169,7 @@ class CubicWebRootResource(resource.Resource):
try:
### Try to generate the actual request content
content = self.appli.handle_request(req, path)
except DirectResponse, ex:
except DirectResponse as ex:
return ex.response
# at last: create twisted object
return HTTPResponse(code = req.status_out,
......
......@@ -91,7 +91,7 @@ class CWService(object, win32serviceutil.ServiceFramework):
logger.info('instance started on %s', root_resource.base_url)
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
reactor.run()
except Exception, e:
except Exception as e:
logger.error('service %s stopped (cause: %s)' % (self.instance, e))
logger.exception('what happened ...')
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
......@@ -114,7 +114,7 @@ def rql_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
vid = 'noresult'
view = _cw.vreg['views'].select(vid, _cw, rset=rset)
content = view.render()
except Exception, exc:
except Exception as exc:
content = 'an error occured while interpreting this rql directive: %r' % exc
set_classes(options)
return [nodes.raw('', content, format='html')], []
......@@ -155,7 +155,7 @@ def winclude_directive(name, arguments, options, content, lineno,
source_path=path, encoding=encoding,
error_handler=state.document.settings.input_encoding_error_handler,
handle_io_errors=None)
except IOError, error:
except IOError as error:
severe = state_machine.reporter.severe(
'Problems with "%s" directive path:\n%s: %s.'
% (name, error.__class__.__name__, error),
......@@ -163,7 +163,7 @@ def winclude_directive(name, arguments, options, content, lineno,
return [severe]
try:
include_text = include_file.read()
except UnicodeError, error:
except UnicodeError as error:
severe = state_machine.reporter.severe(
'Problem with "%s" directive:\n%s: %s'
% (name, error.__class__.__name__, error),
......
......@@ -182,7 +182,7 @@ class CubicWebTemplate(simpleTAL.HTMLTemplate):
""" Internally used when expanding a template that is part of a context."""
try:
interpreter.execute(self)
except UnicodeError, unierror:
except UnicodeError as unierror:
LOGGER.exception(str(unierror))
raise simpleTALES.ContextContentException("found non-unicode %r string in Context!" % unierror.args[1]), None, sys.exc_info()[-1]
......@@ -230,7 +230,7 @@ def evaluatePython (self, expr):
# XXX precompile expr will avoid late syntax error
try:
result = eval(expr, globals, locals)
except Exception, ex:
except Exception as ex:
ex = ex.__class__('in %r: %s' % (expr, ex))
raise ex, None, sys.exc_info()[-1]
if (isinstance (result, simpleTALES.ContextVariable)):
......
......@@ -67,7 +67,7 @@ class UpdateFeedsStartupHook(hook.Hook):
session = repo.internal_session(safe=True)
try:
source.pull_data(session)
except Exception, exc:
except Exception as exc:
session.exception('while trying to update feed %s', source)
finally:
session.close()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment