diff --git a/bin/swift-account-audit b/bin/swift-account-audit index 179bdade2d..026aa2f891 100755 --- a/bin/swift-account-audit +++ b/bin/swift-account-audit @@ -347,7 +347,7 @@ class Auditor(object): if __name__ == '__main__': try: optlist, args = getopt.getopt(sys.argv[1:], 'c:r:e:d') - except getopt.GetoptError, err: + except getopt.GetoptError as err: print str(err) print usage sys.exit(2) diff --git a/bin/swift-dispersion-report b/bin/swift-dispersion-report index 601e76dda9..d5b42eff55 100755 --- a/bin/swift-dispersion-report +++ b/bin/swift-dispersion-report @@ -96,11 +96,11 @@ def container_dispersion_report(coropool, connpool, account, container_ring, container, error_log=error_log, retries=retries) retries_done[0] += attempts - 1 found_count += 1 - except ClientException, err: + except ClientException as err: if err.http_status not in (404, 507): error_log('Giving up on /%s/%s/%s: %s' % (part, account, container, err)) - except (Exception, Timeout), err: + except (Exception, Timeout) as err: error_log('Giving up on /%s/%s/%s: %s' % (part, account, container, err)) if output_missing_partitions and \ @@ -170,7 +170,7 @@ def object_dispersion_report(coropool, connpool, account, object_ring, try: objects = [o['name'] for o in conn.get_container( container, prefix='dispersion_', full_listing=True)[1]] - except ClientException, err: + except ClientException as err: if err.http_status != 404: raise print >>stderr, 'No objects to query. Has ' \ @@ -201,11 +201,11 @@ def object_dispersion_report(coropool, connpool, account, object_ring, container, obj, error_log=error_log, retries=retries) retries_done[0] += attempts - 1 found_count += 1 - except ClientException, err: + except ClientException as err: if err.http_status not in (404, 507): error_log('Giving up on /%s/%s/%s/%s: %s' % (part, account, container, obj, err)) - except (Exception, Timeout), err: + except (Exception, Timeout) as err: error_log('Giving up on /%s/%s/%s/%s: %s' % (part, account, container, obj, err)) if output_missing_partitions and \ diff --git a/bin/swift-ring-builder b/bin/swift-ring-builder index 1b6678fa6a..559ae23e69 100755 --- a/bin/swift-ring-builder +++ b/bin/swift-ring-builder @@ -251,7 +251,7 @@ swift-ring-builder create backup_dir = pathjoin(dirname(argv[1]), 'backups') try: mkdir(backup_dir) - except OSError, err: + except OSError as err: if err.errno != EEXIST: raise builder.save(pathjoin(backup_dir, '%d.' % time() + basename(argv[1]))) @@ -612,7 +612,7 @@ swift-ring-builder remove [search-value ...] for dev in devs: try: builder.remove_dev(dev['id']) - except exceptions.RingBuilderError, e: + except exceptions.RingBuilderError as e: print '-' * 79 print( "An error occurred while removing device with id %d\n" @@ -647,7 +647,7 @@ swift-ring-builder rebalance try: last_balance = builder.get_balance() parts, balance = builder.rebalance(seed=get_seed(3)) - except exceptions.RingBuilderError, e: + except exceptions.RingBuilderError as e: print '-' * 79 print ("An error has occurred during ring validation. Common\n" "causes of failure are rings that are empty or do not\n" @@ -672,7 +672,7 @@ swift-ring-builder rebalance exit(EXIT_WARNING) try: builder.validate() - except exceptions.RingValidationError, e: + except exceptions.RingValidationError as e: print '-' * 79 print ("An error has occurred during ring validation. Common\n" "causes of failure are rings that are empty or do not\n" @@ -813,7 +813,7 @@ if __name__ == '__main__': backup_dir = pathjoin(dirname(argv[1]), 'backups') try: mkdir(backup_dir) - except OSError, err: + except OSError as err: if err.errno != EEXIST: raise diff --git a/swift/account/reaper.py b/swift/account/reaper.py index 0259f31c9a..ef42afa1d1 100644 --- a/swift/account/reaper.py +++ b/swift/account/reaper.py @@ -331,7 +331,7 @@ class AccountReaper(Daemon): self.stats_return_codes[2] = \ self.stats_return_codes.get(2, 0) + 1 self.logger.increment('return_codes.2') - except ClientException, err: + except ClientException as err: if self.logger.getEffectiveLevel() <= DEBUG: self.logger.exception( _('Exception with %(ip)s:%(port)s/%(device)s'), node) @@ -374,7 +374,7 @@ class AccountReaper(Daemon): self.stats_return_codes[2] = \ self.stats_return_codes.get(2, 0) + 1 self.logger.increment('return_codes.2') - except ClientException, err: + except ClientException as err: if self.logger.getEffectiveLevel() <= DEBUG: self.logger.exception( _('Exception with %(ip)s:%(port)s/%(device)s'), node) @@ -433,7 +433,7 @@ class AccountReaper(Daemon): self.stats_return_codes[2] = \ self.stats_return_codes.get(2, 0) + 1 self.logger.increment('return_codes.2') - except ClientException, err: + except ClientException as err: if self.logger.getEffectiveLevel() <= DEBUG: self.logger.exception( _('Exception with %(ip)s:%(port)s/%(device)s'), node) diff --git a/swift/account/server.py b/swift/account/server.py index 530270311f..4e7f54dc9e 100644 --- a/swift/account/server.py +++ b/swift/account/server.py @@ -234,7 +234,7 @@ class AccountController(object): return HTTPInsufficientStorage(drive=drive, request=req) try: args = json.load(req.environ['wsgi.input']) - except ValueError, err: + except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain') ret = self.replicator_rpc.dispatch(post_args, args) ret.request = req diff --git a/swift/common/bench.py b/swift/common/bench.py index be4e9a96d1..97d80488d9 100644 --- a/swift/common/bench.py +++ b/swift/common/bench.py @@ -52,7 +52,7 @@ def delete_containers(logger, conf): def _deleter(url, token, container): try: client.delete_container(url, token, container) - except client.ClientException, e: + except client.ClientException as e: if e.http_status != HTTP_CONFLICT: logger.warn("Unable to delete container '%s'. " "Got http status '%d'." @@ -413,7 +413,7 @@ class BenchDELETE(Bench): direct_client.direct_delete_object(node, partition, self.account, container_name, name) - except client.ClientException, e: + except client.ClientException as e: self.logger.debug(str(e)) self.failures += 1 self.complete += 1 @@ -442,7 +442,7 @@ class BenchGET(Bench): direct_client.direct_get_object(node, partition, self.account, container_name, name) - except client.ClientException, e: + except client.ClientException as e: self.logger.debug(str(e)) self.failures += 1 self.complete += 1 @@ -486,7 +486,7 @@ class BenchPUT(Bench): container_name, name, source, content_length=len(source)) - except client.ClientException, e: + except client.ClientException as e: self.logger.debug(str(e)) self.failures += 1 else: diff --git a/swift/common/bufferedhttp.py b/swift/common/bufferedhttp.py index e3a4b972a6..b302acf1f1 100644 --- a/swift/common/bufferedhttp.py +++ b/swift/common/bufferedhttp.py @@ -130,7 +130,7 @@ def http_connect(ipaddr, port, device, partition, method, path, if isinstance(path, unicode): try: path = path.encode("utf-8") - except UnicodeError, e: + except UnicodeError as e: logging.exception(_('Error encoding to UTF-8: %s'), str(e)) path = quote('/' + device + '/' + str(partition) + path) return http_connect_raw( diff --git a/swift/common/db.py b/swift/common/db.py index c7685ba4da..43c1571405 100644 --- a/swift/common/db.py +++ b/swift/common/db.py @@ -95,7 +95,7 @@ class GreenDBConnection(sqlite3.Connection): while True: try: return call() - except sqlite3.OperationalError, e: + except sqlite3.OperationalError as e: if 'locked' not in str(e): raise sleep(0.05) @@ -305,7 +305,7 @@ class DatabaseBroker(object): os.path.basename(self.db_dir)) try: renamer(self.db_dir, quar_path) - except OSError, e: + except OSError as e: if e.errno not in (errno.EEXIST, errno.ENOTEMPTY): raise quar_path = "%s-%s" % (quar_path, uuid4().hex) @@ -480,7 +480,7 @@ class DatabaseBroker(object): with self.get() as conn: try: curs = conn.execute(query_part1 + 'metadata' + query_part2) - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: if 'no such column: metadata' not in str(err): raise curs = conn.execute(query_part1 + "'' as metadata" + @@ -518,7 +518,7 @@ class DatabaseBroker(object): self.merge_items(item_list) try: os.ftruncate(fp.fileno(), 0) - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise @@ -605,7 +605,7 @@ class DatabaseBroker(object): try: metadata = conn.execute('SELECT metadata FROM %s_stat' % self.db_type).fetchone()[0] - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: if 'no such column: metadata' not in str(err): raise metadata = '' @@ -638,7 +638,7 @@ class DatabaseBroker(object): self.db_type).fetchone()[0] md = json.loads(md) if md else {} utf8encodekeys(md) - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: if 'no such column: metadata' not in str(err): raise conn.execute(""" @@ -678,7 +678,7 @@ class DatabaseBroker(object): conn.execute(''' DELETE FROM incoming_sync WHERE updated_at < ? ''', (sync_timestamp,)) - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: # Old dbs didn't have updated_at in the _sync tables. if 'no such column: updated_at' not in str(err): raise @@ -713,7 +713,7 @@ class DatabaseBroker(object): conn.execute('UPDATE %s_stat SET metadata = ?' % self.db_type, (json.dumps(md),)) return True - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: if 'no such column: metadata' not in str(err): raise return False @@ -915,7 +915,7 @@ class ContainerBroker(DatabaseBroker): pending_size = 0 try: pending_size = os.path.getsize(self.pending_file) - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise if pending_size > PENDING_CAP: @@ -978,7 +978,7 @@ class ContainerBroker(DatabaseBroker): id, %s FROM container_stat ''' % (trailing,)).fetchone() - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: if 'no such column: x_container_sync_point' in str(err): trailing = '-1 AS x_container_sync_point1, ' \ '-1 AS x_container_sync_point2' @@ -998,7 +998,7 @@ class ContainerBroker(DatabaseBroker): try: self._set_x_container_sync_points(conn, sync_point1, sync_point2) - except sqlite3.OperationalError, err: + except sqlite3.OperationalError as err: if 'no such column: x_container_sync_point' not in \ str(err): raise @@ -1377,7 +1377,7 @@ class AccountBroker(DatabaseBroker): pending_size = 0 try: pending_size = os.path.getsize(self.pending_file) - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise if pending_size > PENDING_CAP: diff --git a/swift/common/db_replicator.py b/swift/common/db_replicator.py index 00d0bc277d..41904e027b 100644 --- a/swift/common/db_replicator.py +++ b/swift/common/db_replicator.py @@ -60,7 +60,7 @@ def quarantine_db(object_file, server_type): server_type + 's', os.path.basename(object_dir))) try: renamer(object_dir, quarantine_dir) - except OSError, e: + except OSError as e: if e.errno not in (errno.EEXIST, errno.ENOTEMPTY): raise quarantine_dir = "%s-%s" % (quarantine_dir, uuid.uuid4().hex) @@ -430,7 +430,7 @@ class Replicator(Daemon): self.logger.error( 'Found %s for %s when it should be on partition %s; will ' 'replicate out and remove.' % (object_file, name, bpart)) - except (Exception, Timeout), e: + except (Exception, Timeout) as e: if 'no such table' in str(e): self.logger.error(_('Quarantining DB %s'), object_file) quarantine_db(broker.db_file, broker.db_type) @@ -495,7 +495,7 @@ class Replicator(Daemon): shutil.rmtree(hash_dir, True) try: os.rmdir(suf_dir) - except OSError, err: + except OSError as err: if err.errno not in (errno.ENOENT, errno.ENOTEMPTY): self.logger.exception( _('ERROR while trying to clean up %s') % suf_dir) @@ -604,7 +604,7 @@ class ReplicatorRpc(object): timemark = time.time() try: info = broker.get_replication_info() - except (Exception, Timeout), e: + except (Exception, Timeout) as e: if 'no such table' in str(e): self.logger.error(_("Quarantining DB %s") % broker.db_file) quarantine_db(broker.db_file, broker.db_type) diff --git a/swift/common/direct_client.py b/swift/common/direct_client.py index d85c7016de..36e495ca79 100644 --- a/swift/common/direct_client.py +++ b/swift/common/direct_client.py @@ -469,12 +469,12 @@ def retry(func, *args, **kwargs): attempts += 1 try: return attempts, func(*args, **kwargs) - except (socket.error, HTTPException, Timeout), err: + except (socket.error, HTTPException, Timeout) as err: if error_log: error_log(err) if attempts > retries: raise - except ClientException, err: + except ClientException as err: if error_log: error_log(err) if attempts > retries or not is_server_error(err.http_status) or \ diff --git a/swift/common/manager.py b/swift/common/manager.py index 3672b7761a..b080da6f8b 100644 --- a/swift/common/manager.py +++ b/swift/common/manager.py @@ -100,7 +100,7 @@ def watch_server_pids(server_pids, interval=1, **kwargs): try: # let pid stop if it wants to os.waitpid(pid, os.WNOHANG) - except OSError, e: + except OSError as e: if e.errno not in (errno.ECHILD, errno.ESRCH): raise # else no such child/process # check running pids for server @@ -443,7 +443,7 @@ class Server(): print _('Signal %s pid: %s signal: %s') % (self.server, pid, sig) os.kill(pid, sig) - except OSError, e: + except OSError as e: if e.errno == errno.ESRCH: # pid does not exist if kwargs.get('verbose'): @@ -611,7 +611,7 @@ class Server(): print '%s...(%s)' % (msg, conf_file) try: pid = self.spawn(conf_file, **kwargs) - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: #TODO(clayg): should I check if self.cmd exists earlier? print _("%s does not exist") % self.cmd diff --git a/swift/common/memcached.py b/swift/common/memcached.py index 1b986b85cc..3e5eb13afd 100644 --- a/swift/common/memcached.py +++ b/swift/common/memcached.py @@ -174,7 +174,7 @@ class MemcacheRing(object): sock.connect((host, int(port))) sock.settimeout(self._io_timeout) yield server, sock.makefile(), sock - except Exception, e: + except Exception as e: self._exception_occurred( server, e, action='connecting', sock=sock) @@ -221,7 +221,7 @@ class MemcacheRing(object): (key, flags, timeout, len(value), value)) self._return_conn(server, fp, sock) return - except Exception, e: + except Exception as e: self._exception_occurred(server, e, sock=sock, fp=fp) def get(self, key): @@ -254,7 +254,7 @@ class MemcacheRing(object): line = fp.readline().strip().split() self._return_conn(server, fp, sock) return value - except Exception, e: + except Exception as e: self._exception_occurred(server, e, sock=sock, fp=fp) def incr(self, key, delta=1, time=0, timeout=0): @@ -306,7 +306,7 @@ class MemcacheRing(object): ret = int(line[0].strip()) self._return_conn(server, fp, sock) return ret - except Exception, e: + except Exception as e: self._exception_occurred(server, e, sock=sock, fp=fp) raise MemcacheConnectionError("No Memcached connections succeeded.") @@ -343,7 +343,7 @@ class MemcacheRing(object): sock.sendall('delete %s noreply\r\n' % key) self._return_conn(server, fp, sock) return - except Exception, e: + except Exception as e: self._exception_occurred(server, e, sock=sock, fp=fp) def set_multi(self, mapping, server_key, serialize=True, timeout=0, @@ -391,7 +391,7 @@ class MemcacheRing(object): sock.sendall(msg) self._return_conn(server, fp, sock) return - except Exception, e: + except Exception as e: self._exception_occurred(server, e, sock=sock, fp=fp) def get_multi(self, keys, server_key): @@ -432,5 +432,5 @@ class MemcacheRing(object): values.append(None) self._return_conn(server, fp, sock) return values - except Exception, e: + except Exception as e: self._exception_occurred(server, e, sock=sock, fp=fp) diff --git a/swift/common/middleware/bulk.py b/swift/common/middleware/bulk.py index 29c2ff11aa..89971ed6b5 100644 --- a/swift/common/middleware/bulk.py +++ b/swift/common/middleware/bulk.py @@ -343,7 +343,7 @@ class Bulk(object): resp_dict['Response Status'] = HTTPBadRequest().status resp_dict['Response Body'] = 'Invalid bulk delete.' - except HTTPException, err: + except HTTPException as err: resp_dict['Response Status'] = err.status resp_dict['Response Body'] = err.body except Exception: @@ -436,7 +436,7 @@ class Bulk(object): raise HTTPBadRequest( 'More than %d containers to create ' 'from tar.' % self.max_containers) - except CreateContainerError, err: + except CreateContainerError as err: # the object PUT to this container still may # succeed if acls are set container_failure = [ @@ -483,10 +483,10 @@ class Bulk(object): resp_dict['Response Status'] = HTTPBadRequest().status resp_dict['Response Body'] = 'Invalid Tar File: No Valid Files' - except HTTPException, err: + except HTTPException as err: resp_dict['Response Status'] = err.status resp_dict['Response Body'] = err.body - except tarfile.TarError, tar_error: + except tarfile.TarError as tar_error: resp_dict['Response Status'] = HTTPBadRequest().status resp_dict['Response Body'] = 'Invalid Tar File: %s' % tar_error except Exception: diff --git a/swift/common/middleware/catch_errors.py b/swift/common/middleware/catch_errors.py index 8401c683ea..1141a2f30f 100644 --- a/swift/common/middleware/catch_errors.py +++ b/swift/common/middleware/catch_errors.py @@ -35,7 +35,7 @@ class CatchErrorsContext(WSGIContext): try: # catch any errors in the pipeline resp = self._app_call(env) - except (Exception, Timeout), err: + except (Exception, Timeout) as err: self.logger.exception(_('Error: %s'), err) resp = HTTPServerError(request=Request(env), body='An error occurred', diff --git a/swift/common/middleware/formpost.py b/swift/common/middleware/formpost.py index 05311a97e0..dd0e84d35e 100644 --- a/swift/common/middleware/formpost.py +++ b/swift/common/middleware/formpost.py @@ -320,7 +320,7 @@ class FormPost(object): env, attrs['boundary']) start_response(status, headers) return body - except (FormInvalid, EOFError), err: + except (FormInvalid, EOFError) as err: body = 'FormPost: %s' % err start_response( '400 Bad Request', diff --git a/swift/common/middleware/ratelimit.py b/swift/common/middleware/ratelimit.py index 430005359e..e22dd5d5f3 100644 --- a/swift/common/middleware/ratelimit.py +++ b/swift/common/middleware/ratelimit.py @@ -231,7 +231,7 @@ class RateLimitMiddleware(object): 'container': container_name, 'object': obj_name}) if need_to_sleep > 0: eventlet.sleep(need_to_sleep) - except MaxSleepTimeHitError, e: + except MaxSleepTimeHitError as e: self.logger.error( _('Returning 498 for %(meth)s to %(acc)s/%(cont)s/%(obj)s ' '. Ratelimit (Max Sleep) %(e)s'), diff --git a/swift/common/middleware/recon.py b/swift/common/middleware/recon.py index 9bb4d47d4f..504c6e0831 100644 --- a/swift/common/middleware/recon.py +++ b/swift/common/middleware/recon.py @@ -228,7 +228,7 @@ class ReconMiddleware(object): md5sum.update(block) block = f.read(4096) sums[ringfile] = md5sum.hexdigest() - except IOError, err: + except IOError as err: sums[ringfile] = None if err.errno != errno.ENOENT: self.logger.exception(_('Error reading ringfile')) diff --git a/swift/common/middleware/slo.py b/swift/common/middleware/slo.py index 34ff158d26..48760867b5 100644 --- a/swift/common/middleware/slo.py +++ b/swift/common/middleware/slo.py @@ -428,7 +428,7 @@ class StaticLargeObject(object): body='X-Static-Large-Object is a reserved header. ' 'To create a static large object add query param ' 'multipart-manifest=put.') - except HTTPException, err_resp: + except HTTPException as err_resp: return err_resp(env, start_response) return self.app(env, start_response) diff --git a/swift/common/swob.py b/swift/common/swob.py index 25435fd1fe..a10bb2af53 100644 --- a/swift/common/swob.py +++ b/swift/common/swob.py @@ -1184,7 +1184,7 @@ def wsgify(func): def _wsgify_self(self, env, start_response): try: return func(self, Request(env))(env, start_response) - except HTTPException, err_resp: + except HTTPException as err_resp: return err_resp(env, start_response) return _wsgify_self else: @@ -1192,7 +1192,7 @@ def wsgify(func): def _wsgify_bare(env, start_response): try: return func(Request(env))(env, start_response) - except HTTPException, err_resp: + except HTTPException as err_resp: return err_resp(env, start_response) return _wsgify_bare diff --git a/swift/common/utils.py b/swift/common/utils.py index 6e8cb91088..f316cc8d45 100644 --- a/swift/common/utils.py +++ b/swift/common/utils.py @@ -447,7 +447,7 @@ def mkdirs(path): if not os.path.isdir(path): try: os.makedirs(path) - except OSError, err: + except OSError as err: if err.errno != errno.EEXIST or not os.path.isdir(path): raise @@ -924,7 +924,7 @@ def get_logger(conf, name=None, log_to_console=False, log_route=None, log_address = conf.get('log_address', '/dev/log') try: handler = SysLogHandler(address=log_address, facility=facility) - except socket.error, e: + except socket.error as e: # Either /dev/log isn't a UNIX socket or it does not exist at all if e.errno not in [errno.ENOTSOCK, errno.ENOENT]: raise e @@ -1200,7 +1200,7 @@ def lock_path(directory, timeout=10): try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) break - except IOError, err: + except IOError as err: if err.errno != errno.EAGAIN: raise sleep(0.01) @@ -1235,7 +1235,7 @@ def lock_file(filename, timeout=10, append=False, unlink=True): try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) break - except IOError, err: + except IOError as err: if err.errno != errno.EAGAIN: raise sleep(0.01) @@ -1499,7 +1499,7 @@ def write_file(path, contents): if not os.path.exists(dirname): try: os.makedirs(dirname) - except OSError, err: + except OSError as err: if err.errno == errno.EACCES: sys.exit('Unable to create %s. Running as ' 'non-root?' % dirname) @@ -1821,7 +1821,7 @@ def dump_recon_cache(cache_dict, cache_file, logger, lock_timeout=2): finally: try: os.unlink(tf.name) - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise except (Exception, Timeout): @@ -1831,7 +1831,7 @@ def dump_recon_cache(cache_dict, cache_file, logger, lock_timeout=2): def listdir(path): try: return os.listdir(path) - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise return [] @@ -2020,7 +2020,7 @@ def tpool_reraise(func, *args, **kwargs): def inner(): try: return func(*args, **kwargs) - except BaseException, err: + except BaseException as err: return err resp = tpool.execute(inner) if isinstance(resp, BaseException): @@ -2093,7 +2093,7 @@ class ThreadPool(object): try: result = func(*args, **kwargs) result_queue.put((ev, True, result)) - except BaseException, err: + except BaseException as err: result_queue.put((ev, False, err)) finally: work_queue.task_done() diff --git a/swift/common/wsgi.py b/swift/common/wsgi.py index c804378a36..4d40602fbf 100644 --- a/swift/common/wsgi.py +++ b/swift/common/wsgi.py @@ -158,7 +158,7 @@ def get_socket(conf, default_port=8080): warn_ssl = True sock = ssl.wrap_socket(sock, certfile=conf['cert_file'], keyfile=conf['key_file']) - except socket.error, err: + except socket.error as err: if err.args[0] != errno.EADDRINUSE: raise sleep(0.1) @@ -225,7 +225,7 @@ def run_server(conf, logger, sock): pool = RestrictedGreenPool(size=max_clients) try: wsgi.server(sock, app, NullLogger(), custom_pool=pool) - except socket.error, err: + except socket.error as err: if err[0] != errno.EINVAL: raise pool.waitall() @@ -243,7 +243,7 @@ def run_wsgi(conf_path, app_section, *args, **kwargs): try: (conf, logger, log_name) = \ _initrp(conf_path, app_section, *args, **kwargs) - except ConfigFileError, e: + except ConfigFileError as e: print e return @@ -303,7 +303,7 @@ def run_wsgi(conf_path, app_section, *args, **kwargs): if os.WIFEXITED(status) or os.WIFSIGNALED(status): logger.error('Removing dead child %s' % pid) children.remove(pid) - except OSError, err: + except OSError as err: if err.errno not in (errno.EINTR, errno.ECHILD): raise except KeyboardInterrupt: @@ -321,7 +321,7 @@ class ConfigFileError(Exception): def _initrp(conf_path, app_section, *args, **kwargs): try: conf = appconfig(conf_path, name=app_section) - except Exception, e: + except Exception as e: raise ConfigFileError("Error trying to load config from %s: %s" % (conf_path, e)) diff --git a/swift/container/server.py b/swift/container/server.py index 304a4a2fdb..702d2962e8 100644 --- a/swift/container/server.py +++ b/swift/container/server.py @@ -430,7 +430,7 @@ class ContainerController(object): return HTTPInsufficientStorage(drive=drive, request=req) try: args = json.load(req.environ['wsgi.input']) - except ValueError, err: + except ValueError as err: return HTTPBadRequest(body=str(err), content_type='text/plain') ret = self.replicator_rpc.dispatch(post_args, args) ret.request = req diff --git a/swift/container/sync.py b/swift/container/sync.py index 0bbf7f49c4..0272174ea4 100644 --- a/swift/container/sync.py +++ b/swift/container/sync.py @@ -323,7 +323,7 @@ class ContainerSync(Daemon): headers={'x-timestamp': row['created_at'], 'x-container-sync-key': sync_key}, proxy=self.proxy) - except ClientException, err: + except ClientException as err: if err.http_status != HTTP_NOT_FOUND: raise self.container_deletes += 1 @@ -348,14 +348,14 @@ class ContainerSync(Daemon): timestamp = this_timestamp headers = these_headers body = this_body - except ClientException, err: + except ClientException as err: # If any errors are not 404, make sure we report the # non-404 one. We don't want to mistakenly assume the # object no longer exists just because one says so and # the others errored for some other reason. if not exc or exc.http_status == HTTP_NOT_FOUND: exc = err - except (Exception, Timeout), err: + except (Exception, Timeout) as err: exc = err if timestamp < looking_for_timestamp: if exc: @@ -380,7 +380,7 @@ class ContainerSync(Daemon): self.container_puts += 1 self.logger.increment('puts') self.logger.timing_since('puts.timing', start_time) - except ClientException, err: + except ClientException as err: if err.http_status == HTTP_UNAUTHORIZED: self.logger.info( _('Unauth %(sync_from)r => %(sync_to)r'), @@ -401,7 +401,7 @@ class ContainerSync(Daemon): self.container_failures += 1 self.logger.increment('failures') return False - except (Exception, Timeout), err: + except (Exception, Timeout) as err: self.logger.exception( _('ERROR Syncing %(db_file)s %(row)s'), {'db_file': broker.db_file, 'row': row}) diff --git a/swift/obj/diskfile.py b/swift/obj/diskfile.py index b116c9a044..531f4e1dd9 100644 --- a/swift/obj/diskfile.py +++ b/swift/obj/diskfile.py @@ -102,7 +102,7 @@ def quarantine_renamer(device_path, corrupted_file_path): invalidate_hash(dirname(from_dir)) try: renamer(from_dir, to_dir) - except OSError, e: + except OSError as e: if e.errno not in (errno.EEXIST, errno.ENOTEMPTY): raise to_dir = "%s-%s" % (to_dir, uuid.uuid4().hex) @@ -156,7 +156,7 @@ def hash_suffix(path, reclaim_age): md5 = hashlib.md5() try: path_contents = sorted(os.listdir(path)) - except OSError, err: + except OSError as err: if err.errno in (errno.ENOTDIR, errno.ENOENT): raise PathNotDir() raise @@ -164,7 +164,7 @@ def hash_suffix(path, reclaim_age): hsh_path = join(path, hsh) try: files = hash_cleanup_listdir(hsh_path, reclaim_age) - except OSError, err: + except OSError as err: if err.errno == errno.ENOTDIR: partition_path = dirname(path) objects_path = dirname(partition_path) @@ -601,7 +601,7 @@ class DiskFile(object): try: if verify_file: self._handle_close_quarantine() - except (Exception, Timeout), e: + except (Exception, Timeout) as e: self.logger.error(_( 'ERROR DiskFile %(data_file)s in ' '%(data_dir)s close failure: %(exc)s : %(stack)s'), @@ -720,7 +720,7 @@ class DiskFile(object): 'Content-Length of %s does not match file size ' 'of %s' % (metadata_size, file_size)) return file_size - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise raise DiskFileNotExist('Data File does not exist.') diff --git a/swift/obj/expirer.py b/swift/obj/expirer.py index 959d9ba092..9928520d71 100644 --- a/swift/obj/expirer.py +++ b/swift/obj/expirer.py @@ -134,7 +134,7 @@ class ObjectExpirer(Daemon): self.expiring_objects_account, container, acceptable_statuses=(2, HTTP_NOT_FOUND, HTTP_CONFLICT)) - except (Exception, Timeout), err: + except (Exception, Timeout) as err: self.logger.exception( _('Exception while deleting container %s %s') % (container, str(err))) @@ -205,7 +205,7 @@ class ObjectExpirer(Daemon): container, obj) self.report_objects += 1 self.logger.increment('objects') - except (Exception, Timeout), err: + except (Exception, Timeout) as err: self.logger.increment('errors') self.logger.exception( _('Exception while deleting object %s %s %s') % diff --git a/swift/proxy/controllers/container.py b/swift/proxy/controllers/container.py index 049c289431..a20a782452 100644 --- a/swift/proxy/controllers/container.py +++ b/swift/proxy/controllers/container.py @@ -64,7 +64,7 @@ class ContainerController(Controller): req.headers[header] = \ req.environ['swift.clean_acl'](header, req.headers[header]) - except ValueError, err: + except ValueError as err: return HTTPBadRequest(request=req, body=str(err)) return None diff --git a/swift/proxy/controllers/obj.py b/swift/proxy/controllers/obj.py index c2171f73c7..77dbeb90a4 100644 --- a/swift/proxy/controllers/obj.py +++ b/swift/proxy/controllers/obj.py @@ -240,7 +240,7 @@ class SegmentedIterable(object): self.segment_iter_swift_conn = getattr(resp, 'swift_conn', None) except StopIteration: raise - except SegmentError, err: + except SegmentError as err: if not getattr(err, 'swift_logged', False): self.controller.app.logger.error(_( 'ERROR: While processing manifest ' @@ -251,7 +251,7 @@ class SegmentedIterable(object): err.swift_logged = True self.response.status_int = HTTP_CONFLICT raise - except (Exception, Timeout), err: + except (Exception, Timeout) as err: if not getattr(err, 'swift_logged', False): self.controller.app.logger.exception(_( 'ERROR: While processing manifest ' @@ -298,7 +298,7 @@ class SegmentedIterable(object): # created an invalid condition. yield ' ' raise - except (Exception, Timeout), err: + except (Exception, Timeout) as err: if not getattr(err, 'swift_logged', False): self.controller.app.logger.exception(_( 'ERROR: While processing manifest ' @@ -360,7 +360,7 @@ class SegmentedIterable(object): self.segment_iter = None except StopIteration: raise - except (Exception, Timeout), err: + except (Exception, Timeout) as err: if not getattr(err, 'swift_logged', False): self.controller.app.logger.exception(_( 'ERROR: While processing manifest ' @@ -568,7 +568,7 @@ class ObjectController(Controller): self._remaining_items(pages_iter)) except ListingIterNotFound: return HTTPNotFound(request=req) - except ListingIterNotAuthorized, err: + except ListingIterNotAuthorized as err: return err.aresp except ListingIterError: return HTTPServerError(request=req) @@ -1068,7 +1068,7 @@ class ObjectController(Controller): if conn.queue.unfinished_tasks: conn.queue.join() conns = [conn for conn in conns if not conn.failed] - except ChunkReadTimeout, err: + except ChunkReadTimeout as err: self.app.logger.warn( _('ERROR Client read timeout (%ss)'), err.seconds) self.app.logger.increment('client_timeouts') @@ -1156,7 +1156,7 @@ class ObjectController(Controller): except ListingIterNotFound: # no worries, last_item is None pass - except ListingIterNotAuthorized, err: + except ListingIterNotAuthorized as err: return err.aresp except ListingIterError: return HTTPServerError(request=req) diff --git a/test/functional/swift_test_client.py b/test/functional/swift_test_client.py index 6f11762e12..f9e031b67b 100644 --- a/test/functional/swift_test_client.py +++ b/test/functional/swift_test_client.py @@ -721,7 +721,7 @@ class File(Base): callback(transferred, self.size) self.conn.put_end() - except socket.timeout, err: + except socket.timeout as err: raise err if (self.conn.response.status < 200) or \ diff --git a/test/functional/tests.py b/test/functional/tests.py index 9728379e60..3707082dc6 100644 --- a/test/functional/tests.py +++ b/test/functional/tests.py @@ -100,7 +100,7 @@ def timeout(seconds, method, *args, **kwargs): def run(self): try: self.method(*self.args, **self.kwargs) - except Exception, e: + except Exception as e: self.exception = e t = TimeoutThread(method, *args, **kwargs) diff --git a/test/functionalnosetests/swift_testing.py b/test/functionalnosetests/swift_testing.py index 837af997f8..eabd3476df 100644 --- a/test/functionalnosetests/swift_testing.py +++ b/test/functionalnosetests/swift_testing.py @@ -60,13 +60,13 @@ if conf: '%s:' % conf['account2'] if 'account2' in conf else '', conf['username2']) swift_test_key[1] = conf['password2'] - except KeyError, err: + except KeyError as err: pass # old conf, no second account tests can be run try: swift_test_user[2] = '%s%s' % ('%s:' % conf['account'] if 'account' in conf else '', conf['username3']) swift_test_key[2] = conf['password3'] - except KeyError, err: + except KeyError as err: pass # old conf, no third account tests can be run for _ in range(3): diff --git a/test/functionalnosetests/test_container.py b/test/functionalnosetests/test_container.py index c3bd527f9d..9e344831e0 100755 --- a/test/functionalnosetests/test_container.py +++ b/test/functionalnosetests/test_container.py @@ -426,7 +426,7 @@ class TestContainer(unittest.TestCase): try: resp = retry(get) raise Exception('Should not have been able to GET') - except Exception, err: + except Exception as err: self.assert_(str(err).startswith('No result after '), err) def post(url, token, parsed, conn): @@ -453,7 +453,7 @@ class TestContainer(unittest.TestCase): try: resp = retry(get) raise Exception('Should not have been able to GET') - except Exception, err: + except Exception as err: self.assert_(str(err).startswith('No result after '), err) def test_cross_account_container(self): diff --git a/test/functionalnosetests/test_object.py b/test/functionalnosetests/test_object.py index 36f839aa15..17e58c8233 100755 --- a/test/functionalnosetests/test_object.py +++ b/test/functionalnosetests/test_object.py @@ -168,7 +168,7 @@ class TestObject(unittest.TestCase): try: resp = retry(get) raise Exception('Should not have been able to GET') - except Exception, err: + except Exception as err: self.assert_(str(err).startswith('No result after ')) def post(url, token, parsed, conn): @@ -193,7 +193,7 @@ class TestObject(unittest.TestCase): try: resp = retry(get) raise Exception('Should not have been able to GET') - except Exception, err: + except Exception as err: self.assert_(str(err).startswith('No result after ')) def test_private_object(self): diff --git a/test/probe/common.py b/test/probe/common.py index 71d3bfbcbd..8a88a902cb 100644 --- a/test/probe/common.py +++ b/test/probe/common.py @@ -70,7 +70,7 @@ def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT): raise Exception( 'Unexpected status %s' % resp.status) break - except Exception, err: + except Exception as err: if time() > try_until: print err print 'Giving up on %s:%s after %s seconds.' % ( @@ -86,7 +86,7 @@ def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT): account = url.split('/')[-1] head_account(url, token) return url, token, account - except Exception, err: + except Exception as err: if time() > try_until: print err print 'Giving up on proxy:8080 after 30 seconds.' @@ -98,7 +98,7 @@ def check_server(port, port2server, pids, timeout=CHECK_SERVER_TIMEOUT): def kill_server(port, port2server, pids): try: kill(pids[port2server[port]], SIGTERM) - except Exception, err: + except Exception as err: print err try_until = time() + 30 while True: @@ -106,7 +106,7 @@ def kill_server(port, port2server, pids): conn = HTTPConnection('127.0.0.1', port) conn.request('GET', '/') conn.getresponse() - except Exception, err: + except Exception as err: break if time() > try_until: raise Exception( diff --git a/test/probe/test_container_failures.py b/test/probe/test_container_failures.py index e71d11bf75..fe0feeed4d 100755 --- a/test/probe/test_container_failures.py +++ b/test/probe/test_container_failures.py @@ -107,7 +107,7 @@ class TestContainerFailures(TestCase): try: direct_client.direct_get_container(cnode, cpart, self.account, container1) - except client.ClientException, err: + except client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) headers, containers = client.get_account(self.url, self.token) @@ -147,7 +147,7 @@ class TestContainerFailures(TestCase): exc = None try: client.delete_container(self.url, self.token, container) - except client.ClientException, err: + except client.ClientException as err: exc = err self.assertEquals(exc.http_status, 503) else: @@ -160,7 +160,7 @@ class TestContainerFailures(TestCase): pool.spawn(run_test, 2, True) pool.spawn(run_test, 3, True) pool.waitall() - except Timeout, err: + except Timeout as err: raise Exception( "The server did not return a 503 on container db locks, " "it just hangs: %s" % err) diff --git a/test/probe/test_empty_device_handoff.py b/test/probe/test_empty_device_handoff.py index 5cb25d7083..74bc3c2bee 100644 --- a/test/probe/test_empty_device_handoff.py +++ b/test/probe/test_empty_device_handoff.py @@ -118,7 +118,7 @@ class TestEmptyDevice(TestCase): try: direct_client.direct_get_object(onode, opart, self.account, container, obj) - except direct_client.ClientException, err: + except direct_client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) self.assertFalse(os.path.exists(obj_dir)) @@ -147,7 +147,7 @@ class TestEmptyDevice(TestCase): try: direct_client.direct_get_object(another_onode, opart, self.account, container, obj) - except direct_client.ClientException, err: + except direct_client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) diff --git a/test/probe/test_object_failures.py b/test/probe/test_object_failures.py index 7b5e7ed175..e7f6bf5bf1 100755 --- a/test/probe/test_object_failures.py +++ b/test/probe/test_object_failures.py @@ -80,7 +80,7 @@ class TestObjectFailures(TestCase): direct_client.direct_get_object(onode, opart, self.account, container, obj) raise Exception("Did not quarantine object") - except client.ClientException, err: + except client.ClientException as err: self.assertEquals(err.http_status, 404) def run_quarantine_range_etag(self): @@ -104,7 +104,7 @@ class TestObjectFailures(TestCase): direct_client.direct_get_object(onode, opart, self.account, container, obj) raise Exception("Did not quarantine object") - except client.ClientException, err: + except client.ClientException as err: self.assertEquals(err.http_status, 404) def run_quarantine_zero_byte_get(self): @@ -122,7 +122,7 @@ class TestObjectFailures(TestCase): container, obj, conn_timeout=1, response_timeout=1) raise Exception("Did not quarantine object") - except client.ClientException, err: + except client.ClientException as err: self.assertEquals(err.http_status, 404) def run_quarantine_zero_byte_head(self): @@ -140,7 +140,7 @@ class TestObjectFailures(TestCase): container, obj, conn_timeout=1, response_timeout=1) raise Exception("Did not quarantine object") - except client.ClientException, err: + except client.ClientException as err: self.assertEquals(err.http_status, 404) def run_quarantine_zero_byte_post(self): @@ -161,7 +161,7 @@ class TestObjectFailures(TestCase): conn_timeout=1, response_timeout=1) raise Exception("Did not quarantine object") - except client.ClientException, err: + except client.ClientException as err: self.assertEquals(err.http_status, 404) def test_runner(self): diff --git a/test/probe/test_object_handoff.py b/test/probe/test_object_handoff.py index a213cbf7d3..cf2ae3c148 100755 --- a/test/probe/test_object_handoff.py +++ b/test/probe/test_object_handoff.py @@ -110,7 +110,7 @@ class TestObjectHandoff(TestCase): try: direct_client.direct_get_object(onode, opart, self.account, container, obj) - except direct_client.ClientException, err: + except direct_client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) # Run the extra server last so it'll remove its extra partition @@ -142,7 +142,7 @@ class TestObjectHandoff(TestCase): try: direct_client.direct_get_object(another_onode, opart, self.account, container, obj) - except direct_client.ClientException, err: + except direct_client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) @@ -151,7 +151,7 @@ class TestObjectHandoff(TestCase): exc = None try: client.head_object(self.url, self.token, container, obj) - except direct_client.ClientException, err: + except direct_client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) objs = [o['name'] for o in @@ -189,7 +189,7 @@ class TestObjectHandoff(TestCase): try: direct_client.direct_get_object(another_onode, opart, self.account, container, obj) - except direct_client.ClientException, err: + except direct_client.ClientException as err: exc = err self.assertEquals(exc.http_status, 404) diff --git a/test/unit/account/test_server.py b/test/unit/account/test_server.py index 3827290e60..8461071409 100644 --- a/test/unit/account/test_server.py +++ b/test/unit/account/test_server.py @@ -41,7 +41,7 @@ class TestAccountController(unittest.TestCase): """Tear down for testing swift.account.server.AccountController""" try: rmtree(self.testdir) - except OSError, err: + except OSError as err: if err.errno != errno.ENOENT: raise diff --git a/test/unit/common/middleware/test_formpost.py b/test/unit/common/middleware/test_formpost.py index 6530e98431..282497b7f5 100644 --- a/test/unit/common/middleware/test_formpost.py +++ b/test/unit/common/middleware/test_formpost.py @@ -89,7 +89,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except formpost.FormInvalid, err: + except formpost.FormInvalid as err: exc = err self.assertEquals(str(exc), 'invalid starting boundary') @@ -100,7 +100,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -112,7 +112,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -127,7 +127,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -146,7 +146,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -162,7 +162,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -176,7 +176,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -195,7 +195,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) @@ -217,7 +217,7 @@ class TestIterRequests(unittest.TestCase): exc = None try: it.next() - except StopIteration, err: + except StopIteration as err: exc = err self.assertTrue(exc is not None) finally: @@ -234,7 +234,7 @@ class TestCappedFileLikeObject(unittest.TestCase): exc = None try: formpost._CappedFileLikeObject(StringIO('abc'), 2).read() - except EOFError, err: + except EOFError as err: exc = err self.assertEquals(str(exc), 'max_file_size exceeded') @@ -250,7 +250,7 @@ class TestCappedFileLikeObject(unittest.TestCase): exc = None try: self.assertEquals(fp.readline(), 'def') - except EOFError, err: + except EOFError as err: exc = err self.assertEquals(str(exc), 'max_file_size exceeded') diff --git a/test/unit/common/middleware/test_memcache.py b/test/unit/common/middleware/test_memcache.py index c4db646d8d..27fe2aac0e 100644 --- a/test/unit/common/middleware/test_memcache.py +++ b/test/unit/common/middleware/test_memcache.py @@ -76,7 +76,7 @@ class TestCacheMiddleware(unittest.TestCase): exc = None try: memcache.MemcacheMiddleware(FakeApp(), {}) - except Exception, err: + except Exception as err: exc = err finally: memcache.ConfigParser = orig_parser @@ -91,7 +91,7 @@ class TestCacheMiddleware(unittest.TestCase): memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5', 'memcache_serialization_support': '2'}) - except Exception, err: + except Exception as err: exc = err finally: memcache.ConfigParser = orig_parser diff --git a/test/unit/common/middleware/test_slo.py b/test/unit/common/middleware/test_slo.py index 1139c7d78f..731dcd6180 100644 --- a/test/unit/common/middleware/test_slo.py +++ b/test/unit/common/middleware/test_slo.py @@ -196,7 +196,7 @@ class TestStaticLargeObject(unittest.TestCase): req.content_length = self.slo.max_manifest_size + 1 try: self.slo.handle_multipart_put(req, fake_start_response) - except HTTPException, e: + except HTTPException as e: pass self.assertEquals(e.status_int, 413) @@ -205,7 +205,7 @@ class TestStaticLargeObject(unittest.TestCase): e = None try: self.slo.handle_multipart_put(req, fake_start_response) - except HTTPException, e: + except HTTPException as e: pass self.assertEquals(e.status_int, 413) @@ -213,14 +213,14 @@ class TestStaticLargeObject(unittest.TestCase): req = Request.blank('/v/a/c/o', body=test_json_data) try: self.slo.handle_multipart_put(req, fake_start_response) - except HTTPException, e: + except HTTPException as e: pass self.assertEquals(e.status_int, 400) req = Request.blank('/v/a/c/o', headers={'X-Copy-From': 'lala'}) try: self.slo.handle_multipart_put(req, fake_start_response) - except HTTPException, e: + except HTTPException as e: pass self.assertEquals(e.status_int, 405) @@ -346,7 +346,7 @@ class TestStaticLargeObject(unittest.TestCase): body=bad_data) try: self.slo.handle_multipart_put(req, fake_start_response) - except HTTPException, e: + except HTTPException as e: self.assertEquals(self.app.calls, 4) data = json.loads(e.body) errors = data['Errors'] diff --git a/test/unit/common/test_bufferedhttp.py b/test/unit/common/test_bufferedhttp.py index 9dd815a652..1e7af06dd0 100644 --- a/test/unit/common/test_bufferedhttp.py +++ b/test/unit/common/test_bufferedhttp.py @@ -46,7 +46,7 @@ class TestBufferedHTTP(unittest.TestCase): self.assertEquals(headers['content-length'], '7') self.assertEquals(headers['x-header'], 'value') self.assertEquals(fp.readline(), 'REQUEST\r\n') - except BaseException, err: + except BaseException as err: return err return None for par in ('par', 1357): diff --git a/test/unit/common/test_db.py b/test/unit/common/test_db.py index 9e5beb437f..58c7a6ecdf 100644 --- a/test/unit/common/test_db.py +++ b/test/unit/common/test_db.py @@ -272,7 +272,7 @@ class TestDatabaseBroker(unittest.TestCase): try: with broker.get() as conn: conn.execute('SELECT * FROM test') - except Exception, err: + except Exception as err: exc = err self.assertEquals( str(exc), @@ -288,7 +288,7 @@ class TestDatabaseBroker(unittest.TestCase): try: with broker.get() as conn: conn.execute('SELECT * FROM test') - except Exception, err: + except Exception as err: exc = err self.assertEquals( str(exc), @@ -1727,7 +1727,7 @@ class TestContainerBrokerBeforeMetadata(TestContainerBroker): with broker.get() as conn: try: conn.execute('SELECT metadata FROM container_stat') - except BaseException, err: + except BaseException as err: exc = err self.assert_('no such column: metadata' in str(exc)) @@ -1802,7 +1802,7 @@ class TestContainerBrokerBeforeXSync(TestContainerBroker): try: conn.execute('''SELECT x_container_sync_point1 FROM container_stat''') - except BaseException, err: + except BaseException as err: exc = err self.assert_('no such column: x_container_sync_point1' in str(exc)) @@ -2318,7 +2318,7 @@ class TestAccountBrokerBeforeMetadata(TestAccountBroker): with broker.get() as conn: try: conn.execute('SELECT metadata FROM account_stat') - except BaseException, err: + except BaseException as err: exc = err self.assert_('no such column: metadata' in str(exc)) diff --git a/test/unit/common/test_internal_client.py b/test/unit/common/test_internal_client.py index d2440342a6..4c021b8d67 100644 --- a/test/unit/common/test_internal_client.py +++ b/test/unit/common/test_internal_client.py @@ -283,12 +283,12 @@ class TestInternalClient(unittest.TestCase): try: client.make_request('GET', '/', {}, (400,)) - except Exception, err: + except Exception as err: pass self.assertEquals(200, err.resp.status_int) try: client.make_request('GET', '/', {}, (201,)) - except Exception, err: + except Exception as err: pass self.assertEquals(200, err.resp.status_int) finally: @@ -323,7 +323,7 @@ class TestInternalClient(unittest.TestCase): internal_client.sleep = not_sleep try: client.make_request('PUT', '/', {}, (2,), fobj) - except Exception, err: + except Exception as err: pass self.assertEquals(404, err.resp.status_int) finally: diff --git a/test/unit/common/test_swob.py b/test/unit/common/test_swob.py index 841556a8a1..ffdaed851d 100644 --- a/test/unit/common/test_swob.py +++ b/test/unit/common/test_swob.py @@ -645,11 +645,11 @@ class TestRequest(unittest.TestCase): self.assertEquals(_test_split_path('/a/c/', 2, 3), ['a', 'c', '']) try: _test_split_path('o\nn e', 2) - except ValueError, err: + except ValueError as err: self.assertEquals(str(err), 'Invalid path: o%0An%20e') try: _test_split_path('o\nn e', 2, 3, True) - except ValueError, err: + except ValueError as err: self.assertEquals(str(err), 'Invalid path: o%0An%20e') def test_unicode_path(self): diff --git a/test/unit/common/test_utils.py b/test/unit/common/test_utils.py index 26c7924b87..7134d8a52a 100644 --- a/test/unit/common/test_utils.py +++ b/test/unit/common/test_utils.py @@ -241,11 +241,11 @@ class TestUtils(unittest.TestCase): self.assertEquals(utils.split_path('/a/c/', 2, 3), ['a', 'c', '']) try: utils.split_path('o\nn e', 2) - except ValueError, err: + except ValueError as err: self.assertEquals(str(err), 'Invalid path: o%0An%20e') try: utils.split_path('o\nn e', 2, 3, True) - except ValueError, err: + except ValueError as err: self.assertEquals(str(err), 'Invalid path: o%0An%20e') def test_validate_device_partition(self): @@ -271,11 +271,11 @@ class TestUtils(unittest.TestCase): utils.validate_device_partition, 'foo', '..') try: utils.validate_device_partition('o\nn e', 'foo') - except ValueError, err: + except ValueError as err: self.assertEquals(str(err), 'Invalid device: o%0An%20e') try: utils.validate_device_partition('foo', 'o\nn e') - except ValueError, err: + except ValueError as err: self.assertEquals(str(err), 'Invalid partition: o%0An%20e') def test_NullLogger(self): @@ -1182,7 +1182,7 @@ log_name = %(yarr)s''' for (value, default), expected in expectations.items(): try: rv = utils.config_auto_int_value(value, default) - except Exception, e: + except Exception as e: if e.__class__ is not expected: raise else: @@ -1245,7 +1245,7 @@ log_name = %(yarr)s''' exc = None try: fallocate(0, 1, 0, ctypes.c_uint64(0)) - except OSError, err: + except OSError as err: exc = err self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024') # Want 1024 reserved, have 512 * 2 free, so fails @@ -1255,7 +1255,7 @@ log_name = %(yarr)s''' exc = None try: fallocate(0, 1, 0, ctypes.c_uint64(0)) - except OSError, err: + except OSError as err: exc = err self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024') # Want 2048 reserved, have 1024 * 1 free, so fails @@ -1265,7 +1265,7 @@ log_name = %(yarr)s''' exc = None try: fallocate(0, 1, 0, ctypes.c_uint64(0)) - except OSError, err: + except OSError as err: exc = err self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 2048') # Want 2048 reserved, have 512 * 2 free, so fails @@ -1275,7 +1275,7 @@ log_name = %(yarr)s''' exc = None try: fallocate(0, 1, 0, ctypes.c_uint64(0)) - except OSError, err: + except OSError as err: exc = err self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 2048') # Want 1023 reserved, have 1024 * 1 free, but file size is 1, so @@ -1286,7 +1286,7 @@ log_name = %(yarr)s''' exc = None try: fallocate(0, 1, 0, ctypes.c_uint64(1)) - except OSError, err: + except OSError as err: exc = err self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1023 <= 1023') # Want 1022 reserved, have 1024 * 1 free, and file size is 1, so @@ -1309,7 +1309,7 @@ log_name = %(yarr)s''' exc = None try: fallocate(0, 1, 0, ctypes.c_uint64(0)) - except OSError, err: + except OSError as err: exc = err self.assertEquals(str(exc), 'FALLOCATE_RESERVE fail 1024 <= 1024') finally: @@ -2038,7 +2038,7 @@ class TestStatsdLoggingDelegation(unittest.TestCase): if payload and 'STOP' in payload: return 42 self.queue.put(payload) - except Exception, e: + except Exception as e: sys.stderr.write('statsd_reader thread: %r' % (e,)) break diff --git a/test/unit/container/test_server.py b/test/unit/container/test_server.py index 7b31096a84..dddff8f6f8 100644 --- a/test/unit/container/test_server.py +++ b/test/unit/container/test_server.py @@ -458,7 +458,7 @@ class TestContainerController(unittest.TestCase): line = inc.readline() self.assertEquals(headers['x-put-timestamp'], expected_timestamp) - except BaseException, err: + except BaseException as err: return err return None @@ -512,7 +512,7 @@ class TestContainerController(unittest.TestCase): try: with Timeout(3): resp = req.get_response(self.controller) - except BaseException, err: + except BaseException as err: got_exc = True finally: err = event.wait() @@ -679,7 +679,7 @@ class TestContainerController(unittest.TestCase): line = inc.readline() self.assertEquals(headers['x-delete-timestamp'], expected_timestamp) - except BaseException, err: + except BaseException as err: return err return None @@ -742,7 +742,7 @@ class TestContainerController(unittest.TestCase): try: with Timeout(3): resp = req.get_response(self.controller) - except BaseException, err: + except BaseException as err: got_exc = True finally: err = event.wait() diff --git a/test/unit/container/test_sync.py b/test/unit/container/test_sync.py index 557e4e228a..163f4e8172 100644 --- a/test/unit/container/test_sync.py +++ b/test/unit/container/test_sync.py @@ -142,7 +142,7 @@ class TestContainerSync(unittest.TestCase): cs = sync.ContainerSync({}, container_ring=FakeRing(), object_ring=FakeRing()) cs.run_forever() - except Exception, err: + except Exception as err: if str(err) != 'we are now done': raise finally: @@ -201,7 +201,7 @@ class TestContainerSync(unittest.TestCase): self.assertEquals(audit_location_generator_calls, [1]) self.assertEquals(cs.reported, 3602) cs.run_once() - except Exception, err: + except Exception as err: if str(err) != 'we are now done': raise finally: diff --git a/test/unit/container/test_updater.py b/test/unit/container/test_updater.py index bb7ca1c870..a7da07b757 100644 --- a/test/unit/container/test_updater.py +++ b/test/unit/container/test_updater.py @@ -129,7 +129,7 @@ class TestContainerUpdater(unittest.TestCase): self.assert_('x-delete-timestamp' in headers) self.assert_('x-object-count' in headers) self.assert_('x-bytes-used' in headers) - except BaseException, err: + except BaseException as err: import traceback traceback.print_exc() return err @@ -185,7 +185,7 @@ class TestContainerUpdater(unittest.TestCase): out.write('HTTP/1.1 201 OK\r\nContent-Length: 0\r\n\r\n') out.flush() inc.read() - except BaseException, err: + except BaseException as err: import traceback traceback.print_exc() return err diff --git a/test/unit/obj/test_expirer.py b/test/unit/obj/test_expirer.py index 118b7e58e1..f406e61bde 100644 --- a/test/unit/obj/test_expirer.py +++ b/test/unit/obj/test_expirer.py @@ -577,7 +577,7 @@ class TestObjectExpirer(TestCase): expirer.sleep = not_sleep x.run_once = raise_system_exit x.run_forever() - except SystemExit, err: + except SystemExit as err: pass finally: expirer.random = orig_random @@ -601,7 +601,7 @@ class TestObjectExpirer(TestCase): expirer.sleep = not_sleep x.run_once = raise_exceptions x.run_forever() - except SystemExit, err: + except SystemExit as err: pass finally: expirer.sleep = orig_sleep @@ -680,7 +680,7 @@ class TestObjectExpirer(TestCase): exc = None try: x.delete_actual_object('/path/to/object', '1234') - except Exception, err: + except Exception as err: exc = err finally: pass diff --git a/test/unit/obj/test_updater.py b/test/unit/obj/test_updater.py index 15b307ea55..ebfac25bbb 100644 --- a/test/unit/obj/test_updater.py +++ b/test/unit/obj/test_updater.py @@ -175,7 +175,7 @@ class TestObjectUpdater(unittest.TestCase): line.split(':')[1].strip() line = inc.readline() self.assert_('x-container-timestamp' in headers) - except BaseException, err: + except BaseException as err: return err return None @@ -192,7 +192,7 @@ class TestObjectUpdater(unittest.TestCase): err = event.wait() if err: raise err - except BaseException, err: + except BaseException as err: return err return None