diff --git a/deluge/common.py b/deluge/common.py index a8b228405..eaf564a31 100644 --- a/deluge/common.py +++ b/deluge/common.py @@ -99,8 +99,8 @@ def get_default_config_dir(filename=None): filename = '' try: return os.path.join(save_config_path("deluge"), filename) - except OSError, e: - log.error("Unable to use default config directory, exiting... (%s)", e) + except OSError as ex: + log.error("Unable to use default config directory, exiting... (%s)", ex) sys.exit(1) @@ -938,8 +938,8 @@ def set_language(lang): try: ro = gettext.translation("deluge", localedir=translations_path, languages=[lang]) ro.install() - except IOError, e: - log.warn("IOError when loading translations: %s", e) + except IOError as ex: + log.warn("IOError when loading translations: %s", ex) # Initialize gettext @@ -965,9 +965,9 @@ def setup_translations(setup_gettext=True, setup_pygtk=False): import gtk.glade gtk.glade.bindtextdomain(domain, translations_path) gtk.glade.textdomain(domain) - except Exception, e: + except Exception as ex: log.error("Unable to initialize glade translation!") - log.exception(e) + log.exception(ex) if setup_gettext: try: if hasattr(locale, "bindtextdomain"): @@ -979,9 +979,9 @@ def setup_translations(setup_gettext=True, setup_pygtk=False): gettext.bind_textdomain_codeset(domain, 'UTF-8') gettext.textdomain(domain) gettext.install(domain, translations_path, unicode=True) - except Exception, e: + except Exception as ex: log.error("Unable to initialize gettext/locale!") - log.exception(e) + log.exception(ex) import __builtin__ __builtin__.__dict__["_"] = lambda x: x diff --git a/deluge/config.py b/deluge/config.py index 013a7a337..d6a1b6ed3 100644 --- a/deluge/config.py +++ b/deluge/config.py @@ -419,8 +419,8 @@ what is currently in the config and it could not convert the value try: data = open(filename, "rb").read() - except IOError, e: - log.warning("Unable to open config file %s: %s", filename, e) + except IOError as ex: + log.warning("Unable to open config file %s: %s", filename, ex) return objects = find_json_objects(data) @@ -429,15 +429,15 @@ what is currently in the config and it could not convert the value # No json objects found, try depickling it try: self.__config.update(pickle.loads(data)) - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) log.warning("Unable to load config file: %s", filename) elif len(objects) == 1: start, end = objects[0] try: self.__config.update(json.loads(data[start:end])) - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) log.warning("Unable to load config file: %s", filename) elif len(objects) == 2: try: @@ -445,8 +445,8 @@ what is currently in the config and it could not convert the value self.__version.update(json.loads(data[start:end])) start, end = objects[1] self.__config.update(json.loads(data[start:end])) - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) log.warning("Unable to load config file: %s", filename) log.debug("Config %s version: %s.%s loaded: %s", filename, @@ -477,8 +477,8 @@ what is currently in the config and it could not convert the value if self._save_timer and self._save_timer.active(): self._save_timer.cancel() return True - except (IOError, IndexError), e: - log.warning("Unable to open config file: %s because: %s", filename, e) + except (IOError, IndexError) as ex: + log.warning("Unable to open config file: %s because: %s", filename, ex) # Save the new config and make sure it's written to disk try: @@ -489,24 +489,24 @@ what is currently in the config and it could not convert the value f.flush() os.fsync(f.fileno()) f.close() - except IOError, e: - log.error("Error writing new config file: %s", e) + except IOError as ex: + log.error("Error writing new config file: %s", ex) return False # Make a backup of the old config try: log.debug("Backing up old config file to %s.bak", filename) shutil.move(filename, filename + ".bak") - except Exception, e: - log.warning("Unable to backup old config...") + except IOError as ex: + log.warning("Unable to backup old config: %s", ex) # The new config file has been written successfully, so let's move it over # the existing one. try: log.debug("Moving new config file %s to %s..", filename + ".new", filename) shutil.move(filename + ".new", filename) - except Exception, e: - log.error("Error moving new config file: %s", e) + except IOError as ex: + log.error("Error moving new config file: %s", ex) return False else: return True @@ -538,8 +538,8 @@ what is currently in the config and it could not convert the value try: self.__config = func(self.__config) - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) log.error("There was an exception try to convert config file %s %s to %s", self.__config_file, self.__version["file"], output_version) raise e diff --git a/deluge/configmanager.py b/deluge/configmanager.py index dc92a534a..0c725661a 100644 --- a/deluge/configmanager.py +++ b/deluge/configmanager.py @@ -74,8 +74,8 @@ class _ConfigManager: # Try to create the config folder if it doesn't exist try: os.makedirs(directory) - except Exception, e: - log.error("Unable to make config directory: %s", e) + except OSError as ex: + log.error("Unable to make config directory: %s", ex) return False elif not os.path.isdir(directory): log.error("Config directory needs to be a directory!") diff --git a/deluge/core/authmanager.py b/deluge/core/authmanager.py index 9f31321cd..6a23c67e0 100644 --- a/deluge/core/authmanager.py +++ b/deluge/core/authmanager.py @@ -134,9 +134,9 @@ class AuthManager(component.Component): AUTH_LEVELS_MAPPING[authlevel]) self.write_auth_file() return True - except Exception, err: - log.exception(err) - raise err + except Exception as ex: + log.exception(ex) + raise ex def update_account(self, username, password, authlevel): if username not in self.__auth: @@ -147,9 +147,9 @@ class AuthManager(component.Component): self.__auth[username].authlevel = AUTH_LEVELS_MAPPING[authlevel] self.write_auth_file() return True - except Exception, err: - log.exception(err) - raise err + except Exception as ex: + log.exception(ex) + raise ex def remove_account(self, username): if username not in self.__auth: @@ -184,7 +184,7 @@ class AuthManager(component.Component): _file.flush() os.fsync(_file.fileno()) shutil.move(filepath_tmp, filepath) - except (IOError) as ex: + except IOError as ex: log.error("Unable to save %s: %s", filename, ex) if os.path.isfile(filepath_bak): log.info("Restoring backup of %s from: %s", filename, filepath_bak) @@ -215,7 +215,7 @@ class AuthManager(component.Component): try: with open(_filepath, "rb") as _file: file_data = _file.readlines() - except (IOError), ex: + except IOError as ex: log.warning("Unable to load %s: %s", _filepath, ex) file_data = [] else: diff --git a/deluge/core/core.py b/deluge/core/core.py index 37c7602c0..08ddd510b 100644 --- a/deluge/core/core.py +++ b/deluge/core/core.py @@ -194,7 +194,7 @@ class Core(component.Component): try: with open(_filepath, "rb") as _file: state = lt.bdecode(_file.read()) - except (IOError, EOFError, RuntimeError), ex: + except (IOError, EOFError, RuntimeError) as ex: log.warning("Unable to load %s: %s", _filepath, ex) else: log.info("Successfully loaded %s: %s", filename, _filepath) @@ -203,12 +203,11 @@ class Core(component.Component): def get_new_release(self): log.debug("get_new_release") - from urllib2 import urlopen + from urllib2 import urlopen, URLError try: - self.new_release = urlopen( - "http://download.deluge-torrent.org/version-1.0").read().strip() - except Exception, e: - log.debug("Unable to get release info from website: %s", e) + self.new_release = urlopen("http://download.deluge-torrent.org/version-1.0").read().strip() + except URLError as ex: + log.debug("Unable to get release info from website: %s", ex) return self.check_new_release() @@ -236,17 +235,17 @@ class Core(component.Component): """ try: filedump = base64.decodestring(filedump) - except Exception, e: + except Exception as ex: log.error("There was an error decoding the filedump string!") - log.exception(e) + log.exception(ex) try: torrent_id = self.torrentmanager.add( filedump=filedump, options=options, filename=filename ) - except Exception, e: + except Exception as ex: log.error("There was an error adding the torrent file %s", filename) - log.exception(e) + log.exception(ex) torrent_id = None return torrent_id @@ -275,11 +274,9 @@ class Core(component.Component): f.close() try: os.remove(filename) - except Exception, e: - log.warning("Couldn't remove temp file: %s", e) - return self.add_torrent_file( - filename, base64.encodestring(data), options - ) + except OSError as ex: + log.warning("Couldn't remove temp file: %s", ex) + return self.add_torrent_file(filename, base64.encodestring(data), options) def on_download_fail(failure): if failure.check(twisted.web.error.PageRedirect): @@ -726,9 +723,9 @@ class Core(component.Component): try: filedump = base64.decodestring(filedump) - except Exception, e: + except Exception as ex: log.error("There was an error decoding the filedump string!") - log.exception(e) + log.exception(ex) return f = open(os.path.join(get_config_dir(), "plugins", filename), "wb") diff --git a/deluge/core/eventmanager.py b/deluge/core/eventmanager.py index a53a10e86..0da2c3494 100644 --- a/deluge/core/eventmanager.py +++ b/deluge/core/eventmanager.py @@ -58,8 +58,8 @@ class EventManager(component.Component): #log.debug("Running handler %s for event %s with args: %s", event.name, handler, event.args) try: handler(*event.args) - except Exception, e: - log.error("Event handler %s failed in %s with exception %s", event.name, handler, e) + except Exception as ex: + log.error("Event handler %s failed in %s with exception %s", event.name, handler, ex) def register_event_handler(self, event, handler): """ diff --git a/deluge/core/pluginmanager.py b/deluge/core/pluginmanager.py index e94ae84ca..35ab9857a 100644 --- a/deluge/core/pluginmanager.py +++ b/deluge/core/pluginmanager.py @@ -74,8 +74,8 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon if hasattr(self.plugins[plugin], "update"): try: self.plugins[plugin].update() - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) def enable_plugin(self, name): if name not in self.plugins: diff --git a/deluge/core/preferencesmanager.py b/deluge/core/preferencesmanager.py index a9787553c..efb70b7c4 100644 --- a/deluge/core/preferencesmanager.py +++ b/deluge/core/preferencesmanager.py @@ -181,8 +181,8 @@ class PreferencesManager(component.Component): if self.config["copy_torrent_file"]: try: os.makedirs(value) - except Exception, e: - log.debug("Unable to make directory: %s", e) + except OSError as ex: + log.debug("Unable to make directory: %s", ex) def _on_set_listen_ports(self, key, value): # Only set the listen ports if random_port is not true @@ -229,8 +229,8 @@ class PreferencesManager(component.Component): log.debug("setting peer_tos to: %s", value) try: self.session_set_setting("peer_tos", chr(int(value, 16))) - except ValueError, e: - log.debug("Invalid tos byte: %s", e) + except ValueError as ex: + log.debug("Invalid tos byte: %s", ex) return def _on_set_dht(self, key, value): @@ -393,8 +393,8 @@ class PreferencesManager(component.Component): + "&os=" + platform.system() \ + "&plugins=" + quote_plus(":".join(self.config["enabled_plugins"])) urlopen(url) - except IOError, e: - log.debug("Network error while trying to send info: %s", e) + except IOError as ex: + log.debug("Network error while trying to send info: %s", ex) else: self.config["info_sent"] = now if value: @@ -460,9 +460,9 @@ class PreferencesManager(component.Component): if geoip_db: try: self.session.load_country_db(str(geoip_db)) - except Exception, e: + except RuntimeError as ex: log.error("Unable to load geoip database!") - log.exception(e) + log.exception(ex) def _on_set_cache_size(self, key, value): log.debug("%s: %s", key, value) diff --git a/deluge/core/rpcserver.py b/deluge/core/rpcserver.py index 776b152e7..361d7615c 100644 --- a/deluge/core/rpcserver.py +++ b/deluge/core/rpcserver.py @@ -235,7 +235,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): exceptionValue._kwargs, formated_tb )) - except AttributeError, err: + except AttributeError as err: # This is not a deluge exception (object has no attribute '_args), let's wrap it log.error("An exception occurred while sending RPC_ERROR to " "client. Wrapping it and resending. Error to " @@ -244,7 +244,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): raise WrappedException(str(exceptionValue), exceptionType.__name__, formated_tb) except: send_error() - except Exception, err: + except Exception as err: log.error("An exception occurred while sending RPC_ERROR to client: %s", err) if method == "daemon.info": @@ -263,10 +263,10 @@ class DelugeRPCProtocol(DelugeTransferProtocol): if ret: self.factory.authorized_sessions[self.transport.sessionno] = (ret, args[0]) self.factory.session_protocols[self.transport.sessionno] = self - except Exception, e: + except Exception as ex: send_error() - if not isinstance(e, _ClientSideRecreateError): - log.exception(e) + if not isinstance(ex, _ClientSideRecreateError): + log.exception(ex) else: self.sendData((RPC_RESPONSE, request_id, (ret))) if not ret: @@ -282,7 +282,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): if self.transport.sessionno not in self.factory.interested_events: self.factory.interested_events[self.transport.sessionno] = [] self.factory.interested_events[self.transport.sessionno].extend(args[0]) - except Exception, e: + except Exception: send_error() else: self.sendData((RPC_RESPONSE, request_id, (True))) @@ -303,12 +303,12 @@ class DelugeRPCProtocol(DelugeTransferProtocol): # which session is calling it. self.factory.session_id = self.transport.sessionno ret = self.factory.methods[method](*args, **kwargs) - except Exception, e: + except Exception as ex: send_error() # Don't bother printing out DelugeErrors, because they are just # for the client - if not isinstance(e, DelugeError): - log.exception("Exception calling RPC request: %s", e) + if not isinstance(ex, DelugeError): + log.exception("Exception calling RPC request: %s", ex) else: # Check if the return value is a deferred, since we'll need to # wait for it to fire before sending the RPC_RESPONSE @@ -380,9 +380,9 @@ class RPCServer(component.Component): try: reactor.listenSSL(port, self.factory, ServerContextFactory(), interface=hostname) - except Exception, e: + except Exception as ex: log.info("Daemon already running or port not available..") - log.error(e) + log.error(ex) sys.exit(0) def register_object(self, obj, name=None): diff --git a/deluge/core/torrent.py b/deluge/core/torrent.py index 880df0140..10952b7f7 100644 --- a/deluge/core/torrent.py +++ b/deluge/core/torrent.py @@ -1024,7 +1024,7 @@ class Torrent(object): else: try: self.handle.pause() - except RuntimeError, ex: + except RuntimeError as ex: log.debug("Unable to pause torrent: %s", ex) return False return True @@ -1052,7 +1052,7 @@ class Torrent(object): try: self.handle.resume() - except RuntimeError, ex: + except RuntimeError as ex: log.debug("Unable to resume torrent: %s", ex) def connect_peer(self, peer_ip, peer_port): @@ -1067,7 +1067,7 @@ class Torrent(object): """ try: self.handle.connect_peer((peer_ip, int(peer_port)), 0) - except RuntimeError, ex: + except RuntimeError as ex: log.debug("Unable to connect to peer: %s", ex) return False return True @@ -1087,7 +1087,7 @@ class Torrent(object): if not os.path.exists(dest): try: os.makedirs(dest) - except IOError, ex: + except IOError as ex: log.error("Could not move storage for torrent %s since %s does " "not exist and could not create the directory: %s", self.torrent_id, dest, ex) @@ -1099,7 +1099,7 @@ class Torrent(object): self.handle.move_storage(dest) except TypeError: self.handle.move_storage(utf8_encoded(dest)) - except RuntimeError, ex: + except RuntimeError as ex: log.error("Error calling libtorrent move_storage: %s", ex) return False self.moving_storage = True @@ -1160,14 +1160,14 @@ class Torrent(object): log.debug("Deleting torrent file: %s", path) try: os.remove(path) - except OSError, ex: + except OSError as ex: log.warning("Unable to delete the torrent file: %s", ex) def force_reannounce(self): """Force a tracker reannounce""" try: self.handle.force_reannounce() - except RuntimeError, ex: + except RuntimeError as ex: log.debug("Unable to force reannounce: %s", ex) return False return True @@ -1180,7 +1180,7 @@ class Torrent(object): """ try: self.handle.scrape_tracker() - except RuntimeError, ex: + except RuntimeError as ex: log.debug("Unable to scrape tracker: %s", ex) return False return True @@ -1191,7 +1191,7 @@ class Torrent(object): try: self.handle.force_recheck() self.handle.resume() - except RuntimeError, ex: + except RuntimeError as ex: log.debug("Unable to force recheck: %s", ex) return False self.forcing_recheck = True @@ -1284,14 +1284,11 @@ class Torrent(object): try: os.removedirs(os.path.join(root, name)) log.debug("Removed Empty Folder %s", os.path.join(root, name)) - except OSError as (errno, strerror): - from errno import ENOTEMPTY - if errno == ENOTEMPTY: - # Error raised if folder is not empty - log.debug("%s", strerror) + except OSError as ex: + log.debug(ex) - except OSError as (errno, strerror): - log.debug("Cannot Remove Folder: %s (ErrNo %s)", strerror, errno) + except OSError as ex: + log.debug("Cannot Remove Folder: %s", ex) def cleanup_prev_status(self): """Checks the validity of the keys in the prev_status dict. diff --git a/deluge/pluginmanagerbase.py b/deluge/pluginmanagerbase.py index 3e6a272ae..faea71d0a 100644 --- a/deluge/pluginmanagerbase.py +++ b/deluge/pluginmanagerbase.py @@ -153,10 +153,9 @@ class PluginManagerBase: try: cls = entry_point.load() instance = cls(plugin_name.replace("-", "_")) - except Exception, e: - log.error("Unable to instantiate plugin %r from %r!", - name, egg.location) - log.exception(e) + except Exception as ex: + log.error("Unable to instantiate plugin %r from %r!", name, egg.location) + log.exception(ex) continue instance.enable() if not instance.__module__.startswith("deluge.plugins."): diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py index 2849f66f8..f9568e6f1 100644 --- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py +++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py @@ -157,8 +157,8 @@ class Core(CorePluginBase): if not filedump: raise RuntimeError("Torrent is 0 bytes!") _file.close() - except IOError, e: - log.warning("Unable to open %s: %s", filename, e) + except IOError as ex: + log.warning("Unable to open %s: %s", filename, ex) raise e # Get the info to see if any exceptions are raised @@ -171,8 +171,8 @@ class Core(CorePluginBase): log.debug("Attempting to open %s for splitting magnets.", filename) try: _file = open(filename, "r") - except IOError, e: - log.warning("Unable to open %s: %s", filename, e) + except IOError as ex: + log.warning("Unable to open %s: %s", filename, ex) raise e else: magnets = list(filter(len, _file.readlines())) @@ -191,8 +191,8 @@ class Core(CorePluginBase): n += 1 try: _mfile = open(mname, "w") - except IOError, e: - log.warning("Unable to open %s: %s", mname, e) + except IOError as ex: + log.warning("Unable to open %s: %s", mname, ex) else: _mfile.write(magnet) _mfile.close() @@ -231,9 +231,8 @@ class Core(CorePluginBase): for filename in os.listdir(watchdir["abspath"]): try: filepath = os.path.join(watchdir["abspath"], filename) - except UnicodeDecodeError, e: - log.error("Unable to auto add torrent due to improper " - "filename encoding: %s", e) + except UnicodeDecodeError as ex: + log.error("Unable to auto add torrent due to improper filename encoding: %s", ex) continue if os.path.isdir(filepath): # Skip directories @@ -245,9 +244,8 @@ class Core(CorePluginBase): for filename in os.listdir(watchdir["abspath"]): try: filepath = os.path.join(watchdir["abspath"], filename) - except UnicodeDecodeError, e: - log.error("Unable to auto add torrent due to improper " - "filename encoding: %s", e) + except UnicodeDecodeError as ex: + log.error("Unable to auto add torrent due to improper filename encoding: %s", ex) continue if os.path.isdir(filepath): # Skip directories @@ -262,11 +260,11 @@ class Core(CorePluginBase): continue try: filedump = self.load_torrent(filepath, magnet) - except (RuntimeError, Exception), e: + except (RuntimeError, Exception) as ex: # If the torrent is invalid, we keep track of it so that we # can try again on the next pass. This is because some # torrents may not be fully saved during the pass. - log.debug("Torrent is invalid: %s", e) + log.debug("Torrent is invalid: %s", ex) if filename in self.invalid_torrents: self.invalid_torrents[filename] += 1 if self.invalid_torrents[filename] >= MAX_NUM_ATTEMPTS: @@ -460,6 +458,6 @@ class Core(CorePluginBase): log.info("Removed torrent file \"%s\" from \"%s\"", torrent_fname, copy_torrent_path) break - except OSError, e: + except OSError as ex: log.info("Failed to removed torrent file \"%s\" from " - "\"%s\": %s", torrent_fname, copy_torrent_path, e) + "\"%s\": %s", torrent_fname, copy_torrent_path, ex) diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py index 5116b35a6..536d900bd 100644 --- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py +++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py @@ -273,8 +273,8 @@ class OptionsDialog(): client.autoadd.set_options( str(self.watchdir_id), options ).addCallbacks(self.on_added, self.on_error_show) - except IncompatibleOption, err: - dialogs.ErrorDialog(_("Incompatible Option"), str(err), self.dialog).run() + except IncompatibleOption as ex: + dialogs.ErrorDialog(_("Incompatible Option"), str(ex), self.dialog).run() def on_error_show(self, result): d = dialogs.ErrorDialog(_("Error"), result.value.exception_msg, self.dialog) @@ -288,8 +288,8 @@ class OptionsDialog(): try: options = self.generate_opts() client.autoadd.add(options).addCallbacks(self.on_added, self.on_error_show) - except IncompatibleOption, err: - dialogs.ErrorDialog(_("Incompatible Option"), str(err), self.dialog).run() + except IncompatibleOption as ex: + dialogs.ErrorDialog(_("Incompatible Option"), str(ex), self.dialog).run() def on_cancel(self, event=None): self.dialog.destroy() diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py index 77d5e8682..28e7c23bd 100644 --- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py +++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py @@ -184,8 +184,8 @@ class Core(CorePluginBase): saved.add(ip.address) log.debug("Added %s to whitelisted", ip) self.num_whited += 1 - except BadIP, e: - log.error("Bad IP: %s", e) + except BadIP as ex: + log.error("Bad IP: %s", ex) continue if removed: needs_blocklist_import = True @@ -194,8 +194,8 @@ class Core(CorePluginBase): ip = IP.parse(ip) saved.remove(ip.address) log.debug("Removed %s from whitelisted", ip) - except BadIP, e: - log.error("Bad IP: %s", e) + except BadIP as ex: + log.error("Bad IP: %s", ex) continue self.config[key] = list(saved) diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py index 37e887f40..27668cd63 100644 --- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py +++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py @@ -28,7 +28,7 @@ class GtkUI(GtkPluginBase): try: self.load_preferences_page() - except Exception, err: + except Exception as err: log.exception(err) raise @@ -198,7 +198,7 @@ class GtkUI(GtkPluginBase): try: ip = common.IP.parse(new_text) model.set(model.get_iter_from_string(path_string), 0, ip.address) - except common.BadIP, e: + except common.BadIP as e: model.remove(model.get_iter_from_string(path_string)) from deluge.ui.gtkui import dialogs d = dialogs.ErrorDialog(_("Bad IP address"), e.message) diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py index 478825d05..bea3814a9 100644 --- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py +++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py @@ -37,8 +37,8 @@ class BaseReader(object): for start, end in self.readranges(): try: callback(IP.parse(start), IP.parse(end)) - except BadIP, e: - log.error("Failed to parse IP: %s", e) + except BadIP as ex: + log.error("Failed to parse IP: %s", ex) return self.file def is_ignored(self, line): diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/core.py b/deluge/plugins/Extractor/deluge/plugins/extractor/core.py index c73cc6724..f10cdbb25 100644 --- a/deluge/plugins/Extractor/deluge/plugins/extractor/core.py +++ b/deluge/plugins/Extractor/deluge/plugins/extractor/core.py @@ -126,8 +126,8 @@ class Core(CorePluginBase): if not os.path.exists(dest): try: os.makedirs(dest) - except Exception, e: - log.error("Error creating destination folder: %s", e) + except OSError as ex: + log.error("Error creating destination folder: %s", ex) return def on_extract_success(result, torrent_id, fpath): diff --git a/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py b/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py index bf69e289b..8ca437ada 100644 --- a/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py +++ b/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py @@ -77,8 +77,8 @@ class GtkUI(GtkPluginBase): component.get("TorrentView").remove_column(_("Label")) log.debug(1.1) - except Exception, e: - log.debug(e) + except Exception as ex: + log.debug(ex) def load_interface(self): #sidebar diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/core.py b/deluge/plugins/Notifications/deluge/plugins/notifications/core.py index 19a1d1dc2..b7f45306f 100644 --- a/deluge/plugins/Notifications/deluge/plugins/notifications/core.py +++ b/deluge/plugins/Notifications/deluge/plugins/notifications/core.py @@ -141,11 +141,11 @@ Date: %(date)s # Python 2.5 server = smtplib.SMTP(self.config["smtp_host"], self.config["smtp_port"]) - except Exception, err: + except Exception as ex: err_msg = _("There was an error sending the notification email:" - " %s") % err + " %s") % ex log.error(err_msg) - return err + return ex security_enabled = self.config['smtp_tls'] @@ -160,25 +160,25 @@ Date: %(date)s if self.config['smtp_user'] and self.config['smtp_pass']: try: server.login(self.config['smtp_user'], self.config['smtp_pass']) - except smtplib.SMTPHeloError, err: + except smtplib.SMTPHeloError as ex: err_msg = _("The server didn't reply properly to the helo " - "greeting: %s") % err + "greeting: %s") % ex log.error(err_msg) - return err - except smtplib.SMTPAuthenticationError, err: + return ex + except smtplib.SMTPAuthenticationError as ex: err_msg = _("The server didn't accept the username/password " - "combination: %s") % err + "combination: %s") % ex log.error(err_msg) - return err + return ex try: try: server.sendmail(self.config['smtp_from'], to_addrs, message) - except smtplib.SMTPException, err: + except smtplib.SMTPException as ex: err_msg = _("There was an error sending the notification email:" - " %s") % err + " %s") % ex log.error(err_msg) - return err + return ex finally: if security_enabled: # avoid false failure detection when the server closes diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py b/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py index 44558fda4..5ad16d202 100644 --- a/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py +++ b/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py @@ -213,8 +213,8 @@ class GtkUiNotifications(CustomNotifications): alert_sound = pygame.mixer.music alert_sound.load(sound_path) alert_sound.play() - except pygame.error, message: - err_msg = _("Sound notification failed %s") % (message) + except pygame.error as ex: + err_msg = _("Sound notification failed %s") % ex log.warning(err_msg) return defer.fail(err_msg) else: diff --git a/deluge/plugins/Stats/deluge/plugins/stats/core.py b/deluge/plugins/Stats/deluge/plugins/stats/core.py index a0cbf8d17..33653472e 100644 --- a/deluge/plugins/Stats/deluge/plugins/stats/core.py +++ b/deluge/plugins/Stats/deluge/plugins/stats/core.py @@ -185,8 +185,8 @@ class Core(CorePluginBase): update_interval(30, 5, 6) update_interval(300, 30, 10) - except Exception, e: - log.error("Stats update error %s" % e) + except Exception as ex: + log.error("Stats update error %s" % ex) return True def save_stats(self): @@ -194,8 +194,8 @@ class Core(CorePluginBase): self.saved_stats["stats"] = self.stats self.saved_stats.config.update(self.get_totals()) self.saved_stats.save() - except Exception, e: - log.error("Stats save error", e) + except Exception as ex: + log.error("Stats save error", ex) return True # export: diff --git a/deluge/plugins/init.py b/deluge/plugins/init.py index b8081b313..6c2951689 100644 --- a/deluge/plugins/init.py +++ b/deluge/plugins/init.py @@ -48,13 +48,13 @@ class PluginInitBase(object): def enable(self): try: self.plugin.enable() - except Exception, e: + except Exception as ex: log.error("Unable to enable plugin \"%s\"!", self.plugin._component_name) - log.exception(e) + log.exception(ex) def disable(self): try: self.plugin.disable() - except Exception, e: + except Exception as ex: log.error("Unable to disable plugin \"%s\"!", self.plugin._component_name) - log.exception(e) + log.exception(ex) diff --git a/deluge/tests/test_client.py b/deluge/tests/test_client.py index 806206021..6e94f0259 100644 --- a/deluge/tests/test_client.py +++ b/deluge/tests/test_client.py @@ -71,8 +71,8 @@ class ClientTestCase(unittest.TestCase): while tries > 0: try: self.core = common.start_core(listen_port=self.listen_port) - except CannotListenError, e: - error = e + except CannotListenError as ex: + error = ex self.listen_port += 1 tries -= 1 else: diff --git a/deluge/tests/test_core.py b/deluge/tests/test_core.py index 94dd68386..0ef85c60b 100644 --- a/deluge/tests/test_core.py +++ b/deluge/tests/test_core.py @@ -79,8 +79,8 @@ class CoreTestCase(unittest.TestCase): while tries > 0: try: self.webserver = reactor.listenTCP(self.listen_port, self.website) - except CannotListenError, e: - error = e + except CannotListenError as ex: + error = ex self.listen_port += 1 tries -= 1 else: diff --git a/deluge/tests/test_httpdownloader.py b/deluge/tests/test_httpdownloader.py index 8dd106ac5..b67e7ab9f 100644 --- a/deluge/tests/test_httpdownloader.py +++ b/deluge/tests/test_httpdownloader.py @@ -96,8 +96,8 @@ class DownloadFileTestCase(unittest.TestCase): while tries > 0: try: self.webserver = reactor.listenTCP(self.listen_port, self.website) - except CannotListenError, e: - error = e + except CannotListenError as ex: + error = ex self.listen_port += 1 tries -= 1 else: @@ -113,8 +113,8 @@ class DownloadFileTestCase(unittest.TestCase): f = open(filename) try: self.assertEqual(f.read(), contents) - except Exception, e: - self.fail(e) + except Exception as ex: + self.fail(ex) finally: f.close() return filename @@ -123,8 +123,8 @@ class DownloadFileTestCase(unittest.TestCase): f = open(filename) try: self.failIfEqual(f.read(), contents) - except Exception, e: - self.fail(e) + except Exception as ex: + self.fail(ex) finally: f.close() return filename diff --git a/deluge/tests/test_transfer.py b/deluge/tests/test_transfer.py index ab0298a15..1b9ee2577 100644 --- a/deluge/tests/test_transfer.py +++ b/deluge/tests/test_transfer.py @@ -111,12 +111,12 @@ class TransferTestClass(DelugeTransferProtocol): print " - Buffer length: %d, data length: %d, unused length: %d" % \ (len(data), len(data) - len(dobj.unused_data), len(dobj.unused_data)) print "Packet count:", self.packet_count - except Exception, e: + except Exception as ex: #log.debug("Received possible invalid message (%r): %s", data, e) # This could be cut-off data, so we'll save this in the buffer # and try to prepend it on the next dataReceived() self._buffer = data - print "Failed to load buffer (size %d): %s" % (len(self._buffer), str(e)) + print "Failed to load buffer (size %d): %s" % (len(self._buffer), str(ex)) return else: data = dobj.unused_data diff --git a/deluge/transfer.py b/deluge/transfer.py index 836b0cee2..bf5ec0ad4 100644 --- a/deluge/transfer.py +++ b/deluge/transfer.py @@ -127,8 +127,8 @@ class DelugeTransferProtocol(Protocol): raise Exception("Message length is negative: %d" % self._message_length) # Remove the header from the buffer self._buffer = self._buffer[MESSAGE_HEADER_SIZE:] - except Exception, e: - log.warn("Error occurred when parsing message header: %s." % str(e)) + except Exception as ex: + log.warn("Error occurred when parsing message header: %s.", ex) log.warn("This version of Deluge cannot communicate with the sender of this data.") self._message_length = 0 self._buffer = "" @@ -142,9 +142,8 @@ class DelugeTransferProtocol(Protocol): """ try: self.message_received(rencode.loads(zlib.decompress(data), decode_utf8=True)) - except Exception, e: - log.warn("Failed to decompress (%d bytes) and load serialized data "\ - "with rencode: %s" % (len(data), str(e))) + except Exception as ex: + log.warn("Failed to decompress (%d bytes) and load serialized data with rencode: %s", len(data), ex) def get_bytes_recv(self): """ diff --git a/deluge/ui/client.py b/deluge/ui/client.py index 12354218a..f858b4b96 100644 --- a/deluge/ui/client.py +++ b/deluge/ui/client.py @@ -155,7 +155,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): try: exception_cls = getattr(error, request[2]) exception = exception_cls(*request[3], **request[4]) - except TypeError, err: + except TypeError as err: log.warn("Received invalid RPC_ERROR (Old daemon?): %s", request[2]) return @@ -207,8 +207,8 @@ class DelugeRPCProtocol(DelugeTransferProtocol): #log.debug("Sending RPCRequest %s: %s", request.request_id, request) # Send the request in a tuple because multiple requests can be sent at once self.transfer_message((request.format_message(),)) - except Exception, e: - log.warn("Error occurred when sending message:" + str(e)) + except Exception as ex: + log.warn("Error occurred when sending message: %s", ex) class DelugeRPCClientFactory(ClientFactory): protocol = DelugeRPCProtocol @@ -478,9 +478,9 @@ class DaemonClassicProxy(DaemonProxy): try: m = self.__daemon.rpcserver.get_object_method(method) - except Exception, e: - log.exception(e) - return defer.fail(e) + except Exception as ex: + log.exception(ex) + return defer.fail(ex) else: return defer.maybeDeferred( m, *copy.deepcopy(args), **copy.deepcopy(kwargs) @@ -642,17 +642,17 @@ class Client(object): config = config.encode(sys.getfilesystemencoding()) try: subprocess.Popen(["deluged", "--port=%s" % port, "--config=%s" % config]) - except OSError, e: + except OSError as ex: from errno import ENOENT - if e.errno == ENOENT: + if ex.errno == ENOENT: log.error(_("Deluge cannot find the 'deluged' executable, it is likely \ that you forgot to install the deluged package or it's not in your PATH.")) else: - log.exception(e) + log.exception(ex) raise e - except Exception, e: + except Exception as ex: log.error("Unable to start daemon!") - log.exception(e) + log.exception(ex) return False else: return True diff --git a/deluge/ui/common.py b/deluge/ui/common.py index ed65e988a..6722550b7 100644 --- a/deluge/ui/common.py +++ b/deluge/ui/common.py @@ -90,9 +90,9 @@ class TorrentInfo(object): log.debug("Attempting to open %s.", filename) self.__m_filedata = open(filename, "rb").read() self.__m_metadata = bencode.bdecode(self.__m_filedata) - except Exception, e: - log.warning("Unable to open %s: %s", filename, e) - raise e + except Exception as ex: + log.warning("Unable to open %s: %s", filename, ex) + raise ex self.__m_info_hash = sha(bencode.bencode(self.__m_metadata["info"])).hexdigest() @@ -439,12 +439,8 @@ def get_localhost_auth(): if line.startswith("#"): # This is a comment line continue - line = line.strip() - try: - lsplit = line.split(":") - except Exception, e: - log.error("Your auth file is malformed: %s", e) - continue + + lsplit = line.strip().split(":") if len(lsplit) == 2: username, password = lsplit diff --git a/deluge/ui/console/commander.py b/deluge/ui/console/commander.py index 9e1a66873..c08afa59a 100644 --- a/deluge/ui/console/commander.py +++ b/deluge/ui/console/commander.py @@ -94,16 +94,16 @@ class Commander: try: options, args = parser.parse_args(args) - except Exception, e: - self.write("{!error!}Error parsing options: %s" % e) + except TypeError as ex: + self.write("{!error!}Error parsing options: %s" % ex) return if not getattr(options, '_exit', False): try: ret = self._commands[cmd].handle(*args, **options.__dict__) - except Exception, e: - self.write("{!error!}" + str(e)) - log.exception(e) + except Exception as ex: + self.write("{!error!} %s" % ex) + log.exception(ex) import traceback self.write("%s" % traceback.format_exc()) return defer.succeed(True) diff --git a/deluge/ui/console/commands/help.py b/deluge/ui/console/commands/help.py index 15f69364c..de8cc63b7 100644 --- a/deluge/ui/console/commands/help.py +++ b/deluge/ui/console/commands/help.py @@ -58,7 +58,7 @@ class Command(BaseCommand): try: parser = cmd.create_parser() self.console.write(parser.format_help()) - except AttributeError, e: + except AttributeError: self.console.write(cmd.__doc__ or 'No help for this command') self.console.write(" ") else: diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py index ca71ac5e3..17ef59510 100644 --- a/deluge/ui/console/main.py +++ b/deluge/ui/console/main.py @@ -285,7 +285,7 @@ def load_commands(command_dir, exclude=[]): for a in aliases: commands.append((a, cmd)) return dict(commands) - except OSError, e: + except OSError: return {} diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py index 885f0b36d..db2d72270 100644 --- a/deluge/ui/console/modes/basemode.py +++ b/deluge/ui/console/modes/basemode.py @@ -105,7 +105,7 @@ class BaseMode(CursesStdIO): self.rows, self.cols = self.stdscr.getmaxyx() try: signal.signal(signal.SIGWINCH, self.on_resize) - except Exception, e: + except Exception: log.debug("Unable to catch SIGWINCH signal!") if not encoding: @@ -168,8 +168,8 @@ class BaseMode(CursesStdIO): screen = self.stdscr try: parsed = colors.parse_color_string(string, self.encoding) - except colors.BadColorString, e: - log.error("Cannot add bad color string %s: %s", string, e) + except colors.BadColorString as ex: + log.error("Cannot add bad color string %s: %s", string, ex) return for index, (color, s) in enumerate(parsed): @@ -221,8 +221,8 @@ class BaseMode(CursesStdIO): # We wrap this function to catch exceptions and shutdown the mainloop try: self._doRead() - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) reactor.stop() def _doRead(self): diff --git a/deluge/ui/console/modes/legacy.py b/deluge/ui/console/modes/legacy.py index d9c99f0b9..fadaf7f21 100644 --- a/deluge/ui/console/modes/legacy.py +++ b/deluge/ui/console/modes/legacy.py @@ -590,8 +590,8 @@ class Legacy(BaseMode, component.Component): col = 0 try: parsed = colors.parse_color_string(string, self.encoding) - except colors.BadColorString, e: - log.error("Cannot add bad color string %s: %s", string, e) + except colors.BadColorString as ex: + log.error("Cannot add bad color string %s: %s", string, ex) return for index, (color, s) in enumerate(parsed): @@ -624,8 +624,8 @@ class Legacy(BaseMode, component.Component): try: args = self.console._commands[cmd].split(line) - except ValueError, e: - self.write("{!error!}Error parsing command: %s" % e) + except ValueError as ex: + self.write("{!error!}Error parsing command: %s" % ex) return # Do a little hack here to print 'command --help' properly @@ -647,16 +647,16 @@ class Legacy(BaseMode, component.Component): try: options, args = parser.parse_args(args) - except Exception, e: - self.write("{!error!}Error parsing options: %s" % e) + except TypeError as ex: + self.write("{!error!}Error parsing options: %s" % ex) return if not getattr(options, '_exit', False): try: ret = self.console._commands[cmd].handle(*args, **options.__dict__) - except Exception, e: - self.write("{!error!}" + str(e)) - log.exception(e) + except Exception as ex: + self.write("{!error!} %s" % ex) + log.exception(ex) import traceback self.write("%s" % traceback.format_exc()) return defer.succeed(True) diff --git a/deluge/ui/gtkui/addtorrentdialog.py b/deluge/ui/gtkui/addtorrentdialog.py index 683f90658..d9fb09a6d 100644 --- a/deluge/ui/gtkui/addtorrentdialog.py +++ b/deluge/ui/gtkui/addtorrentdialog.py @@ -213,9 +213,9 @@ class AddTorrentDialog(component.Component): # Get the torrent data from the torrent file try: info = deluge.ui.common.TorrentInfo(filename) - except Exception, e: - log.debug("Unable to open torrent file: %s", e) - dialogs.ErrorDialog(_("Invalid File"), e, self.dialog).run() + except Exception as ex: + log.debug("Unable to open torrent file: %s", ex) + dialogs.ErrorDialog(_("Invalid File"), ex, self.dialog).run() continue if info.info_hash in self.files: diff --git a/deluge/ui/gtkui/connectionmanager.py b/deluge/ui/gtkui/connectionmanager.py index f60cdfc85..bf38d8cbe 100644 --- a/deluge/ui/gtkui/connectionmanager.py +++ b/deluge/ui/gtkui/connectionmanager.py @@ -473,9 +473,9 @@ class ConnectionManager(component.Component): """ try: return client.start_daemon(port, config) - except OSError, e: + except OSError as ex: from errno import ENOENT - if e.errno == ENOENT: + if ex.errno == ENOENT: dialogs.ErrorDialog( _("Unable to start daemon!"), _("Deluge cannot find the 'deluged' executable, it is " @@ -483,8 +483,8 @@ class ConnectionManager(component.Component): "or it's not in your PATH.")).run() return False else: - raise e - except Exception, e: + raise ex + except Exception: import traceback import sys tb = sys.exc_info() @@ -613,9 +613,9 @@ class ConnectionManager(component.Component): try: self.add_host(hostname, port_spinbutton.get_value_as_int(), username, password) - except Exception, e: + except Exception as ex: from deluge.ui.gtkui.dialogs import ErrorDialog - ErrorDialog(_("Error Adding Host"), e).run() + ErrorDialog(_("Error Adding Host"), ex).run() username_entry.set_text("") password_entry.set_text("") diff --git a/deluge/ui/gtkui/details_tab.py b/deluge/ui/gtkui/details_tab.py index e051ba0cc..74009c107 100644 --- a/deluge/ui/gtkui/details_tab.py +++ b/deluge/ui/gtkui/details_tab.py @@ -86,7 +86,7 @@ class DetailsTab(Tab): if widget[1] is not None: try: args = [status[key] for key in widget[2]] - except KeyError, ex: + except KeyError as ex: log.debug("Unable to get status value: %s", ex) continue txt = widget[1](*args) diff --git a/deluge/ui/gtkui/filtertreeview.py b/deluge/ui/gtkui/filtertreeview.py index 0b9164318..22b51bbdf 100644 --- a/deluge/ui/gtkui/filtertreeview.py +++ b/deluge/ui/gtkui/filtertreeview.py @@ -244,8 +244,8 @@ class FilterTreeView(component.Component): if pix: try: return gtk.gdk.pixbuf_new_from_file(get_pixmap("%s16.png" % pix)) - except GError, e: - log.warning(e) + except GError as ex: + log.warning(ex) return self.get_transparent_pix(16, 16) def get_transparent_pix(self, width, height): @@ -257,8 +257,8 @@ class FilterTreeView(component.Component): pix = None try: # assume we could get trashed images here.. pix = gtk.gdk.pixbuf_new_from_file_at_size(filename, 16, 16) - except Exception, e: - log.debug(e) + except Exception as ex: + log.debug(ex) if not pix: pix = self.get_transparent_pix(16, 16) @@ -284,8 +284,8 @@ class FilterTreeView(component.Component): self.selected_path = model.get_path(row) - except Exception, e: - log.debug(e) + except Exception as ex: + log.debug(ex) # paths is likely None .. so lets return None return None @@ -296,8 +296,8 @@ class FilterTreeView(component.Component): hide_cat = ["tracker_host"] client.core.get_filter_tree(self.config["sidebar_show_zero"], hide_cat).addCallback(self.cb_update_filter_tree) - except Exception, e: - log.debug(e) + except Exception as ex: + log.debug(ex) ### Callbacks ### def on_button_press_event(self, widget, event): diff --git a/deluge/ui/gtkui/gtkui.py b/deluge/ui/gtkui/gtkui.py index 8199d674c..66dc6d4ce 100644 --- a/deluge/ui/gtkui/gtkui.py +++ b/deluge/ui/gtkui/gtkui.py @@ -181,8 +181,8 @@ class GtkUI(object): reactor.stop() self.gnome_client.connect("die", on_die) log.debug("GNOME session 'die' handler registered!") - except Exception, e: - log.warning("Unable to register a 'die' handler with the GNOME session manager: %s", e) + except Exception as ex: + log.warning("Unable to register a 'die' handler with the GNOME session manager: %s", ex) if deluge.common.windows_check(): from win32api import SetConsoleCtrlHandler @@ -344,8 +344,8 @@ class GtkUI(object): "Continue in Thin Client mode?")).run() self.started_in_classic = False d.addCallback(on_dialog_response) - except ImportError, e: - if "No module named libtorrent" in e.message: + except ImportError as ex: + if "No module named libtorrent" in ex.message: d = dialogs.YesNoDialog( _("Switch to Thin Client Mode?"), _("Only Thin Client mode is available because libtorrent is not installed." @@ -354,11 +354,11 @@ class GtkUI(object): self.started_in_classic = False d.addCallback(on_dialog_response) else: - raise + raise ex else: component.start() return - except Exception, e: + except Exception: import traceback tb = sys.exc_info() ed = dialogs.ErrorDialog( diff --git a/deluge/ui/gtkui/ipcinterface.py b/deluge/ui/gtkui/ipcinterface.py index 9de5f9d55..6d7605b0d 100644 --- a/deluge/ui/gtkui/ipcinterface.py +++ b/deluge/ui/gtkui/ipcinterface.py @@ -59,6 +59,7 @@ import twisted.internet.error log = logging.getLogger(__name__) + class IPCProtocolServer(Protocol): def dataReceived(self, data): config = ConfigManager("gtkui.conf") @@ -67,6 +68,7 @@ class IPCProtocolServer(Protocol): component.get("MainWindow").present() process_args(data) + class IPCProtocolClient(Protocol): def connectionMade(self): self.transport.write(rencode.dumps(self.factory.args)) @@ -76,6 +78,7 @@ class IPCProtocolClient(Protocol): reactor.stop() self.factory.stop = True + class IPCClientFactory(ClientFactory): protocol = IPCProtocolClient @@ -86,6 +89,7 @@ class IPCClientFactory(ClientFactory): log.warning("Connection to running instance failed.") reactor.stop() + class IPCInterface(component.Component): def __init__(self, args): component.Component.__init__(self, "IPCInterface") @@ -134,17 +138,17 @@ class IPCInterface(component.Component): log.debug("Removing lockfile since it's stale.") try: os.remove(lockfile) - except OSError, ex: + except OSError as ex: log.error("Failed to delete IPC lockfile file: %s", ex) try: os.remove(socket) - except OSError, ex: + except OSError as ex: log.error("Failed to delete IPC socket file: %s", ex) try: self.factory = Factory() self.factory.protocol = IPCProtocolServer reactor.listenUNIX(socket, self.factory, wantPID=True) - except twisted.internet.error.CannotListenError, e: + except twisted.internet.error.CannotListenError as ex: log.info("Deluge is already running! Sending arguments to running instance...") self.factory = IPCClientFactory() self.factory.args = args @@ -157,10 +161,10 @@ class IPCInterface(component.Component): sys.exit(0) else: if old_tempfile: - log.error("Deluge restart failed: %s", e) + log.error("Deluge restart failed: %s", ex) sys.exit(1) else: - log.warning('Restarting Deluge... (%s)', e) + log.warning('Restarting Deluge... (%s)', ex) # Create a tempfile to keep track of restart mkstemp('deluge', dir=ipc_dir) os.execv(sys.argv[0], sys.argv) @@ -172,6 +176,7 @@ class IPCInterface(component.Component): import win32api win32api.CloseHandle(self.mutex) + def process_args(args): """Process arguments sent to already running Deluge""" # Make sure args is a list @@ -219,4 +224,5 @@ def process_args(args): component.get("AddTorrentDialog").add_from_files([path]) component.get("AddTorrentDialog").show(config["focus_add_dialog"]) else: - client.core.add_torrent_file(os.path.split(path)[-1], base64.encodestring(open(path, "rb").read()), None) + client.core.add_torrent_file(os.path.split(path)[-1], + base64.encodestring(open(path, "rb").read()), None) diff --git a/deluge/ui/gtkui/notification.py b/deluge/ui/gtkui/notification.py index 3b8071512..b7ab70d10 100644 --- a/deluge/ui/gtkui/notification.py +++ b/deluge/ui/gtkui/notification.py @@ -102,8 +102,8 @@ class Notification: alert_sound = pygame.mixer.music alert_sound.load(self.config["ntf_sound_path"]) alert_sound.play() - except pygame.error, message: - log.warning("pygame failed to play because %s" % (message)) + except pygame.error as ex: + log.warning("pygame failed to play because %s", ex) else: log.info("sound notification played successfully") @@ -128,8 +128,8 @@ class Notification: port = 25 try: mailServer = smtplib.SMTP(self.config["ntf_server"], port) - except Exception, e: - log.error("There was an error sending the notification email: %s", e) + except Exception as ex: + log.error("There was an error sending the notification email: %s", ex) return if self.config["ntf_username"] and self.config["ntf_pass"]: diff --git a/deluge/ui/gtkui/path_chooser.py b/deluge/ui/gtkui/path_chooser.py index 5874a5e82..6c4902e0c 100644 --- a/deluge/ui/gtkui/path_chooser.py +++ b/deluge/ui/gtkui/path_chooser.py @@ -40,14 +40,17 @@ import deluge.component as component log = logging.getLogger(__name__) + def singleton(cls): instances = {} + def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance + @singleton class PathChoosersHandler(component.Component): @@ -58,14 +61,16 @@ class PathChoosersHandler(component.Component): self.paths_list_keys = [] self.config_properties = {} self.started = False - self.config_keys_to_funcs_mapping = {"path_chooser_show_chooser_button_on_localhost": "filechooser_button_visible", - "path_chooser_show_path_entry": "path_entry_visible", - "path_chooser_auto_complete_enabled": "auto_complete_enabled", - "path_chooser_show_folder_name": "show_folder_name_on_button", - "path_chooser_accelerator_string": "accelerator_string", - "path_chooser_show_hidden_files": "show_hidden_files", - "path_chooser_max_popup_rows": "max_popup_rows", - } + self.config_keys_to_funcs_mapping = { + "path_chooser_show_chooser_button_on_localhost": "filechooser_button_visible", + "path_chooser_show_path_entry": "path_entry_visible", + "path_chooser_auto_complete_enabled": "auto_complete_enabled", + "path_chooser_show_folder_name": "show_folder_name_on_button", + "path_chooser_accelerator_string": "accelerator_string", + "path_chooser_show_hidden_files": "show_hidden_files", + "path_chooser_max_popup_rows": "max_popup_rows", + } + def start(self): self.started = True self.update_config_from_core() @@ -108,6 +113,7 @@ class PathChoosersHandler(component.Component): # Since the max rows value can be changed fast with a spinbutton, we # delay saving to core until the values hasn't been changed in 1 second. self.max_rows_value_set = value + def update(value_): # The value hasn't been changed in one second, so save to core if self.max_rows_value_set == value_: @@ -117,7 +123,7 @@ class PathChoosersHandler(component.Component): def on_list_values_changed(self, values, key, caller): # Save to core - config = { key : values } + config = {key: values} client.core.set_config(config) # Set the values on all path choosers with that key for chooser in self.path_choosers: @@ -130,6 +136,7 @@ class PathChoosersHandler(component.Component): keys += self.paths_list_keys return keys + class PathChooser(PathChooserComboBox): def __init__(self, paths_config_key=None): @@ -177,8 +184,8 @@ class PathChooser(PathChooserComboBox): if key in config: try: self.config_key_funcs[key][1](config[key]) - except TypeError, e: - log.warn("TypeError: %s" % str(e)) + except TypeError as ex: + log.warn("TypeError: %s", ex) # Set the saved paths if self.paths_config_key and self.paths_config_key in config: diff --git a/deluge/ui/gtkui/path_combo_chooser.py b/deluge/ui/gtkui/path_combo_chooser.py index c45963413..7dded1db5 100755 --- a/deluge/ui/gtkui/path_combo_chooser.py +++ b/deluge/ui/gtkui/path_combo_chooser.py @@ -1157,8 +1157,8 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): # Verify that the accelerator can be parsed keyval, mask = gtk.accelerator_parse(self.auto_completer.accelerator_string) self.auto_completer.accelerator_string = accelerator - except TypeError, e: - raise TypeError("TypeError when setting accelerator string: %s" % str(e)) + except TypeError as ex: + raise TypeError("TypeError when setting accelerator string: %s" % ex) def get_auto_complete_enabled(self): return self.auto_completer.auto_complete_enabled diff --git a/deluge/ui/gtkui/peers_tab.py b/deluge/ui/gtkui/peers_tab.py index b4ad5cc45..1a2803115 100644 --- a/deluge/ui/gtkui/peers_tab.py +++ b/deluge/ui/gtkui/peers_tab.py @@ -48,11 +48,13 @@ from deluge.ui.gtkui.common import save_pickled_state_file, load_pickled_state_f log = logging.getLogger(__name__) + def cell_data_progress(column, cell, model, row, data): value = model.get_value(row, data) cell.set_property("value", value * 100) cell.set_property("text", "%.2f%%" % (value * 100)) + class PeersTab(Tab): def __init__(self): Tab.__init__(self) @@ -190,7 +192,7 @@ class PeersTab(Tab): def load_state(self): state = load_pickled_state_file("peers_tab.state") - if state == None: + if state is None: return if len(state["columns"]) != len(self.listview.get_columns()): @@ -246,9 +248,9 @@ class PeersTab(Tab): self.cached_flag_pixbufs[country] = gtk.gdk.pixbuf_new_from_file( deluge.common.resource_filename( "deluge", - os.path.join("ui", "data", "pixmaps", "flags", country.lower() + ".png"))) - except Exception, e: - log.debug("Unable to load flag: %s", e) + os.path.join("ui", "data", "pixmaps", "flags", country.lower() + ".png"))) + except Exception as ex: + log.debug("Unable to load flag: %s", ex) return None return self.cached_flag_pixbufs[country] @@ -289,7 +291,7 @@ class PeersTab(Tab): if peer["ip"].count(":") == 1: # This is an IPv4 address ip_int = sum([int(byte) << shift - for byte, shift in izip(peer["ip"].split(":")[0].split("."), (24, 16, 8, 0))]) + for byte, shift in izip(peer["ip"].split(":")[0].split("."), (24, 16, 8, 0))]) peer_ip = peer["ip"] else: # This is an IPv6 address diff --git a/deluge/ui/gtkui/queuedtorrents.py b/deluge/ui/gtkui/queuedtorrents.py index 57ef22b42..8d26cce2c 100644 --- a/deluge/ui/gtkui/queuedtorrents.py +++ b/deluge/ui/gtkui/queuedtorrents.py @@ -33,7 +33,6 @@ # # -import base64 import os.path import gtk @@ -41,7 +40,6 @@ import logging import gobject import deluge.component as component -from deluge.ui.client import client from deluge.ui.gtkui.ipcinterface import process_args import deluge.common from deluge.configmanager import ConfigManager @@ -49,6 +47,7 @@ import common log = logging.getLogger(__name__) + class QueuedTorrents(component.Component): def __init__(self): component.Component.__init__(self, "QueuedTorrents", depend=["StatusBar", "AddTorrentDialog"]) @@ -120,14 +119,14 @@ class QueuedTorrents(component.Component): """Attempts to update status bar""" # If there are no queued torrents.. remove statusbar widgets and return if len(self.queue) == 0: - if self.status_item != None: + if self.status_item is not None: component.get("StatusBar").remove_item(self.status_item) self.status_item = None return False try: - statusbar = component.get("StatusBar") - except Exception, e: + component.get("StatusBar") + except Exception: # The statusbar hasn't been loaded yet, so we'll add a timer to # update it later. gobject.timeout_add(100, self.update_status_bar) @@ -141,7 +140,7 @@ class QueuedTorrents(component.Component): # Add the statusbar items if needed, or just modify the label if they # have already been added. - if self.status_item == None: + if self.status_item is None: self.status_item = component.get("StatusBar").add_item( stock=gtk.STOCK_SORT_DESCENDING, text=label, @@ -158,7 +157,7 @@ class QueuedTorrents(component.Component): def on_button_remove_clicked(self, widget): selected = self.treeview.get_selection().get_selected()[1] - if selected != None: + if selected is not None: path = self.liststore.get_value(selected, 1) self.liststore.remove(selected) self.queue.remove(path) diff --git a/deluge/ui/gtkui/status_tab.py b/deluge/ui/gtkui/status_tab.py index 58776050c..bc69393ae 100644 --- a/deluge/ui/gtkui/status_tab.py +++ b/deluge/ui/gtkui/status_tab.py @@ -154,7 +154,7 @@ class StatusTab(Tab): if widget[1] is not None: try: args = [status[key] for key in widget[2]] - except KeyError, ex: + except KeyError as ex: log.debug("Unable to get status value: %s", ex) continue txt = widget[1](*args) diff --git a/deluge/ui/gtkui/statusbar.py b/deluge/ui/gtkui/statusbar.py index cdd1a596e..59a1020f8 100644 --- a/deluge/ui/gtkui/statusbar.py +++ b/deluge/ui/gtkui/statusbar.py @@ -221,8 +221,8 @@ class StatusBar(component.Component): self.remove_item(self.health_item) self.remove_item(self.traffic_item) self.remove_item(self.diskspace_item) - except Exception, e: - log.debug("Unable to remove StatusBar item: %s", e) + except Exception as ex: + log.debug("Unable to remove StatusBar item: %s", ex) self.show_not_connected() def visible(self, visible): @@ -249,8 +249,8 @@ class StatusBar(component.Component): if item.get_eventbox() in self.hbox.get_children(): try: self.hbox.remove(item.get_eventbox()) - except Exception, e: - log.debug("Unable to remove widget: %s", e) + except Exception as ex: + log.debug("Unable to remove widget: %s", ex) def add_timeout_item(self, seconds=3, image=None, stock=None, text=None, callback=None): """Adds an item to the StatusBar for seconds""" diff --git a/deluge/ui/gtkui/systemtray.py b/deluge/ui/gtkui/systemtray.py index e98740a02..cad5507a5 100644 --- a/deluge/ui/gtkui/systemtray.py +++ b/deluge/ui/gtkui/systemtray.py @@ -188,8 +188,8 @@ class SystemTray(component.Component): # Hide widgets in hide list because we're not connected to a host for widget in self.hide_widget_list: self.builder.get_object(widget).hide() - except Exception, e: - log.debug("Unable to hide system tray menu widgets: %s", e) + except Exception as ex: + log.debug("Unable to hide system tray menu widgets: %s", ex) self.tray.set_tooltip(_("Deluge") + "\n" + _("Not Connected...")) @@ -305,8 +305,8 @@ class SystemTray(component.Component): del self.tray del self.builder del self.tray_menu - except Exception, e: - log.debug("Unable to disable system tray: %s", e) + except Exception as ex: + log.debug("Unable to disable system tray: %s", ex) def blink(self, value): try: diff --git a/deluge/ui/gtkui/torrentdetails.py b/deluge/ui/gtkui/torrentdetails.py index bc97452fe..44e9e3ed0 100644 --- a/deluge/ui/gtkui/torrentdetails.py +++ b/deluge/ui/gtkui/torrentdetails.py @@ -360,8 +360,8 @@ class TorrentDetails(component.Component): name = tab if name: self.tabs[name].clear() - except Exception, e: - log.debug("Unable to clear torrentdetails: %s", e) + except Exception as ex: + log.debug("Unable to clear torrentdetails: %s", ex) def _on_switch_page(self, notebook, page, page_num): self.update(page_num) diff --git a/deluge/ui/gtkui/torrentview.py b/deluge/ui/gtkui/torrentview.py index b5bc0133a..8e9707bad 100644 --- a/deluge/ui/gtkui/torrentview.py +++ b/deluge/ui/gtkui/torrentview.py @@ -562,8 +562,8 @@ class TorrentView(listview.ListView, component.Component): for path in paths: try: row = self.treeview.get_model().get_iter(path) - except Exception, e: - log.debug("Unable to get iter from path: %s", e) + except Exception as ex: + log.debug("Unable to get iter from path: %s", ex) continue child_row = self.treeview.get_model().convert_iter_to_child_iter(None, row) @@ -571,8 +571,8 @@ class TorrentView(listview.ListView, component.Component): if self.liststore.iter_is_valid(child_row): try: value = self.liststore.get_value(child_row, self.columns["torrent_id"].column_indices[0]) - except Exception, e: - log.debug("Unable to get value from row: %s", e) + except Exception as ex: + log.debug("Unable to get value from row: %s", ex) else: torrent_ids.append(value) if len(torrent_ids) == 0: diff --git a/deluge/ui/gtkui/torrentview_data_funcs.py b/deluge/ui/gtkui/torrentview_data_funcs.py index 38dcb2dcb..d1ac62e8d 100644 --- a/deluge/ui/gtkui/torrentview_data_funcs.py +++ b/deluge/ui/gtkui/torrentview_data_funcs.py @@ -79,6 +79,7 @@ func_last_value = {"cell_data_speed_down": None, "cell_data_progress": [None, None], } + def cell_data_statusicon(column, cell, model, row, data): """Display text with an icon""" try: @@ -101,18 +102,20 @@ def cell_data_statusicon(column, cell, model, row, data): except KeyError: pass + def create_blank_pixbuf(): i = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, 16, 16) i.fill(0x00000000) return i + def set_icon(icon, cell): if icon: pixbuf = icon.get_cached_icon() if pixbuf is None: try: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(icon.get_filename(), 16, 16) - except gobject.GError, e: + except gobject.GError: # Failed to load the pixbuf (Bad image file), so set a blank pixbuf pixbuf = create_blank_pixbuf() finally: @@ -125,6 +128,7 @@ def set_icon(icon, cell): warnings.simplefilter("ignore") cell.set_property("pixbuf", pixbuf) + def cell_data_trackericon(column, cell, model, row, data): host = model[row][data] @@ -144,6 +148,7 @@ def cell_data_trackericon(column, cell, model, row, data): set_icon(None, cell) func_last_value["cell_data_trackericon"] = None + def cell_data_progress(column, cell, model, row, data): """Display progress bar with text""" (value, state_str) = model.get(row, *data) @@ -160,6 +165,7 @@ def cell_data_progress(column, cell, model, row, data): func_last_value["cell_data_progress"][1] = textstr cell.set_property("text", textstr) + def cell_data_queue(column, cell, model, row, data): value = model.get_value(row, data) @@ -172,11 +178,12 @@ def cell_data_queue(column, cell, model, row, data): else: cell.set_property("text", str(value + 1)) + def cell_data_speed(cell, model, row, data, cache_key): """Display value as a speed, eg. 2 KiB/s""" try: speed = model.get_value(row, data) - except AttributeError, e: + except AttributeError: print "AttributeError" import traceback traceback.print_exc() @@ -189,14 +196,17 @@ def cell_data_speed(cell, model, row, data, cache_key): speed_str = common.fspeed(speed) cell.set_property('text', speed_str) + def cell_data_speed_down(column, cell, model, row, data): """Display value as a speed, eg. 2 KiB/s""" cell_data_speed(cell, model, row, data, "cell_data_speed_down") + def cell_data_speed_up(column, cell, model, row, data): """Display value as a speed, eg. 2 KiB/s""" cell_data_speed(cell, model, row, data, "cell_data_speed_up") + def cell_data_speed_limit(cell, model, row, data, cache_key): """Display value as a speed, eg. 2 KiB/s""" speed = model.get_value(row, data) @@ -210,17 +220,21 @@ def cell_data_speed_limit(cell, model, row, data, cache_key): speed_str = common.fspeed(speed * 1024) cell.set_property('text', speed_str) + def cell_data_speed_limit_down(column, cell, model, row, data): cell_data_speed_limit(cell, model, row, data, "cell_data_speed_limit_down") + def cell_data_speed_limit_up(column, cell, model, row, data): cell_data_speed_limit(cell, model, row, data, "cell_data_speed_limit_up") + def cell_data_size(column, cell, model, row, data): """Display value in terms of size, eg. 2 MB""" size = model.get_value(row, data) cell.set_property('text', common.fsize(size)) + def cell_data_peer(column, cell, model, row, data): """Display values as 'value1 (value2)'""" (first, second) = model.get(row, *data) @@ -230,6 +244,7 @@ def cell_data_peer(column, cell, model, row, data): else: cell.set_property('text', '%d' % first) + def cell_data_time(column, cell, model, row, data): """Display value as time, eg 1m10s""" time = model.get_value(row, data) @@ -243,6 +258,7 @@ def cell_data_time(column, cell, model, row, data): time_str = common.ftime(time) cell.set_property('text', time_str) + def cell_data_ratio(cell, model, row, data, cache_key): """Display value as a ratio with a precision of 3.""" ratio = model.get_value(row, data) @@ -252,15 +268,19 @@ def cell_data_ratio(cell, model, row, data, cache_key): func_last_value[cache_key] = ratio cell.set_property('text', "∞" if ratio < 0 else "%.3f" % ratio) + def cell_data_ratio_seeds_peers(column, cell, model, row, data): cell_data_ratio(cell, model, row, data, "cell_data_ratio_seeds_peers") + def cell_data_ratio_ratio(column, cell, model, row, data): cell_data_ratio(cell, model, row, data, "cell_data_ratio_ratio") + def cell_data_ratio_avail(column, cell, model, row, data): cell_data_ratio(cell, model, row, data, "cell_data_ratio_avail") + def cell_data_date(column, cell, model, row, data): """Display value as date, eg 05/05/08""" date = model.get_value(row, data) @@ -272,6 +292,7 @@ def cell_data_date(column, cell, model, row, data): date_str = common.fdate(date) if date > 0.0 else "" cell.set_property('text', date_str) + def cell_data_date_or_never(column, cell, model, row, data): """Display value as date, eg 05/05/08 or Never""" value = model.get_value(row, data) @@ -282,4 +303,3 @@ def cell_data_date_or_never(column, cell, model, row, data): date_str = common.fdate(value) if value > 0.0 else _("Never") cell.set_property('text', date_str) - diff --git a/deluge/ui/gtkui/trackers_tab.py b/deluge/ui/gtkui/trackers_tab.py index b92cb1f7d..9e3783a74 100644 --- a/deluge/ui/gtkui/trackers_tab.py +++ b/deluge/ui/gtkui/trackers_tab.py @@ -76,7 +76,7 @@ class TrackersTab(Tab): else: try: args = [status[key] for key in widget[2]] - except KeyError, ex: + except KeyError as ex: log.debug("Unable to get status value: %s", ex) continue txt = widget[1](*args) diff --git a/deluge/ui/tracker_icons.py b/deluge/ui/tracker_icons.py index adb8db315..9bc310020 100644 --- a/deluge/ui/tracker_icons.py +++ b/deluge/ui/tracker_icons.py @@ -317,8 +317,8 @@ class TrackerIcons(Component): f.close() try: os.remove(page) - except Exception, e: - log.warning("Couldn't remove temp file: %s", e) + except OSError as ex: + log.warning("Couldn't remove temp file: %s", ex) return parser.get_icons() @@ -388,8 +388,8 @@ class TrackerIcons(Component): if PIL_INSTALLED: try: Image.open(icon_name) - except IOError, e: - raise InvalidIconError(e) + except IOError as ex: + raise InvalidIconError(ex) else: if os.stat(icon_name).st_size == 0L: raise InvalidIconError, "empty icon" diff --git a/deluge/ui/ui.py b/deluge/ui/ui.py index 1cedc3dae..cb45d1720 100644 --- a/deluge/ui/ui.py +++ b/deluge/ui/ui.py @@ -178,7 +178,7 @@ class UI: log.info("Starting ConsoleUI..") from deluge.ui.console.main import ConsoleUI ui = ConsoleUI(ui_args) - except ImportError, e: + except ImportError as ex: import sys import traceback error_type, error_value, tb = sys.exc_info() @@ -188,7 +188,7 @@ class UI: log.error("Unable to find the requested UI: %s. Please select a different UI with the '-u' option \ or alternatively use the '-s' option to select a different default UI.", selected_ui) else: - log.exception(e) + log.exception(ex) log.error("There was an error whilst launching the request UI: %s", selected_ui) log.error("Look at the traceback above for more information.") sys.exit(1) diff --git a/deluge/ui/web/auth.py b/deluge/ui/web/auth.py index c69526dd9..93912411c 100644 --- a/deluge/ui/web/auth.py +++ b/deluge/ui/web/auth.py @@ -59,8 +59,8 @@ def get_session_id(session_id): if checksum == make_checksum(session_id): return session_id return None - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) return None diff --git a/deluge/ui/web/json_api.py b/deluge/ui/web/json_api.py index ce0f55781..4d8472435 100644 --- a/deluge/ui/web/json_api.py +++ b/deluge/ui/web/json_api.py @@ -202,13 +202,13 @@ class JSON(resource.Resource, component.Component): result = self._exec_remote(method, params, request) else: error = {"message": "Unknown method", "code": 2} - except AuthError, e: + except AuthError: error = {"message": "Not authenticated", "code": 1} - except Exception, e: + except Exception as ex: log.error("Error calling method `%s`", method) - log.exception(e) + log.exception(ex) - error = {"message": e.message, "code": 3} + error = {"message": ex.message, "code": 3} return request_id, result, error @@ -271,8 +271,8 @@ class JSON(resource.Resource, component.Component): request.json = request.content.read() self._on_json_request(request) return server.NOT_DONE_YET - except Exception, e: - return self._on_json_request_failed(e, request) + except Exception as ex: + return self._on_json_request_failed(ex, request) def register_object(self, obj, name=None): """ @@ -674,8 +674,8 @@ class WebApi(JSONComponent): try: torrent_info = uicommon.TorrentInfo(filename.strip(), 2) return torrent_info.as_dict("name", "info_hash", "files_tree") - except Exception, e: - log.exception(e) + except Exception as ex: + log.exception(ex) return False @export