diff options
65 files changed, 411 insertions, 398 deletions
diff --git a/deluge/_libtorrent.py b/deluge/_libtorrent.py index 99b0f55c8..2e41b2809 100644 --- a/deluge/_libtorrent.py +++ b/deluge/_libtorrent.py @@ -22,9 +22,9 @@ supports. REQUIRED_VERSION = "1.0.6.0" -def check_version(lt): +def check_version(libtorrent): from deluge.common import VersionSplit - if VersionSplit(lt.version) < VersionSplit(REQUIRED_VERSION): + if VersionSplit(libtorrent.version) < VersionSplit(REQUIRED_VERSION): raise ImportError("This version of Deluge requires libtorrent >=%s!" % REQUIRED_VERSION) try: diff --git a/deluge/common.py b/deluge/common.py index f46c98c3b..2a380efbc 100644 --- a/deluge/common.py +++ b/deluge/common.py @@ -30,7 +30,7 @@ try: import dbus bus = dbus.SessionBus() dbus_fileman = bus.get_object("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1") -except: +except Exception: dbus_fileman = None @@ -527,7 +527,7 @@ def get_magnet_info(uri): return False -def create_magnet_uri(infohash, name=None, trackers=[]): +def create_magnet_uri(infohash, name=None, trackers=None): """ Creates a magnet uri @@ -570,9 +570,9 @@ def get_path_size(path): return os.path.getsize(path) dir_size = 0 - for (p, dirs, files) in os.walk(path): - for file in files: - filename = os.path.join(p, file) + for (p, dummy_dirs, files) in os.walk(path): + for _file in files: + filename = os.path.join(p, _file) dir_size += os.path.getsize(filename) return dir_size @@ -840,9 +840,9 @@ def set_env_variable(name, value): if result == 0: raise Warning except Exception: - log.warning('Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')' % name) + log.warning('Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name) else: - log.debug('Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')' % (name, value)) + log.debug('Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name, value) # Update the copy maintained by msvcrt (used by gtk+ runtime) try: @@ -850,9 +850,9 @@ def set_env_variable(name, value): if result != 0: raise Warning except Exception: - log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')' % name) + log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')', name) else: - log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')' % (name, value)) + log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')', name, value) # Update the copy maintained by whatever c runtime is used by Python try: @@ -862,9 +862,9 @@ def set_env_variable(name, value): if result != 0: raise Warning except Exception: - log.warning('Failed to set Env Var \'%s\' (\'%s._putenv\')' % (name, msvcrtname)) + log.warning('Failed to set Env Var \'%s\' (\'%s._putenv\')', name, msvcrtname) else: - log.debug('Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')' % (name, value, msvcrtname)) + log.debug('Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')', name, value, msvcrtname) def set_language(lang): diff --git a/deluge/component.py b/deluge/component.py index 4ae985ac9..3166a5765 100644 --- a/deluge/component.py +++ b/deluge/component.py @@ -248,7 +248,7 @@ class ComponentRegistry(object): else: return succeed(None) - def start(self, names=[]): + def start(self, names=None): """ Starts Components that are currently in a Stopped state and their dependencies. If *names* is specified, will only start those @@ -284,7 +284,7 @@ class ComponentRegistry(object): return DeferredList(deferreds) - def stop(self, names=[]): + def stop(self, names=None): """ Stops Components that are currently not in a Stopped state. If *names* is specified, then it will only stop those Components, @@ -322,7 +322,7 @@ class ComponentRegistry(object): return DeferredList(deferreds) - def pause(self, names=[]): + def pause(self, names=None): """ Pauses Components that are currently in a Started state. If *names* is specified, then it will only pause those Components, @@ -348,7 +348,7 @@ class ComponentRegistry(object): return DeferredList(deferreds) - def resume(self, names=[]): + def resume(self, names=None): """ Resumes Components that are currently in a Paused state. If *names* is specified, then it will only resume those Components, @@ -386,7 +386,7 @@ class ComponentRegistry(object): """ def on_stopped(result): - return DeferredList(map(lambda c: c._component_shutdown(), self.components.values())) + return DeferredList([comp._component_shutdown() for comp in self.components.values()]) return self.stop(self.components.keys()).addCallback(on_stopped) diff --git a/deluge/config.py b/deluge/config.py index bbf7ad311..abd74a159 100644 --- a/deluge/config.py +++ b/deluge/config.py @@ -198,7 +198,7 @@ what is currently in the config and it could not convert the value global callLater if callLater is None: # Must import here and not at the top or it will throw ReactorAlreadyInstalledError - from twisted.internet.reactor import callLater + from twisted.internet.reactor import callLater # pylint: disable=redefined-outer-name # Run the set_function for this key if any try: for func in self.__set_functions[key]: @@ -210,7 +210,7 @@ what is currently in the config and it could not convert the value for func in self.__change_callbacks: func(key, value) callLater(0, do_change_callbacks, key, value) - except: + except Exception: pass # We set the save_timer for 5 seconds if not already set @@ -295,7 +295,7 @@ what is currently in the config and it could not convert the value global callLater if callLater is None: # Must import here and not at the top or it will throw ReactorAlreadyInstalledError - from twisted.internet.reactor import callLater + from twisted.internet.reactor import callLater # pylint: disable=redefined-outer-name # We set the save_timer for 5 seconds if not already set if not self._save_timer or not self._save_timer.active(): diff --git a/deluge/core/core.py b/deluge/core/core.py index c14af338d..0a97176cf 100644 --- a/deluge/core/core.py +++ b/deluge/core/core.py @@ -103,11 +103,13 @@ class Core(component.Component): else: log.error("Invalid listen interface (must be IP Address): %s", listen_interface) - def start(self): - """Starts the core""" # New release check information self.__new_release = None + def start(self): + """Starts the core""" + pass + def stop(self): log.debug("Core stopping...") @@ -726,8 +728,8 @@ class Core(component.Component): def _create_torrent_thread(self, path, tracker, piece_length, comment, target, webseeds, private, created_by, trackers, add_to_session): - import deluge.metafile - deluge.metafile.make_meta_file( + from deluge import metafile + metafile.make_meta_file( path, tracker, piece_length, diff --git a/deluge/core/filtermanager.py b/deluge/core/filtermanager.py index 8c7cc75fd..84203e86f 100644 --- a/deluge/core/filtermanager.py +++ b/deluge/core/filtermanager.py @@ -234,11 +234,11 @@ class FilterManager(component.Component): init_state["Active"] = len(self.filter_state_active(self.torrents.get_torrent_list())) return init_state - def register_filter(self, id, filter_func, filter_value=None): - self.registered_filters[id] = filter_func + def register_filter(self, filter_id, filter_func, filter_value=None): + self.registered_filters[filter_id] = filter_func - def deregister_filter(self, id): - del self.registered_filters[id] + def deregister_filter(self, filter_id): + del self.registered_filters[filter_id] def register_tree_field(self, field, init_func=lambda: {}): self.tree_fields[field] = init_func diff --git a/deluge/core/pluginmanager.py b/deluge/core/pluginmanager.py index 7b89394fa..509299302 100644 --- a/deluge/core/pluginmanager.py +++ b/deluge/core/pluginmanager.py @@ -86,5 +86,5 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon log.debug("Deregistering status field %s with PluginManager", field) try: del self.status_fields[field] - except: + except Exception: log.warning("Unable to deregister status field %s", field) diff --git a/deluge/core/preferencesmanager.py b/deluge/core/preferencesmanager.py index d4c78443a..f131d3171 100644 --- a/deluge/core/preferencesmanager.py +++ b/deluge/core/preferencesmanager.py @@ -121,11 +121,11 @@ class PreferencesManager(component.Component): log.warning("New proxy config is: %s", self.config["proxy"]) del self.config["proxies"] - def start(self): self.core = component.get("Core") self.session = component.get("Core").session self.new_release_timer = None + def start(self): # Set the initial preferences on start-up for key in DEFAULT_PREFS: self.do_config_set_func(key, self.config[key]) @@ -270,13 +270,13 @@ class PreferencesManager(component.Component): pe_settings.allowed_enc_level = lt.enc_level(pe_enc_level[self.config["enc_level"]]) pe_settings.prefer_rc4 = True self.session.set_pe_settings(pe_settings) - set = self.session.get_pe_settings() + pe_sess_settings = self.session.get_pe_settings() log.debug("encryption settings:\n\t\t\tout_policy: %s\n\t\t\ in_policy: %s\n\t\t\tlevel: %s\n\t\t\tprefer_rc4: %s", - set.out_enc_policy, - set.in_enc_policy, - set.allowed_enc_level, - set.prefer_rc4) + pe_sess_settings.out_enc_policy, + pe_sess_settings.in_enc_policy, + pe_sess_settings.allowed_enc_level, + pe_sess_settings.prefer_rc4) def _on_set_max_connections_global(self, key, value): log.debug("max_connections_global set to %s..", value) @@ -346,8 +346,9 @@ class PreferencesManager(component.Component): self.session_set_setting("dont_count_slow_torrents", value) def _on_set_send_info(self, key, value): - log.debug("Sending anonymous stats..") """sends anonymous stats home""" + log.debug("Sending anonymous stats..") + class SendInfoThread(threading.Thread): def __init__(self, config): self.config = config @@ -358,7 +359,6 @@ class PreferencesManager(component.Component): now = time.time() # check if we've done this within the last week or never if (now - self.config["info_sent"]) >= (60 * 60 * 24 * 7): - import deluge.common from urllib import quote_plus from urllib2 import urlopen import platform diff --git a/deluge/core/rpcserver.py b/deluge/core/rpcserver.py index 5dee9dea6..75f978b7a 100644 --- a/deluge/core/rpcserver.py +++ b/deluge/core/rpcserver.py @@ -194,7 +194,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): """ Sends an error response with the contents of the exception that was raised. """ - exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() + exceptionType, exceptionValue, dummy_exceptionTraceback = sys.exc_info() formated_tb = traceback.format_exc() try: self.sendData(( @@ -205,17 +205,17 @@ class DelugeRPCProtocol(DelugeTransferProtocol): exceptionValue._kwargs, formated_tb )) - except AttributeError as err: + except AttributeError: # 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 " "send(causing exception goes next):\n%s", formated_tb) try: raise WrappedException(str(exceptionValue), exceptionType.__name__, formated_tb) - except: + except Exception: send_error() - except Exception as err: - log.error("An exception occurred while sending RPC_ERROR to client: %s", err) + except Exception as ex: + log.error("An exception occurred while sending RPC_ERROR to client: %s", ex) if method == "daemon.info": # This is a special case and used in the initial connection process @@ -241,8 +241,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): self.sendData((RPC_RESPONSE, request_id, (ret))) if not ret: self.transport.loseConnection() - finally: - return + return elif method == "daemon.set_event_interest" and self.valid_session(): log.debug("RPC dispatch daemon.set_event_interest") # This special case is to allow clients to set which events they are @@ -256,8 +255,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): send_error() else: self.sendData((RPC_RESPONSE, request_id, (True))) - finally: - return + return if method in self.factory.methods and self.valid_session(): log.debug("RPC dispatch %s", method) @@ -454,7 +452,7 @@ class RPCServer(component.Component): :returns: the auth level :rtype: int """ - self.factory.methods[rpc]._rpcserver_auth_level + return self.factory.methods[rpc]._rpcserver_auth_level def is_session_valid(self, session_id): """ diff --git a/deluge/core/torrent.py b/deluge/core/torrent.py index 547ddd77b..4c094334e 100644 --- a/deluge/core/torrent.py +++ b/deluge/core/torrent.py @@ -368,12 +368,12 @@ class Torrent(object): # If we are turning off this option, call set_file_priorities to # reset all the piece priorities self.set_file_priorities(self.options["file_priorities"]) - return + return None, None if not self.has_metadata: - return + return None, None if self.get_status(["storage_mode"])["storage_mode"] == "compact": log.debug("Setting first/last priority with compact allocation does not work!") - return + return None, None # A list of priorities for each piece in the torrent priorities = self.handle.piece_priorities() prioritized_pieces = [] diff --git a/deluge/httpdownloader.py b/deluge/httpdownloader.py index 09c76091a..08a253db5 100644 --- a/deluge/httpdownloader.py +++ b/deluge/httpdownloader.py @@ -42,10 +42,12 @@ class HTTPDownloader(client.HTTPDownloader): """ self.part_callback = part_callback self.current_length = 0 + self.total_length = 0 self.decoder = None self.value = filename self.force_filename = force_filename self.allow_compression = allow_compression + self.code = None agent = "Deluge/%s (http://deluge-torrent.org)" % get_version() client.HTTPDownloader.__init__(self, url, filename, headers=headers, agent=agent) @@ -125,14 +127,14 @@ def sanitise_filename(filename): if os.path.basename(filename) != filename: # Dodgy server, log it - log.warning("Potentially malicious server: trying to write to file '%s'" % filename) + log.warning("Potentially malicious server: trying to write to file '%s'", filename) # Only use the basename filename = os.path.basename(filename) filename = filename.strip() if filename.startswith(".") or ";" in filename or "|" in filename: # Dodgy server, log it - log.warning("Potentially malicious server: trying to write to file '%s'" % filename) + log.warning("Potentially malicious server: trying to write to file '%s'", filename) return filename @@ -178,7 +180,7 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal # In Twisted 13.1.0 _parse() function replaced by _URI class. # In Twisted 15.0.0 _URI class renamed to URI. if hasattr(client, "_parse"): - scheme, host, port, path = client._parse(url) + scheme, host, port, dummy_path = client._parse(url) else: try: from twisted.web.client import _URI as URI @@ -203,7 +205,7 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal """ A custom context factory to add a server name for TLS connections. """ - def getContext(self, hostname=None, port=None): # NOQA + def getContext(self): # NOQA ctx = ssl.ClientContextFactory.getContext(self) ClientTLSOptions(host, ctx) return ctx diff --git a/deluge/log.py b/deluge/log.py index 68d56ba3c..8a2ce2aea 100644 --- a/deluge/log.py +++ b/deluge/log.py @@ -12,6 +12,7 @@ import inspect import logging +import logging.handlers import os from twisted.internet import defer @@ -94,7 +95,6 @@ class Logging(LoggingLoggerClass): return rv levels = { - "none": logging.NOTSET, "info": logging.INFO, "warn": logging.WARNING, "warning": logging.WARNING, @@ -114,7 +114,6 @@ def setup_logger(level="error", filename=None, filemode="w"): :param level: str, the level to log :param filename: str, the file to log to """ - import logging if logging.getLoggerClass() is not Logging: logging.setLoggerClass(Logging) @@ -126,7 +125,6 @@ def setup_logger(level="error", filename=None, filemode="w"): root_logger = logging.getLogger() if filename and filemode == "a": - import logging.handlers handler = logging.handlers.RotatingFileHandler( filename, filemode, maxBytes=50 * 1024 * 1024, # 50 Mb @@ -135,7 +133,6 @@ def setup_logger(level="error", filename=None, filemode="w"): delay=0 ) elif filename and filemode == "w": - import logging.handlers handler = getattr( logging.handlers, "WatchedFileHandler", logging.FileHandler)( filename, filemode, "utf-8", delay=0 diff --git a/deluge/pluginmanagerbase.py b/deluge/pluginmanagerbase.py index fbf9fe36f..6d6fd9425 100644 --- a/deluge/pluginmanagerbase.py +++ b/deluge/pluginmanagerbase.py @@ -168,7 +168,7 @@ class PluginManagerBase: cont_lines = [] # Missing plugin info if not self.pkg_env[name]: - log.warn("Failed to retrive info for plugin '%s'" % name) + log.warn("Failed to retrive info for plugin '%s'", name) for k in info: info[k] = "not available" return info diff --git a/deluge/plugins/pluginbase.py b/deluge/plugins/pluginbase.py index 704768154..9e39ff98d 100644 --- a/deluge/plugins/pluginbase.py +++ b/deluge/plugins/pluginbase.py @@ -29,6 +29,7 @@ class PluginBase(component.Component): class CorePluginBase(PluginBase): + def __init__(self, plugin_name): super(CorePluginBase, self).__init__("CorePlugin." + plugin_name) # Register RPC methods @@ -38,12 +39,25 @@ class CorePluginBase(PluginBase): def __del__(self): component.get("RPCServer").deregister_object(self) + def enable(self): + super(CorePluginBase, self).enable() + + def disable(self): + super(CorePluginBase, self).disable() + class GtkPluginBase(PluginBase): + def __init__(self, plugin_name): super(GtkPluginBase, self).__init__("GtkPlugin." + plugin_name) log.debug("GtkPlugin initialized..") + def enable(self): + super(GtkPluginBase, self).enable() + + def disable(self): + super(GtkPluginBase, self).disable() + class WebPluginBase(PluginBase): diff --git a/deluge/tests/common.py b/deluge/tests/common.py index 3dfb44a8a..25d2d668a 100644 --- a/deluge/tests/common.py +++ b/deluge/tests/common.py @@ -8,13 +8,13 @@ from twisted.internet.error import CannotListenError import deluge.common import deluge.configmanager +import deluge.core.preferencesmanager import deluge.log deluge.log.setup_logger("none") def disable_new_release_check(): - import deluge.core.preferencesmanager deluge.core.preferencesmanager.DEFAULT_PREFS["new_release_check"] = False diff --git a/deluge/tests/test_client.py b/deluge/tests/test_client.py index 9441e0aa1..6ee2ef2ae 100644 --- a/deluge/tests/test_client.py +++ b/deluge/tests/test_client.py @@ -2,6 +2,7 @@ from twisted.internet import defer from twisted.internet.error import CannotListenError import deluge.component as component +import deluge.ui.common from deluge import error from deluge.core.authmanager import AUTH_LEVEL_ADMIN from deluge.ui.client import Client, DaemonSSLProxy, client @@ -72,12 +73,12 @@ class ClientTestCase(BaseTestCase): try: self.core = common.start_core(listen_port=self.listen_port) except CannotListenError as ex: - error = ex + exception_error = ex self.listen_port += 1 else: break else: - raise error + raise exception_error def tear_down(self): self.core.terminate() @@ -97,8 +98,7 @@ class ClientTestCase(BaseTestCase): return d def test_connect_localclient(self): - from deluge.ui import common - username, password = common.get_localhost_auth() + username, password = deluge.ui.common.get_localhost_auth() d = client.connect( "localhost", self.listen_port, username=username, password=password ) @@ -112,8 +112,7 @@ class ClientTestCase(BaseTestCase): return d def test_connect_bad_password(self): - from deluge.ui import common - username, password = common.get_localhost_auth() + username, password = deluge.ui.common.get_localhost_auth() d = client.connect( "localhost", self.listen_port, username=username, password=password + "1" ) @@ -129,8 +128,7 @@ class ClientTestCase(BaseTestCase): return d def test_connect_without_password(self): - from deluge.ui import common - username, password = common.get_localhost_auth() + username, password = deluge.ui.common.get_localhost_auth() d = client.connect( "localhost", self.listen_port, username=username ) @@ -147,8 +145,7 @@ class ClientTestCase(BaseTestCase): return d def test_connect_without_sending_client_version_fails(self): - from deluge.ui import common - username, password = common.get_localhost_auth() + username, password = deluge.ui.common.get_localhost_auth() no_version_sending_client = NoVersionSendingClient() d = no_version_sending_client.connect( "localhost", self.listen_port, username=username, password=password diff --git a/deluge/tests/test_core.py b/deluge/tests/test_core.py index aefc86069..14960c848 100644 --- a/deluge/tests/test_core.py +++ b/deluge/tests/test_core.py @@ -11,6 +11,7 @@ from twisted.web.resource import Resource from twisted.web.server import Site from twisted.web.static import File +import deluge.common import deluge.component as component import deluge.core.torrent from deluge.core.core import Core @@ -86,10 +87,12 @@ class CoreTestCase(BaseTestCase): error = ex self.listen_port += 1 else: - return result + break else: raise error + return result + def tear_down(self): def on_shutdown(result): @@ -155,7 +158,6 @@ class CoreTestCase(BaseTestCase): def test_add_magnet(self): info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00" - import deluge.common uri = deluge.common.create_magnet_uri(info_hash) options = {} diff --git a/deluge/tests/test_decorators.py b/deluge/tests/test_decorators.py index 272c9a807..5201060ac 100644 --- a/deluge/tests/test_decorators.py +++ b/deluge/tests/test_decorators.py @@ -9,13 +9,13 @@ class DecoratorsTestCase(unittest.TestCase): return not func(*args, **kwargs) @proxy(negate) - def something(bool): - return bool + def something(_bool): + return _bool @proxy(negate) @proxy(negate) - def double_nothing(bool): - return bool + def double_nothing(_bool): + return _bool self.assertTrue(something(False)) self.assertFalse(something(True)) diff --git a/deluge/transfer.py b/deluge/transfer.py index dcd424b09..7f8de0902 100644 --- a/deluge/transfer.py +++ b/deluge/transfer.py @@ -8,7 +8,7 @@ # try: - import rencode + import rencode # pylint: disable=relative-import except ImportError: import deluge.rencode as rencode diff --git a/deluge/ui/client.py b/deluge/ui/client.py index 7725882cc..5dd36b975 100644 --- a/deluge/ui/client.py +++ b/deluge/ui/client.py @@ -159,7 +159,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): # The rest just get's logged in debug level, just to log # what's happening log.debug(msg) - except: + except Exception: import traceback log.error("Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s", request[2], traceback.format_exc()) @@ -426,8 +426,8 @@ class DaemonClassicProxy(DaemonProxy): def __init__(self, event_handlers=None): if event_handlers is None: event_handlers = {} - import deluge.core.daemon - self.__daemon = deluge.core.daemon.Daemon(classic=True) + from deluge.core import daemon + self.__daemon = daemon.Daemon(classic=True) log.debug("daemon created!") self.connected = True self.host = "localhost" diff --git a/deluge/ui/common.py b/deluge/ui/common.py index 98db49fc2..28f9ecc6e 100644 --- a/deluge/ui/common.py +++ b/deluge/ui/common.py @@ -38,7 +38,6 @@ STATE_TRANSLATION = { "Downloading": _("Downloading"), "Seeding": _("Seeding"), "Paused": _("Paused"), - "Checking": _("Checking"), "Queued": _("Queued"), "Error": _("Error"), } diff --git a/deluge/ui/console/colors.py b/deluge/ui/console/colors.py index 1c87a2b19..0875735ec 100644 --- a/deluge/ui/console/colors.py +++ b/deluge/ui/console/colors.py @@ -83,7 +83,7 @@ def init_colors(): try: curses.init_pair(counter, curses.COLOR_WHITE, curses.COLOR_BLACK) color_pairs[("white", "black")] = counter - except: + except Exception: pass diff --git a/deluge/ui/console/commands/config.py b/deluge/ui/console/commands/config.py index 77ea4ad4a..4dce8981c 100644 --- a/deluge/ui/console/commands/config.py +++ b/deluge/ui/console/commands/config.py @@ -21,16 +21,16 @@ from deluge.ui.console.main import BaseCommand log = logging.getLogger(__name__) -def atom(next, token): +def atom(_next, token): """taken with slight modifications from http://effbot.org/zone/simple-iterator-parser.htm""" if token[1] == "(": out = [] - token = next() + token = _next() while token[1] != ")": - out.append(atom(next, token)) - token = next() + out.append(atom(_next, token)) + token = _next() if token[1] == ",": - token = next() + token = _next() return tuple(out) elif token[0] is tokenize.NUMBER or token[1] == "-": try: @@ -118,7 +118,7 @@ class Command(BaseCommand): if type(config[key]) != type(val): try: val = type(config[key])(val) - except: + except TypeError: self.config.write("{!error!}Configuration value provided has incorrect type.") return diff --git a/deluge/ui/console/commands/connect.py b/deluge/ui/console/commands/connect.py index 948c2c8a8..5cd0bc5f4 100644 --- a/deluge/ui/console/commands/connect.py +++ b/deluge/ui/console/commands/connect.py @@ -38,7 +38,7 @@ class Command(BaseCommand): def on_connect_fail(result): try: msg = result.value.exception_msg - except: + except AttributeError: msg = result.value.args[0] self.console.write("{!error!}Failed to connect to %s:%s with reason: %s" % (host, port, msg)) return result diff --git a/deluge/ui/console/commands/info.py b/deluge/ui/console/commands/info.py index f77596f29..f71387af7 100644 --- a/deluge/ui/console/commands/info.py +++ b/deluge/ui/console/commands/info.py @@ -168,9 +168,9 @@ class Command(BaseCommand): cols = 80 prevpath = [] - for i, file in enumerate(status["files"]): - filename = file["path"].split(dirsep)[-1] - filepath = file["path"].split(dirsep)[:-1] + for i, _file in enumerate(status["files"]): + filename = _file["path"].split(dirsep)[-1] + filepath = _file["path"].split(dirsep)[:-1] for depth, subdir in enumerate(filepath): indent = " " * depth * spaces_per_level @@ -199,10 +199,8 @@ class Command(BaseCommand): col_priority += "{!input!}" col_priority += fp - rf = format_utils.remove_formatting - - def tlen(s): - return strwidth(rf(s)) + def tlen(string): + return strwidth(format_utils.remove_formatting(string)) if not isinstance(col_filename, unicode): col_filename = unicode(col_filename, "utf-8") diff --git a/deluge/ui/console/commands/plugin.py b/deluge/ui/console/commands/plugin.py index df89753a5..066dda1ac 100644 --- a/deluge/ui/console/commands/plugin.py +++ b/deluge/ui/console/commands/plugin.py @@ -118,9 +118,8 @@ class Command(BaseCommand): filedump = base64.encodestring(open(filepath, "rb").read()) try: client.core.upload_plugin(filename, filedump) - client.core.rescan_plugins() - except: + except Exception: self.console.write("{!error!}An error occurred, plugin was not installed") self.console.write("{!green!}Plugin was successfully installed: %s" % filename) diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py index bce728853..2b141589b 100644 --- a/deluge/ui/console/main.py +++ b/deluge/ui/console/main.py @@ -99,12 +99,12 @@ class DelugeHelpFormatter(optparse.IndentedHelpFormatter): replace_dict = { "<torrent-id>": "{!green!}%s{!input!}", "<state>": "{!yellow!}%s{!input!}", - "\.\.\.": "{!yellow!}%s{!input!}", - "\s\*\s": "{!blue!}%s{!input!}", - "(?<![\-a-z])(-[a-zA-Z0-9])": "{!red!}%s{!input!}", + "\\.\\.\\.": "{!yellow!}%s{!input!}", + "\\s\\*\\s": "{!blue!}%s{!input!}", + "(?<![\\-a-z])(-[a-zA-Z0-9])": "{!red!}%s{!input!}", # "(\-[a-zA-Z0-9])": "{!red!}%s{!input!}", - "--[_\-a-zA-Z0-9]+": "{!green!}%s{!input!}", - "(\[|\])": "{!info!}%s{!input!}", + "--[_\\-a-zA-Z0-9]+": "{!green!}%s{!input!}", + "(\\[|\\])": "{!info!}%s{!input!}", "<tab>": "{!white!}%s{!input!}", "[_A-Z]{3,}": "{!cyan!}%s{!input!}", @@ -181,13 +181,13 @@ class OptionParser(optparse.OptionParser): """ raise Exception(msg) - def print_usage(self, file=None): + def print_usage(self, _file=None): console = component.get("ConsoleUI") if self.usage: for line in self.get_usage().splitlines(): console.write(line) - def print_help(self, file=None): + def print_help(self, _file=None): console = component.get("ConsoleUI") console.set_batch_write(True) for line in self.format_help().splitlines(): @@ -239,14 +239,17 @@ class BaseCommand(object): result = shlex.split(text) for i, s in enumerate(result): result[i] = s.replace(r"\ ", " ") - result = filter(lambda s: s != "", result) + result = [s for s in result if s != ""] return result def create_parser(self): return OptionParser(prog=self.name, usage=self.usage, epilog=self.epilog, option_list=self.option_list) -def load_commands(command_dir, exclude=[]): +def load_commands(command_dir, exclude=None): + if not exclude: + exclude = [] + def get_command(name): return getattr(__import__("deluge.ui.console.commands.%s" % name, {}, {}, ["Command"]), "Command")() @@ -277,7 +280,7 @@ class ConsoleUI(component.Component): try: locale.setlocale(locale.LC_ALL, "") self.encoding = locale.getpreferredencoding() - except: + except Exception: self.encoding = sys.getdefaultencoding() log.debug("Using encoding: %s", self.encoding) @@ -404,9 +407,9 @@ Please use commands from the command line, eg:\n if self.interactive and isinstance(self.screen, deluge.ui.console.modes.legacy.Legacy): return self.screen.tab_complete_torrent(line) - def tab_complete_path(self, line, type="file", ext="", sort="name", dirs_first=True): + def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=True): if self.interactive and isinstance(self.screen, deluge.ui.console.modes.legacy.Legacy): - return self.screen.tab_complete_path(line, type=type, ext=ext, sort=sort, dirs_first=dirs_first) + return self.screen.tab_complete_path(line, path_type=path_type, ext=ext, sort=sort, dirs_first=dirs_first) def set_mode(self, mode): reactor.removeReader(self.screen) diff --git a/deluge/ui/console/modes/addtorrents.py b/deluge/ui/console/modes/addtorrents.py index 10e8e154f..e5abe2825 100644 --- a/deluge/ui/console/modes/addtorrents.py +++ b/deluge/ui/console/modes/addtorrents.py @@ -11,7 +11,7 @@ import base64 import logging import os -import deluge.common as common +import deluge.common import deluge.component as component from deluge.ui.client import client from deluge.ui.console.modes import format_utils @@ -134,7 +134,7 @@ class AddTorrents(BaseMode, component.Component): full_path = os.path.join(path, dirname) try: size = len(os.listdir(full_path)) - except: + except OSError: size = -1 time = os.stat(full_path).st_mtime @@ -185,7 +185,7 @@ class AddTorrents(BaseMode, component.Component): self.formatted_rows = [] for row in self.raw_rows: - filename = row[0] + filename = deluge.common.decode_string(row[0]) size = row[1] time = row[2] @@ -195,21 +195,12 @@ class AddTorrents(BaseMode, component.Component): else: size_str = " unknown" - try: - filename = filename.decode("utf8") - except: - pass - - cols = [filename, size_str, common.fdate(time)] + cols = [filename, size_str, deluge.common.fdate(time)] widths = [self.cols - 35, 12, 23] self.formatted_rows.append(format_utils.format_row(cols, widths)) else: # Size of .torrent file itself couldn't matter less so we'll leave it out - try: - filename = filename.decode("utf8") - except: - pass - cols = [filename, common.fdate(time)] + cols = [filename, deluge.common.fdate(time)] widths = [self.cols - 23, 23] self.formatted_rows.append(format_utils.format_row(cols, widths)) @@ -262,8 +253,8 @@ class AddTorrents(BaseMode, component.Component): string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr self.add_string(self.rows - 1, string) - except: - pass + except Exception as ex: + log.debug("Exception caught: %s", ex) off = 1 @@ -400,7 +391,7 @@ class AddTorrents(BaseMode, component.Component): ress = {"succ": 0, "fail": 0, "total": len(self.marked), "fmsg": []} def fail_cb(msg, t_file, ress): - log.debug("failed to add torrent: %s: %s" % (t_file, msg)) + log.debug("failed to add torrent: %s: %s", t_file, msg) ress["fail"] += 1 ress["fmsg"].append("{!input!} * %s: {!error!}%s" % (t_file, msg)) if (ress["succ"] + ress["fail"]) >= ress["total"]: @@ -408,7 +399,7 @@ class AddTorrents(BaseMode, component.Component): def success_cb(tid, t_file, ress): if tid: - log.debug("added torrent: %s (%s)" % (t_file, tid)) + log.debug("added torrent: %s (%s)", t_file, tid) ress["succ"] += 1 if (ress["succ"] + ress["fail"]) >= ress["total"]: self.alltorrentmode._report_add_status(ress["succ"], ress["fail"], ress["fmsg"]) diff --git a/deluge/ui/console/modes/alltorrents.py b/deluge/ui/console/modes/alltorrents.py index 18ea2d751..8bbc1c86c 100644 --- a/deluge/ui/console/modes/alltorrents.py +++ b/deluge/ui/console/modes/alltorrents.py @@ -102,18 +102,18 @@ files in the torrent and the ability to set file priorities. input something """ - -class FILTER: - ALL = 0 - ACTIVE = 1 - DOWNLOADING = 2 - SEEDING = 3 - PAUSED = 4 - CHECKING = 5 - ERROR = 6 - QUEUED = 7 - ALLOCATING = 8 - MOVING = 9 +STATE_FILTER = { + "all": 0, + "active": 1, + "downloading": 2, + "seeding": 3, + "paused": 4, + "checking": 5, + "error": 6, + "queued": 7, + "allocating": 8, + "moving": 9 +} DEFAULT_PREFS = { "show_queue": True, @@ -386,14 +386,14 @@ class AllTorrents(BaseMode, component.Component): def __update_columns(self): self.column_widths = [self.config["%s_width" % c] for c in self.__cols_to_show] - req = sum(filter(lambda x: x >= 0, self.column_widths)) - if req > self.cols: # can't satisfy requests, just spread out evenly + requested_width = sum([width for width in self.column_widths if width >= 0]) + if requested_width > self.cols: # can't satisfy requests, just spread out evenly cw = int(self.cols / len(self.__columns)) for i in range(0, len(self.column_widths)): self.column_widths[i] = cw else: - rem = self.cols - req - var_cols = len(filter(lambda x: x < 0, self.column_widths)) + rem = self.cols - requested_width + var_cols = len([width for width in self.column_widths if width < 0]) if var_cols > 0: vw = int(rem / var_cols) for i in range(0, len(self.column_widths)): @@ -404,7 +404,7 @@ class AllTorrents(BaseMode, component.Component): try: primary_sort_col_name = prefs_to_names[self.config["sort_primary"]] - except: + except KeyError: primary_sort_col_name = "" for i, column in enumerate(self.__columns): @@ -652,34 +652,34 @@ class AllTorrents(BaseMode, component.Component): component.stop(["AllTorrents"]).addCallback(dolegacy) def _torrent_filter(self, idx, data): - if data == FILTER.ALL: + if data == STATE_FILTER["all"]: self.__status_dict = {} self._curr_filter = None - elif data == FILTER.ACTIVE: + elif data == STATE_FILTER["active"]: self.__status_dict = {"state": "Active"} self._curr_filter = "Active" - elif data == FILTER.DOWNLOADING: + elif data == STATE_FILTER["downloading"]: self.__status_dict = {"state": "Downloading"} self._curr_filter = "Downloading" - elif data == FILTER.SEEDING: + elif data == STATE_FILTER["seeding"]: self.__status_dict = {"state": "Seeding"} self._curr_filter = "Seeding" - elif data == FILTER.PAUSED: + elif data == STATE_FILTER["paused"]: self.__status_dict = {"state": "Paused"} self._curr_filter = "Paused" - elif data == FILTER.CHECKING: + elif data == STATE_FILTER["checking"]: self.__status_dict = {"state": "Checking"} self._curr_filter = "Checking" - elif data == FILTER.ERROR: + elif data == STATE_FILTER["error"]: self.__status_dict = {"state": "Error"} self._curr_filter = "Error" - elif data == FILTER.QUEUED: + elif data == STATE_FILTER["queued"]: self.__status_dict = {"state": "Queued"} self._curr_filter = "Queued" - elif data == FILTER.ALLOCATING: + elif data == STATE_FILTER["allocating"]: self.__status_dict = {"state": "Allocating"} self._curr_filter = "Allocating" - elif data == FILTER.MOVING: + elif data == STATE_FILTER["moving"]: self.__status_dict = {"state": "Moving"} self._curr_filter = "Moving" @@ -688,16 +688,16 @@ class AllTorrents(BaseMode, component.Component): def _show_torrent_filter_popup(self): self.popup = SelectablePopup(self, "Filter Torrents", self._torrent_filter) - self.popup.add_line("_All", data=FILTER.ALL) - self.popup.add_line("Ac_tive", data=FILTER.ACTIVE) - self.popup.add_line("_Downloading", data=FILTER.DOWNLOADING, foreground="green") - self.popup.add_line("_Seeding", data=FILTER.SEEDING, foreground="cyan") - self.popup.add_line("_Paused", data=FILTER.PAUSED) - self.popup.add_line("_Error", data=FILTER.ERROR, foreground="red") - self.popup.add_line("_Checking", data=FILTER.CHECKING, foreground="blue") - self.popup.add_line("Q_ueued", data=FILTER.QUEUED, foreground="yellow") - self.popup.add_line("A_llocating", data=FILTER.ALLOCATING, foreground="yellow") - self.popup.add_line("_Moving", data=FILTER.MOVING, foreground="green") + self.popup.add_line("_All", data=STATE_FILTER["all"]) + self.popup.add_line("Ac_tive", data=STATE_FILTER["active"]) + self.popup.add_line("_Downloading", data=STATE_FILTER["downloading"], foreground="green") + self.popup.add_line("_Seeding", data=STATE_FILTER["seeding"], foreground="cyan") + self.popup.add_line("_Paused", data=STATE_FILTER["paused"]) + self.popup.add_line("_Error", data=STATE_FILTER["error"], foreground="red") + self.popup.add_line("_Checking", data=STATE_FILTER["checking"], foreground="blue") + self.popup.add_line("Q_ueued", data=STATE_FILTER["queued"], foreground="yellow") + self.popup.add_line("A_llocating", data=STATE_FILTER["allocating"], foreground="yellow") + self.popup.add_line("_Moving", data=STATE_FILTER["moving"], foreground="green") def _report_add_status(self, succ_cnt, fail_cnt, fail_msgs): if fail_cnt == 0: @@ -712,13 +712,13 @@ class AllTorrents(BaseMode, component.Component): def do_add_from_url(result): def fail_cb(msg, url): - log.debug("failed to add torrent: %s: %s" % (url, msg)) + log.debug("failed to add torrent: %s: %s", url, msg) error_msg = "{!input!} * %s: {!error!}%s" % (url, msg) self._report_add_status(0, 1, [error_msg]) def success_cb(tid, url): if tid: - log.debug("added torrent: %s (%s)" % (url, tid)) + log.debug("added torrent: %s (%s)", url, tid) self._report_add_status(1, 0, []) else: fail_cb("Already in session (probably)", url) @@ -859,7 +859,7 @@ class AllTorrents(BaseMode, component.Component): string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr self.add_string(self.rows - 1, string) - except: + except Exception: pass # add all the torrents @@ -958,8 +958,8 @@ class AllTorrents(BaseMode, component.Component): try: self.add_string(currow, "%s%s" % (colorstr, row[0]), trim=False) - except: - # Yeah, this should be fixed in some better way + except Exception: + # XXX: Yeah, this should be fixed in some better way pass tidx += 1 currow += 1 @@ -1260,7 +1260,7 @@ class AllTorrents(BaseMode, component.Component): i = len(self.__cols_to_show) try: i = self.__cols_to_show.index(self.config["sort_primary"]) - 1 - except: + except KeyError: pass i = max(0, i) @@ -1276,7 +1276,7 @@ class AllTorrents(BaseMode, component.Component): i = 0 try: i = self.__cols_to_show.index(self.config["sort_primary"]) + 1 - except: + except KeyError: pass i = min(len(self.__cols_to_show) - 1, i) diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py index 076bcb6b2..4400a7651 100644 --- a/deluge/ui/console/modes/basemode.py +++ b/deluge/ui/console/modes/basemode.py @@ -26,7 +26,7 @@ try: from fcntl import ioctl import termios import struct -except: +except ImportError: pass @@ -155,7 +155,7 @@ class BaseMode(CursesStdIO): # This is the last string so lets append some " " to it s += " " * (self.cols - (col + len(s)) - 1) if trim: - y, x = screen.getmaxyx() + dummy, x = screen.getmaxyx() if (col + len(s)) > x: s = "%s..." % s[0:x - 4 - col] screen.addstr(row, col, s, color) diff --git a/deluge/ui/console/modes/column.py b/deluge/ui/console/modes/column.py index 494c460bf..459088306 100644 --- a/deluge/ui/console/modes/column.py +++ b/deluge/ui/console/modes/column.py @@ -61,13 +61,13 @@ def get_column_value(name, state): if col[1]: try: args = [state[key] for key in col[0]] - except: + except KeyError: return "Please Wait" return col[1](*args) else: try: return state[col[0][0]] - except: + except KeyError: return "Please Wait" diff --git a/deluge/ui/console/modes/eventview.py b/deluge/ui/console/modes/eventview.py index 8af7f4c1d..4ed575188 100644 --- a/deluge/ui/console/modes/eventview.py +++ b/deluge/ui/console/modes/eventview.py @@ -45,8 +45,8 @@ class EventView(BaseMode): string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr self.add_string(self.rows - 1, string) - except: - pass + except Exception as ex: + log.debug("Exception caught: %s", ex) if events: for i, event in enumerate(events): diff --git a/deluge/ui/console/modes/format_utils.py b/deluge/ui/console/modes/format_utils.py index 406445665..c30c47f36 100644 --- a/deluge/ui/console/modes/format_utils.py +++ b/deluge/ui/console/modes/format_utils.py @@ -121,7 +121,7 @@ def format_column(col, lim): def format_row(row, column_widths): return "".join([format_column(row[i], column_widths[i]) for i in range(0, len(row))]) -_strip_re = re.compile("\{!.*?!\}") +_strip_re = re.compile("\\{!.*?!\\}") def remove_formatting(string): diff --git a/deluge/ui/console/modes/input_popup.py b/deluge/ui/console/modes/input_popup.py index 5a69b0288..6eeb68c91 100644 --- a/deluge/ui/console/modes/input_popup.py +++ b/deluge/ui/console/modes/input_popup.py @@ -201,7 +201,7 @@ class IntSpinInput(InputField): self.valstr = self.default_str try: int(self.value) - except: + except ValueError: self.real_value = False else: self.value = int(self.valstr) @@ -214,11 +214,11 @@ class IntSpinInput(InputField): self.real_value = True try: self.value = int(self.valstr) - except: + except ValueError: self.value = self.default_value try: int(self.value) - except: + except ValueError: self.real_value = False if not self.valstr: self.parent.add_string(row, "%s {!input!}[ ]" % self.message, screen, col, False, True) @@ -381,7 +381,7 @@ class FloatSpinInput(InputField): self.valstr = self.default_str try: float(self.value) - except: + except ValueError: self.real_value = False else: self.set_value(self.valstr) @@ -394,11 +394,11 @@ class FloatSpinInput(InputField): self.real_value = True try: self.value = round(float(self.valstr), self.precision) - except: + except ValueError: self.value = self.default_value try: float(self.value) - except: + except ValueError: self.real_value = False if not self.valstr: diff --git a/deluge/ui/console/modes/legacy.py b/deluge/ui/console/modes/legacy.py index 2f1ee8a81..afe95328a 100644 --- a/deluge/ui/console/modes/legacy.py +++ b/deluge/ui/console/modes/legacy.py @@ -142,14 +142,14 @@ class Legacy(BaseMode, component.Component): try: lines1 = open(self.history_file[0], "r").read().splitlines() self._hf_lines[0] = len(lines1) - except: + except IOError: lines1 = [] self._hf_lines[0] = 0 try: lines2 = open(self.history_file[1], "r").read().splitlines() self._hf_lines[1] = len(lines2) - except: + except IOError: lines2 = [] self._hf_lines[1] = 0 @@ -170,13 +170,13 @@ class Legacy(BaseMode, component.Component): # self.lines[i] = line line = format_utils.remove_formatting(line) if line.startswith(">>> "): - input = line[4:] + console_input = line[4:] if self.console_config["ignore_duplicate_lines"]: if len(self.input_history) > 0: - if self.input_history[-1] != input: - self.input_history.append(input) + if self.input_history[-1] != console_input: + self.input_history.append(console_input) else: - self.input_history.append(input) + self.input_history.append(console_input) self.input_history_index = len(self.input_history) @@ -776,10 +776,10 @@ class Legacy(BaseMode, component.Component): cursor = len(line) return (line, cursor) - def tab_complete_path(self, line, type="file", ext="", sort="name", dirs_first=1): + def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=1): self.console = component.get("ConsoleUI") - line = line.replace("\ ", " ") + line = line.replace("\\ ", " ") line = os.path.abspath(os.path.expanduser(line)) ret = [] if os.path.exists(line): @@ -832,12 +832,12 @@ class Legacy(BaseMode, component.Component): self.console.write("{!error!}Permission denied: {!info!}%s" % line) if sort == "date": - ret = sorted(ret, key=lambda p: os.stat(p).st_mtime, reverse=True) + ret = sorted(ret, key=os.path.getmtime, reverse=True) if dirs_first == 1: - ret = sorted(ret, key=lambda p: os.path.isdir(p), reverse=True) + ret = sorted(ret, key=os.path.isdir, reverse=True) elif dirs_first == -1: - ret = sorted(ret, key=lambda p: os.path.isdir(p), reverse=False) + ret = sorted(ret, key=os.path.isdir, reverse=False) # Highlight directory names for i, filename in enumerate(ret): diff --git a/deluge/ui/console/modes/torrent_actions.py b/deluge/ui/console/modes/torrent_actions.py index 9ad936563..a728e22f9 100644 --- a/deluge/ui/console/modes/torrent_actions.py +++ b/deluge/ui/console/modes/torrent_actions.py @@ -104,12 +104,12 @@ def torrent_action(idx, data, mode, ids): mode.marked = range(1, selected_num + 1) elif qact == ACTION.QUEUE_UP: mode.cursel = max(1, mode.cursel - 1) - mode.marked = map(lambda v: v - 1, mode.marked) - mode.marked = filter(lambda v: v > 0, mode.marked) + mode.marked = [marked - 1 for marked in mode.marked] + mode.marked = [marked for marked in mode.marked if marked > 0] elif qact == ACTION.QUEUE_DOWN: mode.cursel = min(queue_length, mode.cursel + 1) - mode.marked = map(lambda v: v + 1, mode.marked) - mode.marked = filter(lambda v: v <= queue_length, mode.marked) + mode.marked = [marked + 1 for marked in mode.marked] + mode.marked = [marked for marked in mode.marked if marked <= queue_length] elif qact == ACTION.QUEUE_BOTTOM: if mode.marked: mode.cursel = queue_length - selected_num + 1 + sorted(mode.marked).index(mode.cursel) @@ -168,7 +168,7 @@ def torrent_action(idx, data, mode, ids): callbacks.append(d.addCallback(got_status)) def finish_up(status): - status = map(lambda x: x[1], status) + status = [t_status[1] for t_status in status] if len(ids) == 1: rem_msg = "{!info!}Removing the following torrent:{!input!}" @@ -290,7 +290,7 @@ def torrent_action(idx, data, mode, ids): callbacks = [] - field_list = map(lambda t: t[0], torrent_options) + field_list = [torrent_option[0] for torrent_option in torrent_options] for tid in torrents: deferred = component.get("SessionProxy").get_torrent_status(tid, field_list) diff --git a/deluge/ui/console/modes/torrentdetail.py b/deluge/ui/console/modes/torrentdetail.py index 7c389d579..b79ba3c20 100644 --- a/deluge/ui/console/modes/torrentdetail.py +++ b/deluge/ui/console/modes/torrentdetail.py @@ -224,14 +224,14 @@ class TorrentDetail(BaseMode, component.Component): def __update_columns(self): self.column_widths = [-1, 15, 15, 20] - req = sum(filter(lambda x: x >= 0, self.column_widths)) + req = sum([col_width for col_width in self.column_widths if col_width >= 0]) if req > self.cols: # can't satisfy requests, just spread out evenly cw = int(self.cols / len(self.column_names)) for i in range(0, len(self.column_widths)): self.column_widths[i] = cw else: rem = self.cols - req - var_cols = len(filter(lambda x: x < 0, self.column_widths)) + var_cols = len([col_width for col_width in self.column_widths if col_width < 0]) vw = int(rem / var_cols) for i in range(0, len(self.column_widths)): if self.column_widths[i] < 0: @@ -267,9 +267,7 @@ class TorrentDetail(BaseMode, component.Component): for i in old_folder.strip("/").split("/"): if not fl: fe = fl = self.file_list - - s = filter(lambda x: x[0].strip("/") == i, fl)[0] - + s = [files for files in fl if files[0].strip("/") == i][0] fe = s fl = s[3] fe[0] = new_folder.strip("/").rpartition("/")[-1] @@ -519,8 +517,8 @@ class TorrentDetail(BaseMode, component.Component): string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr self.add_string(self.rows - 1, string) - except: - pass + except Exception as ex: + log.debug("Exception caught: %s", ex) off = 1 if self.torrent_state: diff --git a/deluge/ui/countries.py b/deluge/ui/countries.py index 9c591f367..08c86a285 100644 --- a/deluge/ui/countries.py +++ b/deluge/ui/countries.py @@ -87,7 +87,6 @@ COUNTRIES = { 'GM': _('Gambia'), 'GE': _('Georgia'), 'DE': _('Germany'), - 'GB': _('United Kingdom'), 'GH': _('Ghana'), 'GI': _('Gibraltar'), 'GR': _('Greece'), diff --git a/deluge/ui/gtkui/addtorrentdialog.py b/deluge/ui/gtkui/addtorrentdialog.py index 886543d2d..6e9b80d11 100644 --- a/deluge/ui/gtkui/addtorrentdialog.py +++ b/deluge/ui/gtkui/addtorrentdialog.py @@ -283,22 +283,22 @@ class AddTorrentDialog(component.Component): def prepare_file_store(self, files): with listview_replace_treestore(self.listview_files): split_files = {} - for i, file in enumerate(files): + for i, _file in enumerate(files): self.prepare_file( - file, file["path"], i, file["download"], split_files + _file, _file["path"], i, _file["download"], split_files ) self.add_files(None, split_files) self.listview_files.expand_row("0", False) - def prepare_file(self, file, file_name, file_num, download, files_storage): + def prepare_file(self, _file, file_name, file_num, download, files_storage): first_slash_index = file_name.find(os.path.sep) if first_slash_index == -1: - files_storage[file_name] = (file_num, file, download) + files_storage[file_name] = (file_num, _file, download) else: file_name_chunk = file_name[:first_slash_index + 1] if file_name_chunk not in files_storage: files_storage[file_name_chunk] = {} - self.prepare_file(file, file_name[first_slash_index + 1:], + self.prepare_file(_file, file_name[first_slash_index + 1:], file_num, download, files_storage[file_name_chunk]) def add_files(self, parent_iter, split_files): @@ -436,13 +436,13 @@ class AddTorrentDialog(component.Component): for i, file_dict in enumerate(self.files[torrent_id]): file_dict["download"] = files_priorities[i] - def build_priorities(self, iter, priorities): - while iter is not None: - if self.files_treestore.iter_has_child(iter): - self.build_priorities(self.files_treestore.iter_children(iter), priorities) - elif not self.files_treestore.get_value(iter, 1).endswith(os.path.sep): - priorities[self.files_treestore.get_value(iter, 3)] = self.files_treestore.get_value(iter, 0) - iter = self.files_treestore.iter_next(iter) + def build_priorities(self, _iter, priorities): + while _iter is not None: + if self.files_treestore.iter_has_child(_iter): + self.build_priorities(self.files_treestore.iter_children(_iter), priorities) + elif not self.files_treestore.get_value(_iter, 1).endswith(os.path.sep): + priorities[self.files_treestore.get_value(_iter, 3)] = self.files_treestore.get_value(_iter, 0) + _iter = self.files_treestore.iter_next(_iter) return priorities def set_default_options(self): @@ -496,35 +496,35 @@ class AddTorrentDialog(component.Component): self.toggle_iter(row) self.update_treeview_toggles(self.files_treestore.get_iter_first()) - def toggle_iter(self, iter, toggle_to=None): + def toggle_iter(self, _iter, toggle_to=None): if toggle_to is None: - toggle_to = not self.files_treestore.get_value(iter, 0) - self.files_treestore.set_value(iter, 0, toggle_to) - if self.files_treestore.iter_has_child(iter): - child = self.files_treestore.iter_children(iter) + toggle_to = not self.files_treestore.get_value(_iter, 0) + self.files_treestore.set_value(_iter, 0, toggle_to) + if self.files_treestore.iter_has_child(_iter): + child = self.files_treestore.iter_children(_iter) while child is not None: self.toggle_iter(child, toggle_to) child = self.files_treestore.iter_next(child) - def update_treeview_toggles(self, iter): + def update_treeview_toggles(self, _iter): toggle_inconsistent = -1 this_level_toggle = None - while iter is not None: - if self.files_treestore.iter_has_child(iter): - toggle = self.update_treeview_toggles(self.files_treestore.iter_children(iter)) + while _iter is not None: + if self.files_treestore.iter_has_child(_iter): + toggle = self.update_treeview_toggles(self.files_treestore.iter_children(_iter)) if toggle == toggle_inconsistent: - self.files_treestore.set_value(iter, 4, True) + self.files_treestore.set_value(_iter, 4, True) else: - self.files_treestore.set_value(iter, 0, toggle) + self.files_treestore.set_value(_iter, 0, toggle) # set inconsistent to false - self.files_treestore.set_value(iter, 4, False) + self.files_treestore.set_value(_iter, 4, False) else: - toggle = self.files_treestore.get_value(iter, 0) + toggle = self.files_treestore.get_value(_iter, 0) if this_level_toggle is None: this_level_toggle = toggle elif this_level_toggle != toggle: this_level_toggle = toggle_inconsistent - iter = self.files_treestore.iter_next(iter) + _iter = self.files_treestore.iter_next(_iter) return this_level_toggle def _on_button_file_clicked(self, widget): diff --git a/deluge/ui/gtkui/connectionmanager.py b/deluge/ui/gtkui/connectionmanager.py index e02d4d401..eadf57c4b 100644 --- a/deluge/ui/gtkui/connectionmanager.py +++ b/deluge/ui/gtkui/connectionmanager.py @@ -222,8 +222,6 @@ class ConnectionManager(component.Component): # Host isn't in the list, so lets add it row = self.liststore.append() - import time - import hashlib self.liststore[row][HOSTLIST_COL_ID] = hashlib.sha1(str(time.time())).hexdigest() self.liststore[row][HOSTLIST_COL_HOST] = host self.liststore[row][HOSTLIST_COL_PORT] = port @@ -330,7 +328,7 @@ class ConnectionManager(component.Component): port, "localclient" if not user and host in ("127.0.0.1", "localhost") else user ) == client.connection_info(): - def on_info(info): + def on_info(info, row): if not self.running: return log.debug("Client connected, query info: %s", info) @@ -339,7 +337,7 @@ class ConnectionManager(component.Component): row[HOSTLIST_COL_STATUS] = "Connected" log.debug("Query daemon's info") - client.daemon.info().addCallback(on_info) + client.daemon.info().addCallback(on_info, row) continue # Create a new Client instance diff --git a/deluge/ui/gtkui/createtorrentdialog.py b/deluge/ui/gtkui/createtorrentdialog.py index 5cafc5ced..f972450c5 100644 --- a/deluge/ui/gtkui/createtorrentdialog.py +++ b/deluge/ui/gtkui/createtorrentdialog.py @@ -25,6 +25,10 @@ log = logging.getLogger(__name__) class CreateTorrentDialog: + + def __init__(self): + pass + def show(self): self.builder = gtk.Builder() diff --git a/deluge/ui/gtkui/edittrackersdialog.py b/deluge/ui/gtkui/edittrackersdialog.py index b3f746b2f..00836d58d 100644 --- a/deluge/ui/gtkui/edittrackersdialog.py +++ b/deluge/ui/gtkui/edittrackersdialog.py @@ -119,10 +119,10 @@ class EditTrackersDialog: if response == 1: self.trackers = [] - def each(model, path, iter, data): + def each(model, path, _iter, data): tracker = {} - tracker["tier"] = model.get_value(iter, 0) - tracker["url"] = model.get_value(iter, 1) + tracker["tier"] = model.get_value(_iter, 0) + tracker["url"] = model.get_value(_iter, 1) self.trackers.append(tracker) self.liststore.foreach(each, None) if self.old_trackers != self.trackers: diff --git a/deluge/ui/gtkui/files_tab.py b/deluge/ui/gtkui/files_tab.py index 17be09ad7..bf489a0c6 100644 --- a/deluge/ui/gtkui/files_tab.py +++ b/deluge/ui/gtkui/files_tab.py @@ -346,15 +346,15 @@ class FilesTab(Tab): def prepare_file_store(self, files): split_files = {} i = 0 - for file in files: - self.prepare_file(file, file["path"], i, split_files) + for _file in files: + self.prepare_file(_file, _file["path"], i, split_files) i += 1 self.add_files(None, split_files) - def prepare_file(self, file, file_name, file_num, files_storage): + def prepare_file(self, _file, file_name, file_num, files_storage): first_slash_index = file_name.find("/") if first_slash_index == -1: - files_storage[file_name] = (file_num, file) + files_storage[file_name] = (file_num, _file) else: file_name_chunk = file_name[:first_slash_index + 1] if file_name_chunk not in files_storage: @@ -419,24 +419,24 @@ class FilesTab(Tab): return def get_completed_bytes(row): - bytes = 0 + completed_bytes = 0 parent = self.treestore.iter_parent(row) while row: if self.treestore.iter_children(row): - bytes += get_completed_bytes(self.treestore.iter_children(row)) + completed_bytes += get_completed_bytes(self.treestore.iter_children(row)) else: - bytes += self.treestore[row][1] * (float(self.treestore[row][3]) / 100.0) + completed_bytes += self.treestore[row][1] * (float(self.treestore[row][3]) / 100.0) row = self.treestore.iter_next(row) try: - value = (float(bytes) / float(self.treestore[parent][1])) * 100 + value = (float(completed_bytes) / float(self.treestore[parent][1])) * 100 except ZeroDivisionError: # Catch the unusal error found when moving folders around value = 0 self.treestore[parent][3] = value self.treestore[parent][2] = "%.2f%%" % value - return bytes + return completed_bytes get_completed_bytes(self.treestore.iter_children(root)) @@ -536,12 +536,12 @@ class FilesTab(Tab): """Sets the file priorities in the core. It will change the selected with the 'priority'""" file_priorities = [] - def set_file_priority(model, path, iter, data): - index = model.get_value(iter, 5) + def set_file_priority(model, path, _iter, data): + index = model.get_value(_iter, 5) if index in selected and index != -1: file_priorities.append((index, priority)) elif index != -1: - file_priorities.append((index, model.get_value(iter, 4))) + file_priorities.append((index, model.get_value(_iter, 4))) self.treestore.foreach(set_file_priority, None) file_priorities.sort() @@ -768,13 +768,13 @@ class FilesTab(Tab): old_split = old_folder.split("/") try: old_split.remove("") - except: + except ValueError: pass new_split = new_folder.split("/") try: new_split.remove("") - except: + except ValueError: pass old_folder_iter = self.get_iter_at_path(old_folder) diff --git a/deluge/ui/gtkui/gtkui.py b/deluge/ui/gtkui/gtkui.py index 100512acf..3709b84a7 100644 --- a/deluge/ui/gtkui/gtkui.py +++ b/deluge/ui/gtkui/gtkui.py @@ -114,7 +114,6 @@ DEFAULT_PREFS = { "autoadd_queued": False, "choose_directory_dialog_path": deluge.common.get_default_download_dir(), "show_new_releases": True, - "signal_port": 40000, "ntf_tray_blink": True, "ntf_sound": False, "ntf_sound_path": deluge.common.get_default_download_dir(), @@ -125,7 +124,6 @@ DEFAULT_PREFS = { "ntf_pass": "", "ntf_server": "", "ntf_security": None, - "signal_port": 40000, "show_sidebar": True, "show_toolbar": True, "show_statusbar": True, diff --git a/deluge/ui/gtkui/ipcinterface.py b/deluge/ui/gtkui/ipcinterface.py index 488e5cb3c..d94ed9bd6 100644 --- a/deluge/ui/gtkui/ipcinterface.py +++ b/deluge/ui/gtkui/ipcinterface.py @@ -34,6 +34,10 @@ log = logging.getLogger(__name__) class IPCProtocolServer(Protocol): + + def __init__(self): + pass + def dataReceived(self, data): # NOQA config = ConfigManager("gtkui.conf") data = rencode.loads(data, decode_utf8=True) @@ -43,6 +47,10 @@ class IPCProtocolServer(Protocol): class IPCProtocolClient(Protocol): + + def __init__(self): + pass + def connectionMade(self): # NOQA self.transport.write(rencode.dumps(self.factory.args)) self.transport.loseConnection() diff --git a/deluge/ui/gtkui/listview.py b/deluge/ui/gtkui/listview.py index ec8922758..aba3c9fcc 100644 --- a/deluge/ui/gtkui/listview.py +++ b/deluge/ui/gtkui/listview.py @@ -203,14 +203,14 @@ class ListView: if self.unique_column_id: self.last_sort_order = {} - def record_position(model, path, iter, data): - self.last_sort_order[model[iter][self.unique_column_id]] = path[0] + def record_position(model, path, _iter, data): + self.last_sort_order[model[_iter][self.unique_column_id]] = path[0] model.foreach(record_position, None) - def on_model_row_inserted(self, model, path, iter): + def on_model_row_inserted(self, model, path, _iter): if self.unique_column_id: self.last_sort_order.setdefault( - model[iter][self.unique_column_id], len(model) - 1) + model[_iter][self.unique_column_id], len(model) - 1) def stabilize_sort_func(self, sort_func): def stabilized(model, iter1, iter2, data): @@ -593,12 +593,14 @@ class ListView: return True - def add_progress_column(self, header, col_types=[float, str], sortid=0, + def add_progress_column(self, header, col_types=None, sortid=0, hidden=False, position=None, status_field=None, function=None, column_type="progress", tooltip=None, sort_func=None, default=True): """Add a progress column to the listview.""" + if col_types is None: + col_types = [float, str] render = gtk.CellRendererProgress() self.add_column(header, render, col_types, hidden, position, status_field, sortid, function=function, @@ -607,11 +609,13 @@ class ListView: return True - def add_texticon_column(self, header, col_types=[str, str], sortid=1, + def add_texticon_column(self, header, col_types=None, sortid=1, hidden=False, position=None, status_field=None, column_type="texticon", function=None, tooltip=None, default=True, default_sort=False): """Adds a texticon column to the listview.""" + if col_types is None: + col_types = [str, str] render1 = gtk.CellRendererPixbuf() render2 = gtk.CellRendererText() @@ -622,9 +626,9 @@ class ListView: return True - def on_keypress_search_by_name(self, model, column, key, iter): + def on_keypress_search_by_name(self, model, column, key, _iter): torrent_name_col = self.columns["Name"].column_indices[1] - return not model[iter][torrent_name_col].lower().startswith(key.lower()) + return not model[_iter][torrent_name_col].lower().startswith(key.lower()) def restore_columns_order_from_state(self): if self.state is None: @@ -656,8 +660,7 @@ class ListView: continue column = find_column(col_state.name) if not column: - log.debug("Could not find column matching \"%s\" on state." % - col_state.name) + log.debug("Could not find column matching \"%s\" on state.", col_state.name) # The cases where I've found that the column could not be found # is when not using the english locale, ie, the default one, or # when changing locales between runs. diff --git a/deluge/ui/gtkui/mainwindow.py b/deluge/ui/gtkui/mainwindow.py index 73af133ba..bd561e622 100644 --- a/deluge/ui/gtkui/mainwindow.py +++ b/deluge/ui/gtkui/mainwindow.py @@ -146,7 +146,7 @@ class MainWindow(component.Component): component.resume("TorrentView") component.resume("StatusBar") component.resume("TorrentDetails") - except: + except Exception: pass self.window.show() @@ -170,13 +170,13 @@ class MainWindow(component.Component): else: self.config["window_x_pos"] = self.window_x_pos self.config["window_y_pos"] = self.window_y_pos - except: + except Exception: pass try: component.resume("TorrentView") component.resume("StatusBar") component.resume("TorrentDetails") - except: + except Exception: pass self.window.present() @@ -272,7 +272,7 @@ class MainWindow(component.Component): try: component.resume("TorrentView") component.resume("StatusBar") - except: + except Exception: pass self.is_minimized = False return False diff --git a/deluge/ui/gtkui/path_combo_chooser.py b/deluge/ui/gtkui/path_combo_chooser.py index a35a19616..00c064024 100755 --- a/deluge/ui/gtkui/path_combo_chooser.py +++ b/deluge/ui/gtkui/path_combo_chooser.py @@ -222,13 +222,13 @@ class ValueList(object): return True return False - def handle_list_scroll(self, next=None, path=None, set_entry=False, swap=False, scroll_window=False): + def handle_list_scroll(self, _next=None, path=None, set_entry=False, swap=False, scroll_window=False): """ Handles changes to the row selection. - :param next: the direction to change selection. True means down and False means up. + :param _next: the direction to change selection. True means down and False means up. None means no change. - :type next: boolean/None + :type _next: boolean/None :param path: the current path. If None, the currently selected path is used. :type path: tuple :param set_entry: if the new value should be set in the text entry. @@ -252,7 +252,7 @@ class ValueList(object): # Set adjustment increment to 3 times the row height adjustment.set_step_increment(self.row_height * 3) - if next: + if _next: # If number of values is less than max rows, no scroll if self.get_values_count() < self.max_visible_rows: return @@ -280,14 +280,14 @@ class ValueList(object): path = cursor[0] else: # Since cursor is none, we won't advance the index - next = None + _next = None - # If next is None, we won't change the selection - if next is not None: + # If _next is None, we won't change the selection + if _next is not None: # We move the selection either one up or down. # If we reach end of list, we wrap index = path[0] if path else 0 - index = index + 1 if next else index - 1 + index = index + 1 if _next else index - 1 if index >= len(self.tree_store): index = 0 elif index < 0: @@ -422,10 +422,10 @@ class StoredValuesList(ValueList): elif key_is_up_or_down(keyval): # Swap the row value if event.state & gtk.gdk.CONTROL_MASK: - self.handle_list_scroll(next=key_is_down(keyval), + self.handle_list_scroll(_next=key_is_down(keyval), swap=True) else: - self.handle_list_scroll(next=key_is_down(keyval)) + self.handle_list_scroll(_next=key_is_down(keyval)) elif key_is_pgup_or_pgdown(event.keyval): # The cursor has been changed by the default key-press-event handler # so set the path of the cursor selected @@ -484,7 +484,7 @@ class CompletionList(ValueList): keyval = event.keyval ctrl = event.state & gtk.gdk.CONTROL_MASK if key_is_up_or_down(keyval): - self.handle_list_scroll(next=key_is_down(keyval)) + self.handle_list_scroll(_next=key_is_down(keyval)) return True elif ctrl: # Set show/hide hidden files @@ -501,7 +501,7 @@ class CompletionList(ValueList): path = self.treeview.get_path_at_pos(int(x), int(y)) if path: - self.handle_list_scroll(path=path[0], next=None) + self.handle_list_scroll(path=path[0], _next=None) class PathChooserPopup(object): @@ -667,7 +667,7 @@ class PathChooserPopup(object): def set_max_popup_rows(self, rows): try: int(rows) - except: + except Exception: self.max_visible_rows = 20 return self.max_visible_rows = rows @@ -780,7 +780,7 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup): """ swap = event.state & gtk.gdk.CONTROL_MASK scroll_window = event.state & gtk.gdk.SHIFT_MASK - self.handle_list_scroll(next=event.direction == gdk.SCROLL_DOWN, + self.handle_list_scroll(_next=event.direction == gdk.SCROLL_DOWN, set_entry=widget != self.treeview, swap=swap, scroll_window=scroll_window) return True @@ -829,10 +829,10 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup): return True def on_button_up_clicked(self, widget): - self.handle_list_scroll(next=False, swap=True) + self.handle_list_scroll(_next=False, swap=True) def on_button_down_clicked(self, widget): - self.handle_list_scroll(next=True, swap=True) + self.handle_list_scroll(_next=True, swap=True) def on_button_default_clicked(self, widget): if self.default_text: @@ -904,11 +904,11 @@ class PathCompletionPopup(CompletionList, PathChooserPopup): """ x, y, state = event.window.get_pointer() - self.handle_list_scroll(next=event.direction == gdk.SCROLL_DOWN, + self.handle_list_scroll(_next=event.direction == gdk.SCROLL_DOWN, set_entry=widget != self.treeview, scroll_window=True) path = self.treeview.get_path_at_pos(int(x), int(y)) if path: - self.handle_list_scroll(path=path[0], next=None) + self.handle_list_scroll(path=path[0], _next=None) return True @@ -970,7 +970,7 @@ class PathAutoCompleter(object): if values_count == 1: self.do_completion() else: - self.completion_popup.handle_list_scroll(next=True) + self.completion_popup.handle_list_scroll(_next=True) return True self.path_entry.text_entry.emit("key-press-event", event) @@ -1305,7 +1305,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): # Select new row with arrow up/down is pressed if key_is_up_or_down(keyval): - self.handle_list_scroll(next=key_is_down(keyval), + self.handle_list_scroll(_next=key_is_down(keyval), set_entry=True) return True elif self.auto_completer.is_auto_completion_accelerator(keyval, state): @@ -1515,7 +1515,7 @@ if __name__ == "__main__": box1.add(entry1) box1.add(entry2) - paths = [ + test_paths = [ "/home/bro/Downloads", "/media/Movies-HD", "/media/torrent/in", @@ -1528,7 +1528,7 @@ if __name__ == "__main__": "/media/Series/19" ] - entry1.add_values(paths) + entry1.add_values(test_paths) entry1.set_text("/home/bro/", default_text=True) entry2.set_text("/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/", cursor_end=False) diff --git a/deluge/ui/gtkui/peers_tab.py b/deluge/ui/gtkui/peers_tab.py index 1c18e8726..943254126 100644 --- a/deluge/ui/gtkui/peers_tab.py +++ b/deluge/ui/gtkui/peers_tab.py @@ -315,9 +315,9 @@ class PeersTab(Tab): if not widget.get_tooltip_context(x, y, keyboard_tip): return False else: - model, path, iter = widget.get_tooltip_context(x, y, keyboard_tip) + model, path, _iter = widget.get_tooltip_context(x, y, keyboard_tip) - country_code = model.get(iter, 5)[0] + country_code = model.get(_iter, 5)[0] if country_code != " " and country_code in COUNTRIES: tooltip.set_text(COUNTRIES[country_code]) # widget here is self.listview diff --git a/deluge/ui/gtkui/piecesbar.py b/deluge/ui/gtkui/piecesbar.py index 448d9705d..0cb31c25f 100644 --- a/deluge/ui/gtkui/piecesbar.py +++ b/deluge/ui/gtkui/piecesbar.py @@ -207,10 +207,10 @@ class PiecesBar(gtk.DrawingArea): if self.__state: text += _(self.__state) + " " if self.__fraction == 1.0: - format = "%d%%" + fraction_format = "%d%%" else: - format = "%.2f%%" - text += format % (self.__fraction * 100) + fraction_format = "%.2f%%" + text += fraction_format % (self.__fraction * 100) log.trace("PiecesBar text %r", text) pl.set_text(text) plsize = pl.get_size() diff --git a/deluge/ui/gtkui/pluginmanager.py b/deluge/ui/gtkui/pluginmanager.py index b6b051af7..ab693c5f6 100644 --- a/deluge/ui/gtkui/pluginmanager.py +++ b/deluge/ui/gtkui/pluginmanager.py @@ -43,7 +43,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon """Deregisters a hook function""" try: self.hooks[hook].remove(function) - except: + except KeyError: log.warning("Unable to deregister hook %s", hook) def start(self): diff --git a/deluge/ui/gtkui/preferences.py b/deluge/ui/gtkui/preferences.py index 9968f9e13..379147923 100644 --- a/deluge/ui/gtkui/preferences.py +++ b/deluge/ui/gtkui/preferences.py @@ -77,8 +77,8 @@ class Preferences(component.Component): self.liststore.append([i, category]) i += 1 - def set_separator(model, iter, data=None): - if "_separator_" == model.get_value(iter, 1): + def set_separator(model, _iter, data=None): + if "_separator_" == model.get_value(_iter, 1): return True self.treeview.set_row_separator_func(set_separator) @@ -207,13 +207,14 @@ class Preferences(component.Component): translations_path = deluge.common.get_translations_path() for root, dirs, files in os.walk(translations_path): # Get the dirs + lang_dirs = dirs break self.language_combo = self.builder.get_object("combobox_language") self.language_checkbox = self.builder.get_object("checkbutton_language") lang_model = self.language_combo.get_model() index = -1 - for i, lang_code in enumerate(sorted(dirs)): + for i, lang_code in enumerate(sorted(lang_dirs)): name = "%s (Language name missing)" % lang_code if lang_code in languages.LANGUAGES: name = languages.LANGUAGES[lang_code] @@ -267,12 +268,12 @@ class Preferences(component.Component): self.page_num_to_remove = None self.iter_to_remove = None - def check_row(model, path, iter, user_data): - row_name = model.get_value(iter, 1) + def check_row(model, path, _iter, user_data): + row_name = model.get_value(_iter, 1) if row_name == user_data: # This is the row we need to remove - self.page_num_to_remove = model.get_value(iter, 0) - self.iter_to_remove = iter + self.page_num_to_remove = model.get_value(_iter, 0) + self.iter_to_remove = _iter return self.liststore.foreach(check_row, name) @@ -834,7 +835,7 @@ class Preferences(component.Component): """Handles widget sensitivity based on radio/check button values.""" try: value = widget.get_active() - except: + except Exception: return path_choosers = {"download_location_path_chooser": self.download_location_path_chooser, @@ -981,7 +982,6 @@ class Preferences(component.Component): import base64 import shutil - import os.path filename = os.path.split(filepath)[1] shutil.copyfile( filepath, @@ -1080,15 +1080,15 @@ class Preferences(component.Component): self.accounts_liststore.clear() for account in known_accounts: - iter = self.accounts_liststore.append() + accounts_iter = self.accounts_liststore.append() self.accounts_liststore.set_value( - iter, ACCOUNTS_USERNAME, account['username'] + accounts_iter, ACCOUNTS_USERNAME, account['username'] ) self.accounts_liststore.set_value( - iter, ACCOUNTS_LEVEL, account['authlevel'] + accounts_iter, ACCOUNTS_LEVEL, account['authlevel'] ) self.accounts_liststore.set_value( - iter, ACCOUNTS_PASSWORD, account['password'] + accounts_iter, ACCOUNTS_PASSWORD, account['password'] ) def _on_accounts_selection_changed(self, treeselection): @@ -1116,15 +1116,15 @@ class Preferences(component.Component): authlevel = dialog.get_authlevel() def add_ok(rv): - iter = self.accounts_liststore.append() + accounts_iter = self.accounts_liststore.append() self.accounts_liststore.set_value( - iter, ACCOUNTS_USERNAME, username + accounts_iter, ACCOUNTS_USERNAME, username ) self.accounts_liststore.set_value( - iter, ACCOUNTS_LEVEL, authlevel + accounts_iter, ACCOUNTS_LEVEL, authlevel ) self.accounts_liststore.set_value( - iter, ACCOUNTS_PASSWORD, password + accounts_iter, ACCOUNTS_PASSWORD, password ) def add_fail(failure): diff --git a/deluge/ui/gtkui/queuedtorrents.py b/deluge/ui/gtkui/queuedtorrents.py index 21a6d88e1..a3689b746 100644 --- a/deluge/ui/gtkui/queuedtorrents.py +++ b/deluge/ui/gtkui/queuedtorrents.py @@ -152,8 +152,8 @@ class QueuedTorrents(component.Component): def on_button_add_clicked(self, widget): # Add all the torrents in the liststore - def add_torrent(model, path, iter, data): - torrent_path = model.get_value(iter, 1).decode('utf-8') + def add_torrent(model, path, _iter, data): + torrent_path = model.get_value(_iter, 1).decode('utf-8') process_args([torrent_path]) self.liststore.foreach(add_torrent, None) diff --git a/deluge/ui/gtkui/removetorrentdialog.py b/deluge/ui/gtkui/removetorrentdialog.py index 0cc4c5f60..9d6a043a2 100644 --- a/deluge/ui/gtkui/removetorrentdialog.py +++ b/deluge/ui/gtkui/removetorrentdialog.py @@ -71,7 +71,7 @@ class RemoveTorrentDialog(object): if errors: log.info("Error(s) occured when trying to delete torrent(s).") for t_id, e_msg in errors: - log.warn("Error removing torrent %s : %s" % (t_id, e_msg)) + log.warn("Error removing torrent %s : %s", t_id, e_msg) d = client.core.remove_torrents(self.__torrent_ids, remove_data) d.addCallback(on_removed_finished) diff --git a/deluge/ui/gtkui/systemtray.py b/deluge/ui/gtkui/systemtray.py index 9a67582f3..66ab3d8e8 100644 --- a/deluge/ui/gtkui/systemtray.py +++ b/deluge/ui/gtkui/systemtray.py @@ -106,11 +106,7 @@ class SystemTray(component.Component): if deluge.common.windows_check() or deluge.common.osx_check(): self.tray = gtk.status_icon_new_from_pixbuf(get_logo(32)) else: - try: - self.tray = gtk.status_icon_new_from_icon_name("deluge") - except: - log.warning("Update PyGTK to 2.10 or greater for SystemTray..") - return + self.tray = gtk.status_icon_new_from_icon_name("deluge") self.tray.connect("activate", self.on_tray_clicked) self.tray.connect("popup-menu", self.on_tray_popup) diff --git a/deluge/ui/gtkui/torrentdetails.py b/deluge/ui/gtkui/torrentdetails.py index 4d2663c8c..cc8b38302 100644 --- a/deluge/ui/gtkui/torrentdetails.py +++ b/deluge/ui/gtkui/torrentdetails.py @@ -138,7 +138,7 @@ class TorrentDetails(component.Component): for w, name in weights: if w >= weight: position = self.tabs[name].position - log.debug("Found pos %d" % position) + log.debug("Found pos %d", position) break return position @@ -166,12 +166,12 @@ class TorrentDetails(component.Component): tab.is_visible = True # add the tab at position guided by the weight insert_pos = self.tab_insert_position(weight) - log.debug("Trying to insert tab at %d" % insert_pos) + log.debug("Trying to insert tab at %d", insert_pos) pos = self.notebook.insert_page( tab.get_child_widget(), tab.get_tab_label(), insert_pos) - log.debug("Tab inserted at %d" % pos) + log.debug("Tab inserted at %d", pos) tab.position = pos if not self.notebook.get_property("visible"): # If the notebook isn't visible, show it @@ -386,10 +386,10 @@ class TorrentDetails(component.Component): # Leave tabs we dont know anything about it the state as they # might come from a plugin for i, (name, visible) in enumerate(self.state): - log.debug("Testing name: %s" % name) + log.debug("Testing name: %s", name) if name in self.tabs: self.state[i] = (name, self.tabs[name].is_visible) - log.debug("Set to %s %d" % self.state[i]) + log.debug("Set to %s", self.state[i]) state = self.state save_pickled_state_file("tabs.state", state) diff --git a/deluge/ui/gtkui/torrentview.py b/deluge/ui/gtkui/torrentview.py index ee3f893de..88bbfc237 100644 --- a/deluge/ui/gtkui/torrentview.py +++ b/deluge/ui/gtkui/torrentview.py @@ -598,7 +598,7 @@ class TorrentView(ListView, component.Component): """Returns data stored in self.status, it may not be complete""" try: return self.status[torrent_id] - except: + except KeyError: return {} def get_visible_torrents(self): diff --git a/deluge/ui/tracker_icons.py b/deluge/ui/tracker_icons.py index bfe341f18..ef7db788c 100644 --- a/deluge/ui/tracker_icons.py +++ b/deluge/ui/tracker_icons.py @@ -388,7 +388,7 @@ class TrackerIcons(Component): icon = TrackerIcon(icon_name) return icon - def on_download_icon_fail(self, f, host, icons=[]): + def on_download_icon_fail(self, f, host, icons=None): """ Recovers from a download error @@ -402,6 +402,8 @@ class TrackerIcons(Component): else the original failure :rtype: Deferred or Failure """ + if not icons: + icons = [] error_msg = f.getErrorMessage() log.debug("Error downloading icon from %s: %s", host, error_msg) d = f @@ -495,21 +497,21 @@ class FaviconParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag == "link" and ("rel", "icon") in attrs or ("rel", "shortcut icon") in attrs: href = None - type = None + icon_type = None for attr, value in attrs: if attr == "href": href = value elif attr == "type": - type = value + icon_type = value if href: try: mimetype = extension_to_mimetype(href.rpartition(".")[2]) except KeyError: pass else: - type = mimetype - if type: - self.icons.append((href, type)) + icon_type = mimetype + if icon_type: + self.icons.append((href, icon_type)) def handle_endtag(self, tag): if tag == "head": diff --git a/deluge/ui/ui.py b/deluge/ui/ui.py index de70afff7..32759dbec 100644 --- a/deluge/ui/ui.py +++ b/deluge/ui/ui.py @@ -117,7 +117,6 @@ class _UI(object): class UI: def __init__(self, options, args, ui_args): - import logging log = logging.getLogger(__name__) log.debug("UI init..") @@ -153,7 +152,6 @@ class UI: from deluge.ui.console.main import ConsoleUI ConsoleUI(ui_args) except ImportError as ex: - import sys import traceback error_type, error_value, tb = sys.exc_info() stack = traceback.extract_tb(tb) diff --git a/deluge/ui/web/auth.py b/deluge/ui/web/auth.py index 55325542d..96b61a822 100644 --- a/deluge/ui/web/auth.py +++ b/deluge/ui/web/auth.py @@ -13,7 +13,6 @@ import random import time from datetime import datetime, timedelta from email.utils import formatdate -from functools import reduce from twisted.internet.task import LoopingCall @@ -43,7 +42,10 @@ from deluge.ui.web.json_api import export, JSONComponent # NOQA, isort:skip def make_checksum(session_id): - return reduce(lambda x, y: x + y, map(ord, session_id)) + checksum = 0 + for value in [ord(char) for char in session_id]: + checksum += value + return checksum def get_session_id(session_id): diff --git a/deluge/ui/web/common.py b/deluge/ui/web/common.py index 214a5a86c..bad3bd364 100644 --- a/deluge/ui/web/common.py +++ b/deluge/ui/web/common.py @@ -31,9 +31,9 @@ def escape(text): def compress(contents, request): request.setHeader("content-encoding", "gzip") - compress = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0) - contents = compress.compress(contents) - contents += compress.flush() + compress_zlib = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0) + contents = compress_zlib.compress(contents) + contents += compress_zlib.flush() return contents try: diff --git a/deluge/ui/web/json_api.py b/deluge/ui/web/json_api.py index dd16d7dd6..b1c3d751b 100644 --- a/deluge/ui/web/json_api.py +++ b/deluge/ui/web/json_api.py @@ -60,7 +60,7 @@ def export(auth_level=AUTH_LEVEL_DEFAULT): """ global AUTH_LEVEL_DEFAULT, AuthError if AUTH_LEVEL_DEFAULT is None: - from deluge.ui.web.auth import AUTH_LEVEL_DEFAULT + from deluge.ui.web.auth import AUTH_LEVEL_DEFAULT, AuthError # pylint: disable=redefined-outer-name def wrap(func, *args, **kwargs): func._json_export = True @@ -847,7 +847,7 @@ class WebApi(JSONComponent): d = c.connect(host, port, user, password) d.addCallback(on_connect, c) d.addErrback(on_connect_failed) - except: + except Exception: main_deferred.callback((False, "An error occurred")) return main_deferred @@ -874,7 +874,7 @@ class WebApi(JSONComponent): try: port = int(port) - except: + except ValueError: return (False, "Port is invalid") # Host isn't in the list, so lets add it diff --git a/deluge/ui/web/server.py b/deluge/ui/web/server.py index 283e9ff64..e5f04ecc7 100644 --- a/deluge/ui/web/server.py +++ b/deluge/ui/web/server.py @@ -261,7 +261,7 @@ class ScriptResource(resource.Resource, component.Component): } } - def add_script(self, path, filepath, type=None): + def add_script(self, path, filepath, script_type=None): """ Adds a script or scripts to the script resource. @@ -269,16 +269,16 @@ class ScriptResource(resource.Resource, component.Component): :type path: string :param filepath: The physical location of the script :type filepath: string - :keyword type: The type of script to add (normal, debug, dev) - :param type: string + :keyword script_type: The type of script to add (normal, debug, dev) + :param script_type: string """ - if type not in ("dev", "debug", "normal"): - type = "normal" + if script_type not in ("dev", "debug", "normal"): + script_type = "normal" - self.__scripts[type]["scripts"][path] = filepath - self.__scripts[type]["order"].append(path) + self.__scripts[script_type]["scripts"][path] = filepath + self.__scripts[script_type]["order"].append(path) - def add_script_folder(self, path, filepath, type=None, recurse=True): + def add_script_folder(self, path, filepath, script_type=None, recurse=True): """ Adds a folder of scripts to the script resource. @@ -286,45 +286,45 @@ class ScriptResource(resource.Resource, component.Component): :type path: string :param filepath: The physical location of the script :type filepath: string - :keyword type: The type of script to add (normal, debug, dev) - :param type: string + :keyword script_type: The type of script to add (normal, debug, dev) + :param script_type: string :keyword recurse: Whether or not to recurse into other folders :param recurse: bool """ - if type not in ("dev", "debug", "normal"): - type = "normal" + if script_type not in ("dev", "debug", "normal"): + script_type = "normal" - self.__scripts[type]["scripts"][path] = (filepath, recurse) - self.__scripts[type]["order"].append(path) + self.__scripts[script_type]["scripts"][path] = (filepath, recurse) + self.__scripts[script_type]["order"].append(path) - def remove_script(self, path, type=None): + def remove_script(self, path, script_type=None): """ Removes a script or folder of scripts from the script resource. :param path: The path of the folder :type path: string - :keyword type: The type of script to add (normal, debug, dev) - :param type: string + :keyword script_type: The type of script to add (normal, debug, dev) + :param script_type: string """ - if type not in ("dev", "debug", "normal"): - type = "normal" + if script_type not in ("dev", "debug", "normal"): + script_type = "normal" - del self.__scripts[type]["scripts"][path] - self.__scripts[type]["order"].remove(path) + del self.__scripts[script_type]["scripts"][path] + self.__scripts[script_type]["order"].remove(path) - def get_scripts(self, type=None): + def get_scripts(self, script_type=None): """ Returns a list of the scripts that can be used for producing script tags. - :keyword type: The type of scripts to get (normal, debug, dev) - :param type: string + :keyword script_type: The type of scripts to get (normal, debug, dev) + :param script_type: string """ - if type not in ("dev", "debug", "normal"): - type = 'normal' + if script_type not in ("dev", "debug", "normal"): + script_type = 'normal' - _scripts = self.__scripts[type]["scripts"] - _order = self.__scripts[type]["order"] + _scripts = self.__scripts[script_type]["scripts"] + _order = self.__scripts[script_type]["order"] scripts = [] for path in _order: @@ -371,8 +371,8 @@ class ScriptResource(resource.Resource, component.Component): def render(self, request): log.debug("Requested path: '%s'", request.lookup_path) - for type in ("dev", "debug", "normal"): - scripts = self.__scripts[type]["scripts"] + for script_type in ("dev", "debug", "normal"): + scripts = self.__scripts[script_type]["scripts"] for pattern in scripts: if not request.lookup_path.startswith(pattern): continue @@ -536,16 +536,19 @@ class TopLevel(resource.Resource): class ServerContextFactory: + def __init__(self): + pass + def getContext(self): # NOQA """Creates an SSL context.""" ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) - deluge_web = component.get("DelugeWeb") + delugeweb = component.get("DelugeWeb") log.debug("Enabling SSL using:") - log.debug("Pkey: %s", deluge_web.pkey) - log.debug("Cert: %s", deluge_web.cert) - ctx.use_privatekey_file(configmanager.get_config_dir(deluge_web.pkey)) - ctx.use_certificate_chain_file(configmanager.get_config_dir(deluge_web.cert)) + log.debug("Pkey: %s", delugeweb.pkey) + log.debug("Cert: %s", delugeweb.cert) + ctx.use_privatekey_file(configmanager.get_config_dir(delugeweb.pkey)) + ctx.use_certificate_chain_file(configmanager.get_config_dir(delugeweb.cert)) return ctx diff --git a/deluge/ui/web/web.py b/deluge/ui/web/web.py index 4fa9c8524..01769c7e4 100644 --- a/deluge/ui/web/web.py +++ b/deluge/ui/web/web.py @@ -12,7 +12,8 @@ from __future__ import print_function import os from optparse import OptionGroup -import deluge.common +from deluge.common import osx_check, windows_check +from deluge.configmanager import get_config_dir from deluge.ui.ui import _UI, UI @@ -35,14 +36,14 @@ class Web(_UI): group.add_option("-b", "--base", dest="base", help="Set the base path that the ui is running on (proxying)", action="store", default=None) - if not (deluge.common.windows_check() or deluge.common.osx_check()): + if not (windows_check() or osx_check()): group.add_option("-d", "--do-not-daemonize", dest="donotdaemonize", help="Do not daemonize the web interface", action="store_true", default=False) group.add_option("-P", "--pidfile", dest="pidfile", type="str", help="Use pidfile to store process id", action="store", default=None) - if not deluge.common.windows_check(): + if not windows_check(): group.add_option("-U", "--user", dest="user", type="str", help="User to switch to. Only use it when starting as root", action="store", default=None) @@ -60,8 +61,8 @@ class Web(_UI): action="store_true", default=False) try: import OpenSSL - OpenSSL.__version__ - except: + assert OpenSSL.__version__ + except ImportError: pass else: group.add_option("--no-ssl", dest="ssl", action="store_false", @@ -94,8 +95,7 @@ class Web(_UI): # chdir() to esnure that our process doesn't keep any directory in # use that may prevent a filesystem unmount. - import deluge.configmanager - os.chdir(deluge.configmanager.get_config_dir()) + os.chdir(get_config_dir()) if self.options.pidfile: open(self.options.pidfile, "wb").write("%d\n" % os.getpid()) @@ -133,7 +133,7 @@ class Web(_UI): if self.options.profile: import cProfile profiler = cProfile.Profile() - profile_output = deluge.configmanager.get_config_dir("delugeweb.profile") + profile_output = get_config_dir("delugeweb.profile") # Twisted catches signals to terminate def save_profile_stats(): @@ -63,13 +63,15 @@ confidence= # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" # -# Arranged by category (convention, error, information, refactor, warning). -# One category per line using symbolic names instead of ids. +# Arranged by category: Convention, Error, Information, Refactor, Warning. +# Category per line (wrapped categories are indented) using symbolic names instead of ids. disable=missing-docstring, invalid-name, old-style-class, bad-continuation, - no-member, not-callable, no-name-in-module, - locally-disabled, - R, - W + no-member, not-callable, no-name-in-module, + locally-disabled, + R, + unused-argument, broad-except, fixme, protected-access, import-error, unidiomatic-typecheck, + unused-variable, global-statement, attribute-defined-outside-init, arguments-differ, + no-init, non-parent-init-called, super-init-not-called, signature-differs [REPORTS] |