Commit b5193345 authored by Kazuhiko Shiozaki's avatar Kazuhiko Shiozaki

py2/py3: 2to3 -f except

parent b21f83fc
...@@ -21,7 +21,7 @@ def getSkinHash(skin, skin_container): ...@@ -21,7 +21,7 @@ def getSkinHash(skin, skin_container):
content = skin.formXML() content = skin.formXML()
if isinstance(content, unicode): if isinstance(content, unicode):
content = content.encode('utf8', 'repr') content = content.encode('utf8', 'repr')
except AttributeError, e: except AttributeError as e:
# This can happen with dead proxy fields. # This can happen with dead proxy fields.
content = "broken form %s" % e content = "broken form %s" % e
content = 'ignore' content = 'ignore'
......
...@@ -22,7 +22,7 @@ if form_id is not None: ...@@ -22,7 +22,7 @@ if form_id is not None:
# button itself # button itself
try: try:
form.validate_all_to_request(request) form.validate_all_to_request(request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -112,7 +112,7 @@ for erp5_action_key in erp5_action_dict.keys(): ...@@ -112,7 +112,7 @@ for erp5_action_key in erp5_action_dict.keys():
if mode != "allDocs": if mode != "allDocs":
return result return result
result_list += result result_list += result
except ValueError, e: except ValueError as e:
try: try:
error_dict.update(json.loads(str(e))) error_dict.update(json.loads(str(e)))
except ValueError: except ValueError:
......
...@@ -196,7 +196,7 @@ try: ...@@ -196,7 +196,7 @@ try:
cell.edit(quantity=total_quantity) cell.edit(quantity=total_quantity)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
redirect_url = '%s/view?%s' % ( context.absolute_url() redirect_url = '%s/view?%s' % ( context.absolute_url()
, 'portal_status_message=%s' % localizer.erp5_ui.gettext("input failed.") , 'portal_status_message=%s' % localizer.erp5_ui.gettext("input failed.")
) )
......
...@@ -35,7 +35,7 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg" ...@@ -35,7 +35,7 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg"
def getDataURI(url): def getDataURI(url):
try: try:
data = urllib2.urlopen(url) data = urllib2.urlopen(url)
except Exception, e: except Exception as e:
raise ConversionError("Error to transform url (%s) into data uri. ERROR = %s" % (url, Exception(e))) raise ConversionError("Error to transform url (%s) into data uri. ERROR = %s" % (url, Exception(e)))
return 'data:%s;base64,%s' % (data.info()["content-type"], return 'data:%s;base64,%s' % (data.info()["content-type"],
data.read().encode("base64").replace('\n', "")) data.read().encode("base64").replace('\n', ""))
......
...@@ -23,7 +23,7 @@ else: ...@@ -23,7 +23,7 @@ else:
new_id = person.generateNewId() new_id = person.generateNewId()
try: try:
default_career.setId(new_id) default_career.setId(new_id)
except ActivityPendingError, error: except ActivityPendingError as error:
message = Base_translateString("%s" % error) message = Base_translateString("%s" % error)
return context.Base_redirect(form_id=form_id, return context.Base_redirect(form_id=form_id,
selection_name=selection_name, selection_name=selection_name,
......
...@@ -14,7 +14,7 @@ if form_id is not None: ...@@ -14,7 +14,7 @@ if form_id is not None:
# button itself # button itself
try: try:
params = form.validate_all_to_request(request) params = form.validate_all_to_request(request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -29,7 +29,7 @@ form = getattr(context,form_id) ...@@ -29,7 +29,7 @@ form = getattr(context,form_id)
try: try:
# Validate # Validate
form.validate_all_to_request(request) form.validate_all_to_request(request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -100,7 +100,8 @@ class TransactionThread(threading.Thread): ...@@ -100,7 +100,8 @@ class TransactionThread(threading.Thread):
# Login # Login
newSecurityManager(None, portal_value.acl_users.getUser('ERP5TypeTestCase')) newSecurityManager(None, portal_value.acl_users.getUser('ERP5TypeTestCase'))
self.payload(portal_value=portal_value) self.payload(portal_value=portal_value)
except Exception as self.exception: # pylint: disable=redefine-in-handler except Exception as e: # pylint: disable=redefine-in-handler
self.exception = e # pylint: disable=redefine-in-handler
if six.PY2: if six.PY2:
self.exception.__traceback__ = sys.exc_info()[2] self.exception.__traceback__ = sys.exc_info()[2]
......
...@@ -280,7 +280,7 @@ class PDFDocument(Image): ...@@ -280,7 +280,7 @@ class PDFDocument(Image):
'-noframes', '-i', tmp.name] '-noframes', '-i', tmp.name]
try: try:
command_result = Popen(command, stdout=PIPE).communicate()[0] command_result = Popen(command, stdout=PIPE).communicate()[0]
except OSError, e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
raise ConversionError('pdftohtml was not found') raise ConversionError('pdftohtml was not found')
raise raise
...@@ -309,7 +309,7 @@ class PDFDocument(Image): ...@@ -309,7 +309,7 @@ class PDFDocument(Image):
command = ['pdf2djvu', tmp.name] command = ['pdf2djvu', tmp.name]
try: try:
command_result = Popen(command, stdout=PIPE).communicate()[0] command_result = Popen(command, stdout=PIPE).communicate()[0]
except OSError, e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
raise ConversionError('pdf2djvu was not found') raise ConversionError('pdf2djvu was not found')
raise raise
...@@ -338,7 +338,7 @@ class PDFDocument(Image): ...@@ -338,7 +338,7 @@ class PDFDocument(Image):
command = ['pdfinfo', '-meta', '-box', tmp.name] command = ['pdfinfo', '-meta', '-box', tmp.name]
try: try:
command_result = Popen(command, stdout=PIPE).communicate()[0] command_result = Popen(command, stdout=PIPE).communicate()[0]
except OSError, e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
raise ConversionError('pdfinfo was not found') raise ConversionError('pdfinfo was not found')
raise raise
......
...@@ -8,7 +8,7 @@ try: ...@@ -8,7 +8,7 @@ try:
return result return result
if not context.hasBaseData(): if not context.hasBaseData():
error_message = context.Base_translateString("This document is not converted yet.") error_message = context.Base_translateString("This document is not converted yet.")
except Exception, e: except Exception as e:
from erp5.component.module.Log import log from erp5.component.module.Log import log
log("asStrippedHTML", str(e)) log("asStrippedHTML", str(e))
error_message = "%s %s" % (context.Base_translateString("Preview Error:"), error_message = "%s %s" % (context.Base_translateString("Preview Error:"),
......
...@@ -11,13 +11,13 @@ if context.getExternalProcessingState() not in ('converted', 'empty'): ...@@ -11,13 +11,13 @@ if context.getExternalProcessingState() not in ('converted', 'empty'):
return context.convertToBaseFormat() return context.convertToBaseFormat()
except ConflictError: except ConflictError:
raise raise
except ConversionError, e: except ConversionError as e:
message = 'Conversion Error: %s' % (str(e) or 'undefined.') message = 'Conversion Error: %s' % (str(e) or 'undefined.')
except Fault, e: except Fault as e:
message = 'XMLFault: %s' % (repr(e) or 'undefined.') message = 'XMLFault: %s' % (repr(e) or 'undefined.')
except SocketError, e: except SocketError as e:
message = 'Socket Error: %s' % (repr(e) or 'undefined.') message = 'Socket Error: %s' % (repr(e) or 'undefined.')
except Exception, e: except Exception as e:
message = 'Problem: %s' % (repr(e) or 'undefined.') message = 'Problem: %s' % (repr(e) or 'undefined.')
# reach here, then exception was raised, message must be logged in workflow # reach here, then exception was raised, message must be logged in workflow
# do not simply raise but rather change external processing state # do not simply raise but rather change external processing state
......
...@@ -7,9 +7,9 @@ try: ...@@ -7,9 +7,9 @@ try:
return context.updateBaseMetadata(**kw) return context.updateBaseMetadata(**kw)
except ConflictError: except ConflictError:
raise raise
except ConversionError, e: except ConversionError as e:
message = 'Conversion Error: %s' % (str(e) or 'undefined.') message = 'Conversion Error: %s' % (str(e) or 'undefined.')
except Exception, e: except Exception as e:
message = 'Problem: %s' % (repr(e) or 'undefined.') message = 'Problem: %s' % (repr(e) or 'undefined.')
# reach here, then exception was raised, message must be logged in workflow # reach here, then exception was raised, message must be logged in workflow
......
...@@ -44,7 +44,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment ...@@ -44,7 +44,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment
cdict = category_dict.copy() cdict = category_dict.copy()
cdict[base_category] = '/'.join(grouplist[:-i]) cdict[base_category] = '/'.join(grouplist[:-i])
category_list.append(cdict) category_list.append(cdict)
except RuntimeError,e: except RuntimeError as e:
log(str(e)) log(str(e))
return category_list return category_list
...@@ -330,7 +330,7 @@ class EmailReader(ExternalSource): ...@@ -330,7 +330,7 @@ class EmailReader(ExternalSource):
# This is very sequential and could be improved probably # This is very sequential and could be improved probably
try: try:
message_uid_list = self._getMailServer().getMessageUIDList(message_folder=message_folder) message_uid_list = self._getMailServer().getMessageUIDList(message_folder=message_folder)
except ValueError, error_message: # Use a better exception here XXX except ValueError as error_message: # Use a better exception here XXX
message_uid_list = [] message_uid_list = []
# Reduce list size based on asumption of growing sequence of uids # Reduce list size based on asumption of growing sequence of uids
latest_uid = self._latest_uid.get(message_folder, 0) latest_uid = self._latest_uid.get(message_folder, 0)
......
...@@ -67,7 +67,7 @@ class Git(WorkingCopy): ...@@ -67,7 +67,7 @@ class Git(WorkingCopy):
argv = ['git'] argv = ['git']
try: try:
return subprocess.Popen(argv + list(args), **kw) return subprocess.Popen(argv + list(args), **kw)
except OSError, e: except OSError as e:
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
LOG('Git', WARNING, LOG('Git', WARNING,
'will not work as the executable cannot be executed, perhaps not ' 'will not work as the executable cannot be executed, perhaps not '
...@@ -117,7 +117,7 @@ class Git(WorkingCopy): ...@@ -117,7 +117,7 @@ class Git(WorkingCopy):
env.update(ERP5_GIT_USERNAME=userpwd[0], ERP5_GIT_PASSWORD=userpwd[1]) env.update(ERP5_GIT_USERNAME=userpwd[0], ERP5_GIT_PASSWORD=userpwd[1])
try: try:
return self.git(*args, **kw) return self.git(*args, **kw)
except GitError, e: except GitError as e:
message = 'Authentication failed' message = 'Authentication failed'
if message in str(e): if message in str(e):
raise GitLoginError(userpwd and message or raise GitLoginError(userpwd and message or
...@@ -148,7 +148,7 @@ class Git(WorkingCopy): ...@@ -148,7 +148,7 @@ class Git(WorkingCopy):
local, remote = self.git('rev-parse', '--symbolic-full-name', local, remote = self.git('rev-parse', '--symbolic-full-name',
'HEAD', '@{u}').splitlines() 'HEAD', '@{u}').splitlines()
remote = remote[:13] == 'refs/remotes/' and remote[13:] or None remote = remote[:13] == 'refs/remotes/' and remote[13:] or None
except GitError, e: except GitError as e:
local = e.stdout.splitlines()[0] local = e.stdout.splitlines()[0]
remote = None remote = None
if local != 'HEAD': if local != 'HEAD':
...@@ -293,7 +293,7 @@ class Git(WorkingCopy): ...@@ -293,7 +293,7 @@ class Git(WorkingCopy):
try: try:
return self.git('show', 'HEAD:' + self.prefix + path, return self.git('show', 'HEAD:' + self.prefix + path,
strip=False, cwd=self.toplevel) strip=False, cwd=self.toplevel)
except GitError, e: except GitError as e:
err = e.args[0] err = e.args[0]
if ' does not exist in ' in err or ' exists on disk, but not in ' in err: if ' does not exist in ' in err or ' exists on disk, but not in ' in err:
raise NotVersionedError(path) raise NotVersionedError(path)
...@@ -350,7 +350,7 @@ class Git(WorkingCopy): ...@@ -350,7 +350,7 @@ class Git(WorkingCopy):
push_args = 'push', '--porcelain', remote, '%s:%s' % (src, dst) push_args = 'push', '--porcelain', remote, '%s:%s' % (src, dst)
try: try:
self.remote_git(*push_args) self.remote_git(*push_args)
except GitError, e: except GitError as e:
# first check why we could not push # first check why we could not push
status = [x for x in e.stdout.splitlines() if x[:1] == '!'] status = [x for x in e.stdout.splitlines() if x[:1] == '!']
if (len(status) != 1 or if (len(status) != 1 or
...@@ -365,7 +365,7 @@ class Git(WorkingCopy): ...@@ -365,7 +365,7 @@ class Git(WorkingCopy):
# TODO: solve conflicts on */bt/revision automatically # TODO: solve conflicts on */bt/revision automatically
try: try:
self.git(merge, '@{u}', env=env) self.git(merge, '@{u}', env=env)
except GitError, e: except GitError as e:
# XXX: how to know how it failed ? # XXX: how to know how it failed ?
try: try:
self.git(merge, '--abort') self.git(merge, '--abort')
...@@ -377,7 +377,7 @@ class Git(WorkingCopy): ...@@ -377,7 +377,7 @@ class Git(WorkingCopy):
reset += 1 reset += 1
# retry to push everything # retry to push everything
self.remote_git(*push_args) self.remote_git(*push_args)
except (GitError, GitLoginError), e: except (GitError, GitLoginError) as e:
self.git('reset', '--soft', '@{%u}' % reset) self.git('reset', '--soft', '@{%u}' % reset)
if isinstance(e, GitLoginError): if isinstance(e, GitLoginError):
raise raise
......
...@@ -145,7 +145,7 @@ class Subversion(WorkingCopy): ...@@ -145,7 +145,7 @@ class Subversion(WorkingCopy):
try: try:
return self._getClient().cat(os.path.join(self.working_copy, path), return self._getClient().cat(os.path.join(self.working_copy, path),
Revision(opt_revision_kind.base)) Revision(opt_revision_kind.base))
except ClientError, e: except ClientError as e:
if e.args[1][-1][1] in (errno.ENOENT, svn_err.entry_not_found): if e.args[1][-1][1] in (errno.ENOENT, svn_err.entry_not_found):
raise NotVersionedError(path) raise NotVersionedError(path)
raise raise
......
...@@ -271,7 +271,7 @@ try: ...@@ -271,7 +271,7 @@ try:
return Revision(self.client.checkin(path, return Revision(self.client.checkin(path,
log_message=log_message or 'none', log_message=log_message or 'none',
recurse=recurse)) recurse=recurse))
except pysvn.ClientError, error: except pysvn.ClientError as error:
excep = self.getException() excep = self.getException()
if excep: if excep:
raise excep # pylint: disable=raising-bad-type raise excep # pylint: disable=raising-bad-type
...@@ -281,7 +281,7 @@ try: ...@@ -281,7 +281,7 @@ try:
def update(self, path): def update(self, path):
try: try:
return [Revision(x) for x in self.client.update(path)] return [Revision(x) for x in self.client.update(path)]
except pysvn.ClientError, error: except pysvn.ClientError as error:
excep = self.getException() excep = self.getException()
if excep: if excep:
raise excep # pylint: disable=raising-bad-type raise excep # pylint: disable=raising-bad-type
...@@ -293,7 +293,7 @@ try: ...@@ -293,7 +293,7 @@ try:
# Zope, convert the objects. # Zope, convert the objects.
try: try:
status_list = [Status(x) for x in self.client.status(path=path, **kw)] status_list = [Status(x) for x in self.client.status(path=path, **kw)]
except pysvn.ClientError, error: except pysvn.ClientError as error:
excep = self.getException() excep = self.getException()
if excep: if excep:
raise excep # pylint: disable=raising-bad-type raise excep # pylint: disable=raising-bad-type
...@@ -328,7 +328,7 @@ try: ...@@ -328,7 +328,7 @@ try:
def log(self, path): def log(self, path):
try: try:
log_list = self.client.log(path) log_list = self.client.log(path)
except pysvn.ClientError, error: except pysvn.ClientError as error:
if 'path not found' in error.args[0]: if 'path not found' in error.args[0]:
return return
excep = self.getException() excep = self.getException()
...@@ -361,7 +361,7 @@ try: ...@@ -361,7 +361,7 @@ try:
path = os.path.realpath(path) path = os.path.realpath(path)
try: try:
entry = self.client.info(path=path) entry = self.client.info(path=path)
except pysvn.ClientError, error: except pysvn.ClientError as error:
excep = self.getException() excep = self.getException()
if excep: if excep:
raise excep # pylint: disable=raising-bad-type raise excep # pylint: disable=raising-bad-type
...@@ -381,7 +381,7 @@ try: ...@@ -381,7 +381,7 @@ try:
def ls(self, path): def ls(self, path):
try: try:
dict_list = self.client.ls(url_or_path=path, recurse=False) dict_list = self.client.ls(url_or_path=path, recurse=False)
except pysvn.ClientError, error: except pysvn.ClientError as error:
if 'non-existent' in error.args[0]: if 'non-existent' in error.args[0]:
return return
excep = self.getException() excep = self.getException()
......
...@@ -269,7 +269,7 @@ class WorkingCopy(Implicit): ...@@ -269,7 +269,7 @@ class WorkingCopy(Implicit):
try: try:
with open(os.path.join(self.working_copy, path), 'rU') as f: with open(os.path.join(self.working_copy, path), 'rU') as f:
text = f.read() text = f.read()
except IOError, e: except IOError as e:
if e.errno == errno.EISDIR: if e.errno == errno.EISDIR:
return '%s<hr/>%r is a folder!' % (head, path) return '%s<hr/>%r is a folder!' % (head, path)
if e.errno != errno.ENOENT: if e.errno != errno.ENOENT:
...@@ -369,7 +369,7 @@ class BusinessTemplateWorkingCopy(BusinessTemplateFolder): ...@@ -369,7 +369,7 @@ class BusinessTemplateWorkingCopy(BusinessTemplateFolder):
try: try:
try: try:
file_obj = open(path, 'r+b') file_obj = open(path, 'r+b')
except IOError, e: except IOError as e:
if e.errno == errno.EISDIR: if e.errno == errno.EISDIR:
shutil.rmtree(path, ignore_errors=True) shutil.rmtree(path, ignore_errors=True)
elif e.errno != errno.ENOENT: elif e.errno != errno.ENOENT:
......
...@@ -3,10 +3,10 @@ from erp5.component.module.SubversionClient import SubversionSSLTrustError, Subv ...@@ -3,10 +3,10 @@ from erp5.component.module.SubversionClient import SubversionSSLTrustError, Subv
vcs_tool = context.getVcsTool() vcs_tool = context.getVcsTool()
try: try:
entry_dict = vcs_tool.checkout(context, url) entry_dict = vcs_tool.checkout(context, url)
except SubversionSSLTrustError, error: except SubversionSSLTrustError as error:
context.REQUEST.set('portal_status_message', 'SSL Certificate was not recognized') context.REQUEST.set('portal_status_message', 'SSL Certificate was not recognized')
return context.asContext(trust_dict = error.getTrustDict(), caller='info').BusinessTemplate_viewSvnSSLTrustDialog() return context.asContext(trust_dict = error.getTrustDict(), caller='info').BusinessTemplate_viewSvnSSLTrustDialog()
except SubversionLoginError, error1 : except SubversionLoginError as error1 :
context.REQUEST.set('portal_status_message', 'Server needs authentication, no cookie found') context.REQUEST.set('portal_status_message', 'Server needs authentication, no cookie found')
return context.asContext(caller='info', realm = error1.getRealm(), username = vcs_tool.getPreferredUsername()).BusinessTemplate_viewSvnLoginDialog() return context.asContext(caller='info', realm = error1.getRealm(), username = vcs_tool.getPreferredUsername()).BusinessTemplate_viewSvnLoginDialog()
return entry_dict return entry_dict
...@@ -52,5 +52,5 @@ try: ...@@ -52,5 +52,5 @@ try:
modified=commit_dict['modified'], modified=commit_dict['modified'],
removed=commit_dict['removed'] removed=commit_dict['removed']
) )
except Exception, error: except Exception as error:
return context.BusinessTemplate_handleException(error, script.id, commit_dict) return context.BusinessTemplate_handleException(error, script.id, commit_dict)
...@@ -8,7 +8,7 @@ if keep: ...@@ -8,7 +8,7 @@ if keep:
try: try:
new_bt = context.getVcsTool().update(commit_dict['keep']) new_bt = context.getVcsTool().update(commit_dict['keep'])
except Exception, error: except Exception as error:
return context.BusinessTemplate_handleException( return context.BusinessTemplate_handleException(
error, script.id, commit_dict) error, script.id, commit_dict)
......
...@@ -4,15 +4,15 @@ import json ...@@ -4,15 +4,15 @@ import json
try: try:
raise exception raise exception
except SubversionSSLTrustError, e: except SubversionSSLTrustError as e:
message = 'SSL Certificate was not recognized' message = 'SSL Certificate was not recognized'
kw = dict(trust_dict=e.getTrustDict()) kw = dict(trust_dict=e.getTrustDict())
method = 'BusinessTemplate_viewSvnSSLTrustDialog' method = 'BusinessTemplate_viewSvnSSLTrustDialog'
except SubversionLoginError, e: except SubversionLoginError as e:
message = 'Server needs authentication, no cookie found' message = 'Server needs authentication, no cookie found'
kw = dict(realm=e.getRealm(), username=context.getVcsTool().getPreferredUsername()) kw = dict(realm=e.getRealm(), username=context.getVcsTool().getPreferredUsername())
method = 'BusinessTemplate_viewSvnLoginDialog' method = 'BusinessTemplate_viewSvnLoginDialog'
except GitLoginError, e: except GitLoginError as e:
message = str(e) message = str(e)
kw = dict(remote_url=context.getVcsTool().getRemoteUrl()) kw = dict(remote_url=context.getVcsTool().getRemoteUrl())
method = 'BusinessTemplate_viewGitLoginDialog' method = 'BusinessTemplate_viewGitLoginDialog'
......
...@@ -26,7 +26,7 @@ for path in path_list: ...@@ -26,7 +26,7 @@ for path in path_list:
raise raise
except Unauthorized: # should happen in tricky testERP5Catalog tests only except Unauthorized: # should happen in tricky testERP5Catalog tests only
continue continue
except Exception, e: except Exception as e:
exception = e exception = e
failed_path_list.append(path) failed_path_list.append(path)
else: else:
......
...@@ -26,7 +26,7 @@ for path in path_list: ...@@ -26,7 +26,7 @@ for path in path_list:
raise raise
except Unauthorized: # should happen in tricky testERP5Catalog tests only except Unauthorized: # should happen in tricky testERP5Catalog tests only
continue continue
except Exception, e: except Exception as e:
exception = e exception = e
failed_path_list.append(path) failed_path_list.append(path)
else: else:
......
...@@ -6,7 +6,7 @@ form = getattr(context, form_id) ...@@ -6,7 +6,7 @@ form = getattr(context, form_id)
try: try:
# Validate # Validate
form.validate_all_to_request(request, key_prefix='my_') form.validate_all_to_request(request, key_prefix='my_')
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
result = {} result = {}
result['field_errors'] = {} result['field_errors'] = {}
......
...@@ -18,7 +18,7 @@ try: ...@@ -18,7 +18,7 @@ try:
request.set('editable_mode', 1) request.set('editable_mode', 1)
form.validate_all_to_request(request) form.validate_all_to_request(request)
request.set('editable_mode', editable_mode) request.set('editable_mode', editable_mode)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
...@@ -69,7 +69,7 @@ try: ...@@ -69,7 +69,7 @@ try:
context, context,
doaction_param_list['workflow_action'], doaction_param_list['workflow_action'],
**doaction_param_list) **doaction_param_list)
except ValidationFailed, error_message: except ValidationFailed as error_message:
if getattr(error_message, 'msg', None): if getattr(error_message, 'msg', None):
# use of Message class to store message+mapping+domain # use of Message class to store message+mapping+domain
message = error_message.msg message = error_message.msg
......
...@@ -86,7 +86,7 @@ class InotifyTool(TimerServiceMixin, BaseTool): ...@@ -86,7 +86,7 @@ class InotifyTool(TimerServiceMixin, BaseTool):
p = os.path.join(inode_path, name) p = os.path.join(inode_path, name)
try: try:
s = os.lstat(p) s = os.lstat(p)
except OSError, e: except OSError as e:
if e.errno != errno.ENOENT: if e.errno != errno.ENOENT:
raise raise
else: else:
......
...@@ -985,7 +985,7 @@ class TestInvoiceMixin(TestPackingListMixin): ...@@ -985,7 +985,7 @@ class TestInvoiceMixin(TestPackingListMixin):
""" """
try: try:
self.tic() self.tic()
except RuntimeError, exc: except RuntimeError as exc:
invoice = sequence.get('invoice') invoice = sequence.get('invoice')
# check which activities are failing # check which activities are failing
self.assertTrue(str(exc).startswith('tic is looping forever.'), self.assertTrue(str(exc).startswith('tic is looping forever.'),
......
...@@ -153,7 +153,7 @@ return json.dumps({ ...@@ -153,7 +153,7 @@ return json.dumps({
try: try:
getattr(self.portal, method)(json_data, list_error=True) getattr(self.portal, method)(json_data, list_error=True)
raise ValueError("No error raised during processing") raise ValueError("No error raised during processing")
except ValueError, e: except ValueError as e:
self.assertEqual(error, json.loads(str(e))) self.assertEqual(error, json.loads(str(e)))
def test_call_valid_datetime_format(self): def test_call_valid_datetime_format(self):
...@@ -211,6 +211,6 @@ return json.dumps({ ...@@ -211,6 +211,6 @@ return json.dumps({
try: try:
getattr(self.portal, method)(json_data, list_error=True) getattr(self.portal, method)(json_data, list_error=True)
raise ValueError("No error raised during processing") raise ValueError("No error raised during processing")
except ValueError, e: except ValueError as e:
self.assertEqual(error, json.loads(str(e))) self.assertEqual(error, json.loads(str(e)))
...@@ -16,7 +16,7 @@ form = getattr(box, form_id) ...@@ -16,7 +16,7 @@ form = getattr(box, form_id)
try: try:
# Validate # Validate
form.validate_all_to_request(request, key_prefix=form_fields_main_prefix) form.validate_all_to_request(request, key_prefix=form_fields_main_prefix)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -70,11 +70,11 @@ class MailevaSOAPConnector(XMLObject): ...@@ -70,11 +70,11 @@ class MailevaSOAPConnector(XMLObject):
try: try:
response = suds.client.Client(url = self.getProperty('submit_url_string'), transport=authenticated).service.submit(__inject={'msg': maileva_exchange.getRequest()}) response = suds.client.Client(url = self.getProperty('submit_url_string'), transport=authenticated).service.submit(__inject={'msg': maileva_exchange.getRequest()})
maileva_exchange.activate().MailevaExchange_processResponse(response) maileva_exchange.activate().MailevaExchange_processResponse(response)
except socket.error, e: except socket.error as e:
if e.errno == socket.errno.ECONNREFUSED: if e.errno == socket.errno.ECONNREFUSED:
if runtime_environment: if runtime_environment:
runtime_environment.edit(max_retry=None) runtime_environment.edit(max_retry=None)
except Exception, e: except Exception as e:
maileva_exchange.activate().MailevaExchange_processResponse(str(e), failed = True) maileva_exchange.activate().MailevaExchange_processResponse(str(e), failed = True)
......
...@@ -57,7 +57,7 @@ else: ...@@ -57,7 +57,7 @@ else:
**imported_line_property_dict) **imported_line_property_dict)
except ConflictError: except ConflictError:
raise raise
except Exception, error: except Exception as error:
translated_msg = Message('erp5_ui', translated_msg = Message('erp5_ui',
'An error Occurred while creating object: ${error}', 'An error Occurred while creating object: ${error}',
mapping=dict(error=Message('erp5_ui', mapping=dict(error=Message('erp5_ui',
...@@ -75,7 +75,7 @@ else: ...@@ -75,7 +75,7 @@ else:
new_object.edit(**category_dict) new_object.edit(**category_dict)
except ConflictError: except ConflictError:
raise raise
except Exception, error: except Exception as error:
#context.log('category: %s' %category) #context.log('category: %s' %category)
translated_msg = Message( translated_msg = Message(
'erp5_ui', 'erp5_ui',
......
...@@ -18,7 +18,7 @@ try: ...@@ -18,7 +18,7 @@ try:
message_list = template_tool.upgradeSite(bt5_list, dry_run=True, message_list = template_tool.upgradeSite(bt5_list, dry_run=True,
update_catalog=CATALOG_UPDATABLE) update_catalog=CATALOG_UPDATABLE)
severity = len(message_list) severity = len(message_list)
except BusinessTemplateUnknownError, error: except BusinessTemplateUnknownError as error:
severity = -1 severity = -1
detail = str(error) detail = str(error)
......
...@@ -54,7 +54,7 @@ class TestRealTimeInventoryAccountingMixin: ...@@ -54,7 +54,7 @@ class TestRealTimeInventoryAccountingMixin:
self.portal.portal_workflow.doActionFor(document, workflow_method_id) self.portal.portal_workflow.doActionFor(document, workflow_method_id)
else: else:
getattr(document, workflow_method_id)() getattr(document, workflow_method_id)()
except ValidationFailed, error: except ValidationFailed as error:
self.fail("Transition '%s' on %r should have succeeded (%s)" % \ self.fail("Transition '%s' on %r should have succeeded (%s)" % \
(workflow_method_id, document, (workflow_method_id, document,
sorted([m.message for m in error.msg]))) sorted([m.message for m in error.msg])))
......
...@@ -33,7 +33,7 @@ try: ...@@ -33,7 +33,7 @@ try:
# Update basic attributes # Update basic attributes
context.updateConfiguration(**kw) context.updateConfiguration(**kw)
context.reindexObject() context.reindexObject()
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -8,7 +8,7 @@ response = container.REQUEST.RESPONSE ...@@ -8,7 +8,7 @@ response = container.REQUEST.RESPONSE
start = time.time() start = time.time()
try: try:
results = context.manage_test(query) results = context.manage_test(query)
except Exception, e: except Exception as e:
response.setStatus(500) response.setStatus(500)
try: try:
response.write(str(e[1])) response.write(str(e[1]))
......
...@@ -271,7 +271,7 @@ class ERP5ProjectUnitTestDistributor(XMLObject): ...@@ -271,7 +271,7 @@ class ERP5ProjectUnitTestDistributor(XMLObject):
if test_node.getValidationState() != 'validated': if test_node.getValidationState() != 'validated':
try: try:
test_node.validate() test_node.validate()
except Exception, e: except Exception as e:
LOG('Test Node Validate',ERROR,'%s' %e) LOG('Test Node Validate',ERROR,'%s' %e)
if test_node is None: if test_node is None:
test_node = test_node_module.newContent(portal_type="Test Node", title=title, computer_guid=computer_guid, test_node = test_node_module.newContent(portal_type="Test Node", title=title, computer_guid=computer_guid,
......
...@@ -128,7 +128,7 @@ class ERP5ScalabilityDistributor(ERP5ProjectUnitTestDistributor, object): ...@@ -128,7 +128,7 @@ class ERP5ScalabilityDistributor(ERP5ProjectUnitTestDistributor, object):
if test_node.getValidationState() != 'validated': if test_node.getValidationState() != 'validated':
try: try:
test_node.validate() test_node.validate()
except Exception, e: except Exception as e:
LOG('Test Node Validate',ERROR,'%s' %e) LOG('Test Node Validate',ERROR,'%s' %e)
return test_node return test_node
return None return None
......
...@@ -87,7 +87,7 @@ class IntegrationModule(XMLObject): ...@@ -87,7 +87,7 @@ class IntegrationModule(XMLObject):
return self.getObjectList(id=item) return self.getObjectList(id=item)
else: else:
return self.getObjectList[item] return self.getObjectList[item]
except ValueError, msg: except ValueError as msg:
raise KeyError(msg) raise KeyError(msg)
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
......
...@@ -184,7 +184,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): ...@@ -184,7 +184,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate):
# Call the method # Call the method
try: try:
url, xml = callRequest(self, method_name, *args, **kw) url, xml = callRequest(self, method_name, *args, **kw)
except ConnectionError, msg: except ConnectionError as msg:
if test_mode: if test_mode:
error = msg error = msg
url = connection.url url = connection.url
......
...@@ -20,7 +20,7 @@ if context.getLastRequestError() is None: ...@@ -20,7 +20,7 @@ if context.getLastRequestError() is None:
for obj in object_list: for obj in object_list:
try: try:
xml = obj.asXML(debug=True) xml = obj.asXML(debug=True)
except (ValueError, NotImplementedError), msg: except (ValueError, NotImplementedError) as msg:
error = msg error = msg
continue continue
if not xml: if not xml:
......
...@@ -47,7 +47,7 @@ from Products.ERP5Type.Core.Workflow import ValidationFailed ...@@ -47,7 +47,7 @@ from Products.ERP5Type.Core.Workflow import ValidationFailed
from zExceptions import Redirect from zExceptions import Redirect
try: try:
transaction.Base_checkConsistency() transaction.Base_checkConsistency()
except ValidationFailed, error_message: except ValidationFailed as error_message:
if getattr(error_message, 'msg', None): if getattr(error_message, 'msg', None):
# use of Message class to store message+mapping+domain # use of Message class to store message+mapping+domain
message = error_message.msg message = error_message.msg
......
...@@ -239,7 +239,7 @@ class TestListBox(ERP5TypeTestCase): ...@@ -239,7 +239,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module request['here'] = portal.foo_module
try: try:
listbox.get_value('default', render_format='list', REQUEST=request) listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e: except UnicodeError as e:
self.fail('Rendering failed: %s' % e) self.fail('Rendering failed: %s' % e)
self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request)) self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request))
...@@ -269,7 +269,7 @@ class TestListBox(ERP5TypeTestCase): ...@@ -269,7 +269,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module request['here'] = portal.foo_module
try: try:
listbox.get_value('default', render_format='list', REQUEST=request) listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e: except UnicodeError as e:
self.fail('Rendering failed: %s' % e) self.fail('Rendering failed: %s' % e)
self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request)) self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request))
...@@ -303,7 +303,7 @@ class TestListBox(ERP5TypeTestCase): ...@@ -303,7 +303,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module request['here'] = portal.foo_module
try: try:
listbox.get_value('default', render_format='list', REQUEST=request) listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e: except UnicodeError as e:
self.fail('Rendering failed: %s' % e) self.fail('Rendering failed: %s' % e)
self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request)) self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request))
...@@ -337,7 +337,7 @@ class TestListBox(ERP5TypeTestCase): ...@@ -337,7 +337,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module request['here'] = portal.foo_module
try: try:
listbox.get_value('default', render_format='list', REQUEST=request) listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e: except UnicodeError as e:
self.fail('Rendering failed: %s' % e) self.fail('Rendering failed: %s' % e)
self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request)) self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request))
...@@ -359,7 +359,7 @@ class TestListBox(ERP5TypeTestCase): ...@@ -359,7 +359,7 @@ class TestListBox(ERP5TypeTestCase):
listbox.get_value('default', render_format='list', REQUEST=request) listbox.get_value('default', render_format='list', REQUEST=request)
try: try:
self.commit() self.commit()
except TypeError, e: except TypeError as e:
self.fail('Unable to commit transaction: %s' % e) self.fail('Unable to commit transaction: %s' % e)
def test_06_LineFields(self, quiet=0, run=run_all_test): def test_06_LineFields(self, quiet=0, run=run_all_test):
......
...@@ -36,7 +36,7 @@ def urlread(url, safe_return=0): ...@@ -36,7 +36,7 @@ def urlread(url, safe_return=0):
import urllib import urllib
try: try:
return urllib.urlopen(url).read() return urllib.urlopen(url).read()
except IOError, e: except IOError as e:
if safe_return: if safe_return:
# Return an Selenium test code that will obviously fail. This # Return an Selenium test code that will obviously fail. This
# prevent zelenium test run get Stalled. # prevent zelenium test run get Stalled.
......
...@@ -36,7 +36,7 @@ try: ...@@ -36,7 +36,7 @@ try:
user = context.WebSite_createUser(**kwargs) user = context.WebSite_createUser(**kwargs)
log(user) log(user)
msg = 'Thank you for registering. Your password will be sent to the email address that you provided once your account has been validated by the appropriate department.' msg = 'Thank you for registering. Your password will be sent to the email address that you provided once your account has been validated by the appropriate department.'
except Exception, e: except Exception as e:
msg = str(e) msg = str(e)
return req.RESPONSE.redirect(context.absolute_url() + '?portal_status_message='+msg) return req.RESPONSE.redirect(context.absolute_url() + '?portal_status_message='+msg)
...@@ -94,14 +94,14 @@ class SFTPConnection: ...@@ -94,14 +94,14 @@ class SFTPConnection:
raise SFTPError("No password or private_key defined") raise SFTPError("No password or private_key defined")
# Connect # Connect
self.conn = SFTPClient.from_transport(self.transport) self.conn = SFTPClient.from_transport(self.transport)
except (gaierror, error), msg: except (gaierror, error) as msg:
raise SFTPError(str(msg) + ' while establishing connection to %s' % (self.url,)) raise SFTPError(str(msg) + ' while establishing connection to %s' % (self.url,))
# Go to specified directory # Go to specified directory
try: try:
schema.path.rstrip('/') schema.path.rstrip('/')
if len(schema.path): if len(schema.path):
self.conn.chdir(schema.path) self.conn.chdir(schema.path)
except IOError, msg: except IOError as msg:
raise SFTPError(str(msg) + ' while changing to dir -%r-' % (schema.path,)) raise SFTPError(str(msg) + ' while changing to dir -%r-' % (schema.path,))
return self return self
...@@ -113,7 +113,7 @@ class SFTPConnection: ...@@ -113,7 +113,7 @@ class SFTPConnection:
serialized_data = Binary(str(data)) serialized_data = Binary(str(data))
try: try:
self.conn.putfo(StringIO(str(serialized_data)), filepath, confirm=confirm) self.conn.putfo(StringIO(str(serialized_data)), filepath, confirm=confirm)
except error, msg: except error as msg:
raise SFTPError(str(msg) + ' while writing file %s on %s' % (filepath, path)) raise SFTPError(str(msg) + ' while writing file %s on %s' % (filepath, path))
def _getFile(self, filepath): def _getFile(self, filepath):
...@@ -125,7 +125,7 @@ class SFTPConnection: ...@@ -125,7 +125,7 @@ class SFTPConnection:
tmp_file = self.conn.file(filepath, 'rb') tmp_file = self.conn.file(filepath, 'rb')
tmp_file.seek(0) tmp_file.seek(0)
return tmp_file.read() return tmp_file.read()
except error, msg: except error as msg:
raise SFTPError(str(msg) + ' while retrieving file %s from %s' % (filepath, self.url)) raise SFTPError(str(msg) + ' while retrieving file %s from %s' % (filepath, self.url))
def readBinaryFile(self, filepath): def readBinaryFile(self, filepath):
...@@ -149,7 +149,7 @@ class SFTPConnection: ...@@ -149,7 +149,7 @@ class SFTPConnection:
if sort_on: if sort_on:
return [x.filename for x in sorted(self.conn.listdir_attr(path), key=operator.attrgetter(sort_on))] return [x.filename for x in sorted(self.conn.listdir_attr(path), key=operator.attrgetter(sort_on))]
return self.conn.listdir(path) return self.conn.listdir(path)
except (EOFError, error), msg: except (EOFError, error) as msg:
raise SFTPError(str(msg) + ' while trying to list %s on %s' % (path, self.url)) raise SFTPError(str(msg) + ' while trying to list %s on %s' % (path, self.url))
def getDirectoryFileList(self, path): def getDirectoryFileList(self, path):
...@@ -160,14 +160,14 @@ class SFTPConnection: ...@@ -160,14 +160,14 @@ class SFTPConnection:
"""Delete the file""" """Delete the file"""
try: try:
self.conn.unlink(filepath) self.conn.unlink(filepath)
except error, msg: except error as msg:
raise SFTPError(str(msg) + 'while trying to delete %s on %s' % (filepath, self.url)) raise SFTPError(str(msg) + 'while trying to delete %s on %s' % (filepath, self.url))
def renameFile(self, old_path, new_path): def renameFile(self, old_path, new_path):
"""Rename a file""" """Rename a file"""
try: try:
self.conn.rename(old_path, new_path) self.conn.rename(old_path, new_path)
except error, msg: except error as msg:
raise SFTPError('%s while trying to rename "%s" to "%s" on %s.' % \ raise SFTPError('%s while trying to rename "%s" to "%s" on %s.' % \
(str(msg), old_path, new_path, self.url)) (str(msg), old_path, new_path, self.url))
......
...@@ -156,7 +156,7 @@ class MethodWrapper(object): ...@@ -156,7 +156,7 @@ class MethodWrapper(object):
def __call__(self, *args, **kw): def __call__(self, *args, **kw):
try: try:
return self._method(*args, **kw) return self._method(*args, **kw)
except SOAPpy.Types.faultType, exception: except SOAPpy.Types.faultType as exception:
raise SOAPWSDLException(*exception()) raise SOAPWSDLException(*exception())
# SOAPpy says nothing about thread-safeness of parsed WSDL. # SOAPpy says nothing about thread-safeness of parsed WSDL.
......
...@@ -78,6 +78,9 @@ class Python3StyleTest(ERP5TypeTestCase): ...@@ -78,6 +78,9 @@ class Python3StyleTest(ERP5TypeTestCase):
def test_applyFixApplied(self): def test_applyFixApplied(self):
self._testFixer('apply') self._testFixer('apply')
def test_exceptFixApplied(self):
self._testFixer('except')
def test_hasKeyFixApplied(self): def test_hasKeyFixApplied(self):
self._testFixer('has_key') self._testFixer('has_key')
......
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