[Lint] Quote cleanup

This commit is contained in:
Calum Lind 2016-11-13 15:09:30 +00:00 committed by Calum Lind
parent 441861786b
commit 2657cc3921
77 changed files with 294 additions and 282 deletions

View File

@ -208,7 +208,7 @@ def get_pixmap(fname):
def resource_filename(module, path):
# While developing, if there's a second deluge package, installed globally
# and another in develop mode somewhere else, while pkg_resources.require("Deluge")
# and another in develop mode somewhere else, while pkg_resources.require('Deluge')
# returns the proper deluge instance, pkg_resources.resource_filename does
# not, it returns the first found on the python path, which is not good
# enough.
@ -556,7 +556,7 @@ def is_url(url):
**Usage**
>>> is_url("http://deluge-torrent.org")
>>> is_url('http://deluge-torrent.org')
True
"""
@ -588,7 +588,7 @@ def is_magnet(uri):
**Usage**
>>> is_magnet("magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN")
>>> is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN')
True
"""
@ -732,7 +732,7 @@ def is_ip(ip):
** Usage **
>>> is_ip("127.0.0.1")
>>> is_ip('127.0.0.1')
True
"""

View File

@ -142,8 +142,10 @@ class Component(object):
elif self._component_state == 'Started':
d = succeed(True)
else:
d = fail(ComponentException("Trying to start a component ('%s') not in stopped state. Current state: '%s'" %
(self._component_name, self._component_state), traceback.format_stack(limit=4)))
d = fail(ComponentException('Trying to start component "%s" but it is '
'not in a stopped state. Current state: %s' %
(self._component_name, self._component_state),
traceback.format_stack(limit=4)))
return d
def _component_stop(self):
@ -187,8 +189,10 @@ class Component(object):
elif self._component_state == 'Paused':
d = succeed(None)
else:
d = fail(ComponentException("Trying to pause a component ('%s') not in started state. Current state: '%s'" %
(self._component_name, self._component_state), traceback.format_stack(limit=4)))
d = fail(ComponentException('Trying to pause component "%s" but it is '
'not in a started state. Current state: %s' %
(self._component_name, self._component_state),
traceback.format_stack(limit=4)))
return d
def _component_resume(self):
@ -199,8 +203,10 @@ class Component(object):
d = maybeDeferred(self._component_start_timer)
d.addCallback(on_resume)
else:
d = fail(ComponentException("Trying to resume a component ('%s') not in paused state. Current state: '%s'" %
(self._component_name, self._component_state), traceback.format_stack(limit=4)))
d = fail(ComponentException('Trying to resume component "%s" but it is '
'not in a paused state. Current state: %s' %
(self._component_name, self._component_state),
traceback.format_stack(limit=4)))
return d
def _component_shutdown(self):

View File

@ -101,15 +101,15 @@ def find_json_objects(s):
class Config(object):
"""This class is used to access/create/modify config files
"""This class is used to access/create/modify config files.
Args:
filename (str): The config filename.
defaults (dict): The default config values to insert before loading the config file
config_dir (str): the path to the config directory
defaults (dict): The default config values to insert before loading the config file.
config_dir (str): the path to the config directory.
file_version (int): The file format for the default config values when creating
a fresh config. This value should be increased whenever a new migration function is
setup to convert old config files. Default value is 1.
setup to convert old config files. (default: 1)
"""
def __init__(self, filename, defaults=None, config_dir=None, file_version=1):
@ -148,24 +148,27 @@ class Config(object):
return self.set_item(key, value)
def set_item(self, key, value):
"""Sets item 'key' to 'value' in the config dictionary, but does not allow
changing the item's type unless it is None. If the types do not match,
it will attempt to convert it to the set type before raising a ValueError.
"""Sets item 'key' to 'value' in the config dictionary.
Does not allow changing the item's type unless it is None.
If the types do not match, it will attempt to convert it to the
set type before raising a ValueError.
Args:
key (str): item to change to change
value (any): the value to change item to, must be same type as what is
currently in the config
key (str): Item to change to change.
value (any): The value to change item to, must be same type as what is
currently in the config.
Raises:
ValueError: raised when the type of value is not the same as what is
currently in the config and it could not convert the value
ValueError: Raised when the type of value is not the same as what is
currently in the config and it could not convert the value.
**Usage**
Examples:
>>> config = Config("test.conf")
>>> config["test"] = 5
>>> config["test"]
>>> config = Config('test.conf')
>>> config['test'] = 5
>>> config['test']
5
"""
@ -174,7 +177,7 @@ class Config(object):
if key not in self.__config:
self.__config[key] = value
log.debug("Setting '%s' to %s of %s", key, value, type(value))
log.debug('Setting key "%s" to: %s (of type: %s)', key, value, type(value))
return
if self.__config[key] == value:
@ -190,10 +193,10 @@ class Config(object):
else:
value = oldtype(value)
except ValueError:
log.warning("Type '%s' invalid for '%s'", type(value), key)
log.warning('Value Type "%s" invalid for key: %s', type(value), key)
raise
log.debug("Setting '%s' to %s of %s", key, value, type(value))
log.debug('Setting key "%s" to: %s (of type: %s)', key, value, type(value))
self.__config[key] = value
@ -224,21 +227,21 @@ class Config(object):
return self.get_item(key)
def get_item(self, key):
"""Gets the value of item 'key'
"""Gets the value of item 'key'.
Args:
key (str): the item for which you want it's value
key (str): The item for which you want it's value.
Returns:
the value of item 'key'
any: The value of item 'key'.
Raises:
ValueError: if 'key' is not in the config dictionary
ValueError: If 'key' is not in the config dictionary.
**Usage**
Examples:
>>> config = Config("test.conf", defaults={"test": 5})
>>> config["test"]
>>> config = Config('test.conf', defaults={'test': 5})
>>> config['test']
5
"""
@ -252,6 +255,7 @@ class Config(object):
def get(self, key, default=None):
"""Gets the value of item 'key' if key is in the config, else default.
If default is not given, it defaults to None, so that this method
never raises a KeyError.
@ -260,14 +264,14 @@ class Config(object):
default (any): the default value if key is missing
Returns:
the value of item 'key' or default
any: The value of item 'key' or default.
**Usage**
Examples:
>>> config = Config("test.conf", defaults={"test": 5})
>>> config.get("test", 10)
>>> config = Config('test.conf', defaults={'test': 5})
>>> config.get('test', 10)
5
>>> config.get("bad_key", 10)
>>> config.get('bad_key', 10)
10
"""
@ -287,15 +291,18 @@ class Config(object):
"""Deletes item with a specific key from the configuration.
Args:
key (str): the item which you wish to delete.
key (str): The item which you wish to delete.
Raises:
ValueError: if 'key' is not in the config dictionary
ValueError: If 'key' is not in the config dictionary.
Examples:
>>> config = Config('test.conf', defaults={'test': 5})
>>> del config['test']
**Usage**
>>> config = Config("test.conf", defaults={"test": 5})
>>> del config["test"]
"""
del self.__config[key]
global callLater
@ -308,14 +315,16 @@ class Config(object):
self._save_timer = callLater(5, self.save)
def register_change_callback(self, callback):
"""Registers a callback function that will be called when a value is changed in the config dictionary
"""Registers a callback function for any changed value.
Will be called when any value is changed in the config dictionary.
Args:
callback (func): the function, callback(key, value)
callback (func): The function to call with parameters: f(key, value).
**Usage**
Examples:
>>> config = Config("test.conf", defaults={"test": 5})
>>> config = Config('test.conf', defaults={'test': 5})
>>> def cb(key, value):
... print key, value
...
@ -325,20 +334,20 @@ class Config(object):
self.__change_callbacks.append(callback)
def register_set_function(self, key, function, apply_now=True):
"""Register a function to be called when a config value changes
"""Register a function to be called when a config value changes.
Args:
key (str): the item to monitor for change
function (func): the function to call when the value changes, f(key, value)
apply_now (bool): if True, the function will be called after it's registered
key (str): The item to monitor for change.
function (func): The function to call when the value changes, f(key, value).
apply_now (bool): If True, the function will be called immediately after it's registered.
**Usage**
Examples:
>>> config = Config("test.conf", defaults={"test": 5})
>>> config = Config('test.conf', defaults={'test': 5})
>>> def cb(key, value):
... print key, value
...
>>> config.register_set_function("test", cb, apply_now=True)
>>> config.register_set_function('test', cb, apply_now=True)
test 5
"""
@ -354,15 +363,15 @@ class Config(object):
return
def apply_all(self):
"""Calls all set functions
"""Calls all set functions.
**Usage**
Examples:
>>> config = Config("test.conf", defaults={"test": 5})
>>> config = Config('test.conf', defaults={'test': 5})
>>> def cb(key, value):
... print key, value
...
>>> config.register_set_function("test", cb, apply_now=False)
>>> config.register_set_function('test', cb, apply_now=False)
>>> config.apply_all()
test 5
@ -385,10 +394,10 @@ class Config(object):
func(key, self.__config[key])
def load(self, filename=None):
"""Load a config file
"""Load a config file.
Args:
filename (str): if None, uses filename set in object initialization
filename (str): If None, uses filename set in object initialization
"""
if not filename:
@ -431,13 +440,13 @@ class Config(object):
self.__version['format'], self.__version['file'], self.__config)
def save(self, filename=None):
"""Save configuration to disk
"""Save configuration to disk.
Args:
filename (str): if None, uses filename set in object initialization
filename (str): If None, uses filename set in object initialization
Returns:
bool: whether or not the save succeeded.
bool: Whether or not the save succeeded.
"""
if not filename:
@ -494,17 +503,16 @@ class Config(object):
self._save_timer.cancel()
def run_converter(self, input_range, output_version, func):
"""Runs a function that will convert file versions in the `:param:input_range`
to the `:param:output_version`.
"""Runs a function that will convert file versions.
Args:
input_range (tuple): (int, int) the range of input versions this function will accept
output_version (int): the version this function will return
func (func): the function that will do the conversion, it will take the config
dict as an argument and return the augmented dict
input_range (tuple): (int, int) The range of input versions this function will accept.
output_version (int): The version this function will convert to.
func (func): The function that will do the conversion, it will take the config
dict as an argument and return the augmented dict.
Raises:
ValueError: if the output_version is less than the input_range
ValueError: If output_version is less than the input_range.
"""
if output_version in input_range or output_version <= max(input_range):

View File

@ -86,7 +86,7 @@ class _ConfigManager(object):
def get_config(self, config_file, defaults=None, file_version=1):
"""Get a reference to the Config object for this filename"""
log.debug("Getting config '%s'", config_file)
log.debug('Getting config: %s', config_file)
# Create the config object if not already created
if config_file not in self.config_files.keys():
self.config_files[config_file] = Config(config_file, defaults,

View File

@ -128,7 +128,7 @@ class AuthManager(component.Component):
if username in self.__auth:
raise AuthManagerError('Username in use.', username)
if authlevel not in AUTH_LEVELS_MAPPING:
raise AuthManagerError("Invalid auth level: '%s'" % authlevel)
raise AuthManagerError('Invalid auth level: %s' % authlevel)
try:
self.__auth[username] = Account(username, password,
AUTH_LEVELS_MAPPING[authlevel])
@ -142,7 +142,7 @@ class AuthManager(component.Component):
if username not in self.__auth:
raise AuthManagerError('Username not known', username)
if authlevel not in AUTH_LEVELS_MAPPING:
raise AuthManagerError("Invalid auth level: '%s'" % authlevel)
raise AuthManagerError('Invalid auth level: %s' % authlevel)
try:
self.__auth[username].username = username
self.__auth[username].password = password

View File

@ -281,7 +281,7 @@ class Core(component.Component):
yield self._add_torrent_file(torrent[0], torrent[1],
torrent[2], save_state=idx == last_index)
except AddTorrentError as ex:
log.warn("Error when adding torrent: '%s'", ex)
log.warn('Error when adding torrent: %s', ex)
errors.append(ex)
defer.returnValue(errors)
return task.deferLater(reactor, 0, add_torrents)
@ -310,7 +310,7 @@ class Core(component.Component):
try:
os.remove(filename)
except OSError as ex:
log.warning("Couldn't remove temp file: %s", ex)
log.warning('Could not remove temp file: %s', ex)
return self.add_torrent_file(filename, base64.encodestring(data), options)
def on_download_fail(failure):
@ -372,7 +372,7 @@ class Core(component.Component):
list: An empty list if no errors occurred otherwise the list contains
tuples of strings, a torrent ID and an error message. For example:
[("<torrent_id>", "Error removing torrent")]
[('<torrent_id>', 'Error removing torrent')]
"""
log.info('Removing %d torrents from core.', len(torrent_ids))

View File

@ -30,7 +30,7 @@ class EventManager(component.Component):
# Call any handlers for the event
if event.name in self.handlers:
for handler in self.handlers[event.name]:
# log.debug("Running handler %s for event %s with args: %s", event.name, handler, event.args)
# log.debug('Running handler %s for event %s with args: %s', event.name, handler, event.args)
try:
handler(*event.args)
except Exception as ex:

View File

@ -124,7 +124,7 @@ class PreferencesManager(component.Component):
component.Component.__init__(self, 'PreferencesManager')
self.config = deluge.configmanager.ConfigManager('core.conf', DEFAULT_PREFS)
if 'proxies' in self.config:
log.warning("Updating config file for proxy, using 'peer' values to fill new 'proxy' setting")
log.warning('Updating config file for proxy, using "peer" values to fill new "proxy" setting')
self.config['proxy'].update(self.config['proxies']['peer'])
log.warning('New proxy config is: %s', self.config['proxy'])
del self.config['proxies']

View File

@ -130,7 +130,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
log.debug('Received invalid rpc request: number of items '
'in request is %s', len(call))
continue
# log.debug("RPCRequest: %s", format_request(call))
# log.debug('RPCRequest: %s', format_request(call))
reactor.callLater(0, self.dispatch, *call)
def sendData(self, data): # NOQA: N802
@ -273,7 +273,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
if method not in self.factory.methods:
try:
# Raise exception to be sent back to client
raise AttributeError("RPC call on invalid function '%s'." % method)
raise AttributeError('RPC call on invalid function: %s' % method)
except AttributeError:
send_error()
return

View File

@ -495,7 +495,7 @@ class Torrent(object):
return
if log.isEnabledFor(logging.DEBUG):
log.debug("Setting %s's file priorities: %s", self.torrent_id, file_priorities)
log.debug('Setting %s file priorities to: %s', self.torrent_id, file_priorities)
self.handle.prioritize_files(file_priorities)
@ -650,7 +650,7 @@ class Torrent(object):
component.get('EventManager').emit(TorrentStateChangedEvent(self.torrent_id, self.state))
if log.isEnabledFor(logging.DEBUG):
log.debug("State from lt was: %s | Session is paused: %s\nTorrent state set from '%s' to '%s' (%s)",
log.debug('State from lt was: %s | Session is paused: %s\nTorrent state set from "%s" to "%s" (%s)',
'error' if status_error else status.state, session_paused, old_state, self.state, self.torrent_id)
if self.forced_error:
log.debug('Torrent Error state message: %s', self.forced_error.error_message)
@ -1080,10 +1080,10 @@ class Torrent(object):
if self.status.paused and self.status.auto_managed:
log.debug('Resume not possible for auto-managed torrent!')
elif self.forced_error and self.forced_error.was_paused:
log.debug("Resume skipped for error'd torrent as it was originally paused.")
log.debug('Resume skipped for forced_error torrent as it was originally paused.')
elif (self.status.is_finished and self.options['stop_at_ratio'] and
self.get_ratio() >= self.options['stop_ratio']):
log.debug("Resume skipped for torrent as it has reached 'stop_seed_ratio'.")
log.debug('Resume skipped for torrent as it has reached "stop_seed_ratio".')
else:
# Check if torrent was originally being auto-managed.
if self.options['auto_managed']:

View File

@ -483,7 +483,7 @@ class TorrentManager(component.Component):
try:
torrent = self.torrents[torrent_id]
except KeyError:
raise InvalidTorrentError("torrent_id '%s' not in session." % torrent_id)
raise InvalidTorrentError('torrent_id %s not in session.' % torrent_id)
torrent_name = torrent.get_status(['name'])['name']
@ -508,8 +508,8 @@ class TorrentManager(component.Component):
try:
self.queued_torrents.remove(torrent_id)
except KeyError:
log.debug("%s isn't in queued torrents set?", torrent_id)
raise InvalidTorrentError("%s isn't in queued torrents set?" % torrent_id)
log.debug('%s is not in queued torrents set.', torrent_id)
raise InvalidTorrentError('%s is not in queued torrents set.' % torrent_id)
# Remove the torrent from deluge's session
del self.torrents[torrent_id]
@ -607,7 +607,7 @@ class TorrentManager(component.Component):
d = self.add(torrent_info=torrent_info, state=t_state, options=options, save_state=False,
magnet=magnet, resume_data=resume_data.get(t_state.torrent_id))
except AddTorrentError as ex:
log.warn("Error when adding torrent '%s' to session: %s", t_state.torrent_id, ex)
log.warn('Error when adding torrent "%s" to session: %s', t_state.torrent_id, ex)
else:
deferreds.append(d)
@ -981,7 +981,7 @@ class TorrentManager(component.Component):
except KeyError:
# Sometimes libtorrent fires a TorrentFinishedEvent twice
if log.isEnabledFor(logging.DEBUG):
log.debug("%s isn't in queued torrents set?", torrent_id)
log.debug('%s is not in queued torrents set.', torrent_id)
# Only save resume data if it was actually downloaded something. Helps
# on startup with big queues with lots of seeding torrents. Libtorrent

View File

@ -102,15 +102,15 @@ def _overrides(stack, method, explicit_base_classes=None):
if issubclass(classes[bc], classes[cc]):
break
else:
raise Exception("Excplicit override class '%s' is not a super class of '%s'"
raise Exception('Excplicit override class "%s" is not a super class of: %s'
% (explicit_base_classes, class_name))
if not all(hasattr(classes[cls], method.__name__) for cls in check_classes):
for cls in check_classes:
if not hasattr(classes[cls], method.__name__):
raise Exception("Function override '%s' not found in superclass: '%s'\n%s"
raise Exception('Function override "%s" not found in superclass: %s\n%s'
% (method.__name__, cls, 'File: %s:%s' % (stack[1][1], stack[1][2])))
if not any(hasattr(classes[cls], method.__name__) for cls in check_classes):
raise Exception("Function override '%s' not found in any superclass: '%s'\n%s"
raise Exception('Function override "%s" not found in any superclass: %s\n%s'
% (method.__name__, check_classes, 'File: %s:%s' % (stack[1][1], stack[1][2])))
return method

View File

@ -124,18 +124,18 @@ def sanitise_filename(filename):
"""
# Remove any quotes
filename = filename.strip("'\"")
filename = filename.strip('\'"')
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
@ -253,7 +253,7 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal
result.addCallbacks(on_download_success, on_download_fail)
else:
# Log the failure and pass to the caller
log.warning("Error occurred downloading file from '%s': %s",
log.warning('Error occurred downloading file from "%s": %s',
url, failure.getErrorMessage())
result = failure
return result

View File

@ -114,7 +114,7 @@ def setup_logger(level='error', filename=None, filemode='w', logrotate=None,
to that file instead of stdout.
Args:
level (str): The log level to use (Default: "error")
level (str): The log level to use (Default: 'error')
filename (str, optional): The log filename. Default is None meaning log
to terminal
filemode (str): The filemode to use when opening the log file

View File

@ -37,10 +37,10 @@ class TorrentMetadata(object):
Examples:
>>> t = TorrentMetadata()
>>> t.data_path = "/tmp/torrent"
>>> t.comment = "My Test Torrent"
>>> t.trackers = [["http://tracker.openbittorent.com"]]
>>> t.save("/tmp/test.torrent")
>>> t.data_path = '/tmp/torrent'
>>> t.comment = 'My Test Torrent'
>>> t.trackers = [['http://tracker.openbittorent.com']]
>>> t.save('/tmp/test.torrent')
"""
def __init__(self):

View File

@ -152,7 +152,7 @@ class PluginManagerBase(object):
try:
return_d = defer.maybeDeferred(instance.enable)
except Exception as ex:
log.error("Unable to enable plugin '%s'!", name)
log.error('Unable to enable plugin: %s', name)
log.exception(ex)
return_d = defer.fail(False)
@ -174,11 +174,11 @@ class PluginManagerBase(object):
if plugin_name_space not in self.config['enabled_plugins']:
log.debug('Adding %s to enabled_plugins list in config', plugin_name_space)
self.config['enabled_plugins'].append(plugin_name_space)
log.info('Plugin %s enabled..', plugin_name_space)
log.info('Plugin %s enabled...', plugin_name_space)
return True
def on_started_error(result, instance):
log.warn("Failed to start plugin '%s': %s", plugin_name, result.getTraceback())
log.warn('Failed to start plugin: %s\n%s', plugin_name, result.getTraceback())
component.deregister(instance.plugin)
return False
@ -199,20 +199,20 @@ class PluginManagerBase(object):
"""
if name not in self.plugins:
log.warning("Plugin '%s' is not enabled..", name)
log.warning('Plugin "%s" is not enabled...', name)
return defer.succeed(True)
try:
d = defer.maybeDeferred(self.plugins[name].disable)
except Exception as ex:
log.error("Error when disabling plugin '%s'", self.plugin._component_name)
log.error('Error when disabling plugin: %s', self.plugin._component_name)
log.exception(ex)
d = defer.succeed(False)
def on_disabled(result):
ret = True
if isinstance(result, Failure):
log.error("Error when disabling plugin '%s'", name)
log.error('Error when disabling plugin: %s', name)
log.exception(result.getTraceback())
ret = False
try:
@ -220,11 +220,11 @@ class PluginManagerBase(object):
del self.plugins[name]
self.config['enabled_plugins'].remove(name)
except Exception as ex:
log.error("Unable to disable plugin '%s'!", name)
log.error('Unable to disable plugin: %s', name)
log.exception(ex)
ret = False
else:
log.info('Plugin %s disabled..', name)
log.info('Plugin %s disabled...', name)
return ret
d.addBoth(on_disabled)
@ -237,7 +237,7 @@ class PluginManagerBase(object):
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

View File

@ -116,7 +116,7 @@ class IP(object):
# if q3 >= 255:
# if q2 >= 255:
# if q1 >= 255:
# raise BadIP(_("There ain't a next IP address"))
# raise BadIP(_('There is not a next IP address'))
# q1 += 1
# else:
# q2 += 1
@ -132,7 +132,7 @@ class IP(object):
# if q3 <= 1:
# if q2 <= 1:
# if q1 <= 1:
# raise BadIP(_("There ain't a previous IP address"))
# raise BadIP(_('There is not a previous IP address'))
# q1 -= 1
# else:
# q2 -= 1

View File

@ -225,7 +225,7 @@ class Core(CorePluginBase):
if needs_blocklist_import:
log.debug('IP addresses were removed from the whitelist. Since we '
"don't know if they were blocked before. Re-import "
'do not know if they were blocked before. Re-import '
'current blocklist and re-add whitelisted.')
self.has_imported = False
d = self.import_list(deluge.configmanager.get_config_dir('blocklist.cache'))
@ -360,7 +360,8 @@ class Core(CorePluginBase):
else:
log.warning('Blocklist download failed: %s', error_msg)
if self.failed_attempts < self.config['try_times']:
log.debug("Let's try again")
log.debug('Try downloading blocklist again... (%s/%s)',
self.failed_attempts, self.config['try_times'])
self.failed_attempts += 1
d = self.download_list()
d.addCallbacks(self.on_download_complete, self.on_download_error)
@ -380,7 +381,7 @@ class Core(CorePluginBase):
def on_read_ip_range(start, end):
"""Add ip range to blocklist"""
# log.trace("Adding ip range %s - %s to ipfilter as blocked", start, end)
# log.trace('Adding ip range %s - %s to ipfilter as blocked', start, end)
self.blocklist.add_rule(start.address, end.address, BLOCK_RANGE)
self.num_blocked += 1
@ -422,7 +423,7 @@ class Core(CorePluginBase):
log.debug('Importing using reader: %s', self.reader)
log.debug('Reader type: %s compression: %s', self.config['list_type'], self.config['list_compression'])
log.debug('Clearing current ip filtering')
# self.blocklist.add_rule("0.0.0.0", "255.255.255.255", ALLOW_RANGE)
# self.blocklist.add_rule('0.0.0.0', '255.255.255.255', ALLOW_RANGE)
d = threads.deferToThread(self.reader(blocklist).read, on_read_ip_range)
d.addCallback(on_finish_read).addErrback(on_reader_failure)

View File

@ -106,7 +106,7 @@ class Core(CorePluginBase):
def log_error(result, command):
(stdout, stderr, exit_code) = result
if exit_code:
log.warn("Command '%s' failed with exit code %d", command, exit_code)
log.warn('Command "%s" failed with exit code %d', command, exit_code)
if stdout:
log.warn('stdout: %s', stdout)
if stderr:

View File

@ -121,7 +121,7 @@ class Core(CorePluginBase):
if file_ext_sec and file_ext_sec + file_ext in EXTRACT_COMMANDS:
file_ext = file_ext_sec + file_ext
elif file_ext not in EXTRACT_COMMANDS or file_ext_sec == '.tar':
log.debug("Can't extract file with unknown file type: %s", f['path'])
log.debug('Cannot extract file with unknown file type: %s', f['path'])
continue
elif file_ext == '.rar' and 'part' in file_ext_sec:
part_num = file_ext_sec.split('part')[1]

View File

@ -53,13 +53,11 @@ class CustomNotifications(object):
self._deregister_custom_provider(kind, eventtype)
def _handle_custom_providers(self, kind, eventtype, *args, **kwargs):
log.debug("Calling CORE's custom %s providers for %s: %s %s",
kind, eventtype, args, kwargs)
log.debug('Calling CORE custom %s providers for %s: %s %s', kind, eventtype, args, kwargs)
if eventtype in self.config['subscriptions'][kind]:
wrapper, handler = self.custom_notifications[kind][eventtype]
log.debug('Found handler for kind %s: %s', kind, handler)
custom_notif_func = getattr(self,
'handle_custom_%s_notification' % kind)
custom_notif_func = getattr(self, 'handle_custom_%s_notification' % kind)
d = defer.maybeDeferred(handler, *args, **kwargs)
d.addCallback(custom_notif_func, eventtype)
d.addCallback(self._on_notify_sucess, kind)

View File

@ -135,13 +135,11 @@ Date: %(date)s
try:
server.login(self.config['smtp_user'], self.config['smtp_pass'])
except smtplib.SMTPHeloError as ex:
err_msg = _("The server didn't reply properly to the helo "
'greeting: %s') % ex
err_msg = _('Server did not reply properly to HELO greeting: %s') % ex
log.error(err_msg)
return ex
except smtplib.SMTPAuthenticationError as ex:
err_msg = _("The server didn't accept the username/password "
'combination: %s') % ex
err_msg = _('Server refused username/password combination: %s') % ex
log.error(err_msg)
return ex
@ -149,8 +147,7 @@ Date: %(date)s
try:
server.sendmail(self.config['smtp_from'], to_addrs, message)
except smtplib.SMTPException as ex:
err_msg = _('There was an error sending the notification email:'
' %s') % ex
err_msg = _('There was an error sending the notification email: %s') % ex
log.error(err_msg)
return ex
finally:
@ -174,7 +171,7 @@ Date: %(date)s
subject = _('Finished Torrent "%(name)s"') % torrent_status
message = _(
'This email is to inform you that Deluge has finished '
'downloading \"%(name)s\", which includes %(num_files)i files.'
'downloading "%(name)s", which includes %(num_files)i files.'
'\nTo stop receiving these alerts, simply turn off email '
"notification in Deluge's preferences.\n\n"
'Thank you,\nDeluge.'
@ -183,7 +180,7 @@ Date: %(date)s
# d = defer.maybeDeferred(self.handle_custom_email_notification,
# [subject, message],
# "TorrentFinishedEvent")
# 'TorrentFinishedEvent')
# d.addCallback(self._on_notify_sucess, 'email')
# d.addErrback(self._on_notify_failure, 'email')
# return d

View File

@ -145,7 +145,7 @@ class GtkUiNotifications(CustomNotifications):
def handle_custom_blink_notification(self, result, eventtype):
if result:
return defer.maybeDeferred(self.__blink)
return defer.succeed("Won't blink. The returned value from the custom "
return defer.succeed('Will not blink. The returned value from the custom '
'handler was: %s' % result)
def handle_custom_sound_notification(self, result, eventtype):
@ -154,7 +154,7 @@ class GtkUiNotifications(CustomNotifications):
return defer.maybeDeferred(
self.__play_sound, self.config['custom_sounds'][eventtype])
return defer.maybeDeferred(self.__play_sound, result)
return defer.succeed("Won't play sound. The returned value from the "
return defer.succeed('Will not play sound. The returned value from the '
'custom handler was: %s' % result)
def __blink(self):
@ -222,7 +222,7 @@ class GtkUiNotifications(CustomNotifications):
'Got Torrent Status')
title = _('Finished Torrent')
torrent_status['num_files'] = torrent_status['file_progress'].count(1.0)
message = _('The torrent \"%(name)s\" including %(num_files)i file(s) '
message = _('The torrent "%(name)s" including %(num_files)i file(s) '
'has finished downloading.') % torrent_status
return title, message

View File

@ -40,7 +40,7 @@ class TestEmailNotifications(component.Component):
log.debug('\n\nEnabling %s', self.__class__.__name__)
for event in self.events:
if self.__imp == 'core':
# component.get("CorePlugin.Notifications").register_custom_email_notification(
# component.get('CorePlugin.Notifications').register_custom_email_notification(
component.get('Notifications').register_custom_email_notification(
event.__class__.__name__,
self.custom_email_message_provider

View File

@ -77,7 +77,7 @@ class Core(CorePluginBase):
self.length = self.config['length']
# self.stats = get_key(self.saved_stats, "stats") or {}
# self.stats = get_key(self.saved_stats, 'stats') or {}
self.stats_keys = []
self.add_stats(
'upload_rate',

View File

@ -113,7 +113,7 @@ import deluge.configmanager
from deluge.core.rpcserver import export
DEFAULT_PREFS = {
"test": "NiNiNi"
'test': 'NiNiNi'
}
log = logging.getLogger(__name__)
@ -121,7 +121,7 @@ log = logging.getLogger(__name__)
class Core(CorePluginBase):
def enable(self):
self.config = deluge.configmanager.ConfigManager("%(safe_name)s.conf", DEFAULT_PREFS)
self.config = deluge.configmanager.ConfigManager('%(safe_name)s.conf', DEFAULT_PREFS)
def disable(self):
pass
@ -171,15 +171,15 @@ class WebUIPlugin(PluginInitBase):
SETUP = """
from setuptools import setup, find_packages
__plugin_name__ = "%(name)s"
__author__ = "%(author_name)s"
__author_email__ = "%(author_email)s"
__version__ = "0.1"
__url__ = "%(url)s"
__license__ = "GPLv3"
__description__ = ""
__plugin_name__ = '%(name)s'
__author__ = '%(author_name)s'
__author_email__ = '%(author_email)s'
__version__ = '0.1'
__url__ = '%(url)s'
__license__ = 'GPLv3'
__description__ = ''
__long_description__ = \"\"\"\"\"\"
__pkg_data__ = {"deluge.plugins."+__plugin_name__.lower(): ["template/*", "data/*"]}
__pkg_data__ = {'deluge.plugins.'+__plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@ -192,7 +192,7 @@ setup(
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(),
namespace_packages=["deluge", "deluge.plugins"],
namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points=\"\"\"
@ -211,8 +211,8 @@ COMMON = """
def get_resource(filename):
import pkg_resources
import os
return pkg_resources.resource_filename("deluge.plugins.%(safe_name)s",
os.path.join("data", filename))
return pkg_resources.resource_filename('deluge.plugins.%(safe_name)s',
os.path.join('data', filename))
"""
GTKUI = """
@ -230,21 +230,21 @@ log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase):
def enable(self):
self.glade = gtk.glade.XML(get_resource("config.glade"))
self.glade = gtk.glade.XML(get_resource('config.glade'))
component.get("Preferences").add_page("%(name)s", self.glade.get_widget("prefs_box"))
component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs)
component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs)
component.get('Preferences').add_page('%(name)s', self.glade.get_widget('prefs_box'))
component.get('PluginManager').register_hook('on_apply_prefs', self.on_apply_prefs)
component.get('PluginManager').register_hook('on_show_prefs', self.on_show_prefs)
def disable(self):
component.get("Preferences").remove_page("%(name)s")
component.get("PluginManager").deregister_hook("on_apply_prefs", self.on_apply_prefs)
component.get("PluginManager").deregister_hook("on_show_prefs", self.on_show_prefs)
component.get('Preferences').remove_page('%(name)s')
component.get('PluginManager').deregister_hook('on_apply_prefs', self.on_apply_prefs)
component.get('PluginManager').deregister_hook('on_show_prefs', self.on_show_prefs)
def on_apply_prefs(self):
log.debug("applying prefs for %(name)s")
log.debug('applying prefs for %(name)s')
config = {
"test": self.glade.get_widget("txt_test").get_text()
'test': self.glade.get_widget('txt_test').get_text()
}
client.%(safe_name)s.set_config(config)
@ -252,8 +252,8 @@ class GtkUI(GtkPluginBase):
client.%(safe_name)s.get_config().addCallback(self.cb_get_config)
def cb_get_config(self, config):
"callback for on show_prefs"
self.glade.get_widget("txt_test").set_text(config["test"])
\"\"\"callback for on show_prefs\"\"\"
self.glade.get_widget('txt_test').set_text(config['test'])
"""
GLADE = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
@ -297,7 +297,7 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
scripts = [get_resource("%(safe_name)s.js")]
scripts = [get_resource('%(safe_name)s.js')]
def enable(self):
pass
@ -321,7 +321,7 @@ Copyright:
%(name)sPlugin = Ext.extend(Deluge.Plugin, {
constructor: function(config) {
config = Ext.apply({
name: "%(name)s"
name: '%(name)s'
}, config);
%(name)sPlugin.superclass.constructor.call(this, config);
},

View File

@ -17,7 +17,7 @@ class BaseTestCase(unittest.TestCase):
if len(component._ComponentRegistry.components) != 0:
warnings.warn('The component._ComponentRegistry.components is not empty on test setup.\n'
"This is probably caused by another test that didn't clean up after finishing!: %s" %
'This is probably caused by another test that did not clean up after finishing!: %s' %
component._ComponentRegistry.components)
d = maybeDeferred(self.set_up)

View File

@ -174,7 +174,7 @@ class ProcessOutputHandler(protocol.ProcessProtocol):
if 'cb' in trigger:
trigger['cb'](self, c['deferred'], data, self.log_output)
elif 'value' not in trigger:
raise Exception("Trigger must specify either 'cb' or 'value'")
raise Exception('Trigger must specify either "cb" or "value"')
else:
val = trigger['value'](self, data, self.log_output)
if trigger.get('type', 'callback') == 'errback':
@ -237,7 +237,7 @@ try:
daemon.start()
except:
import traceback
sys.stderr.write("Exception raised:\\n %%s" %% traceback.format_exc())
sys.stderr.write('Exception raised:\\n %%s' %% traceback.format_exc())
""" % (config_directory, listen_port, custom_script)
callbacks = []
default_core_cb = {'deferred': Deferred(), 'types': 'stdout'}
@ -247,7 +247,7 @@ except:
# Specify the triggers for daemon log output
default_core_cb['triggers'] = [
{'expr': 'Finished loading ', 'value': lambda reader, data, data_all: reader},
{'expr': "Couldn't listen on localhost:%d" % (listen_port), 'type': 'errback', # Error from libtorrent
{'expr': 'Could not listen on localhost:%d' % (listen_port), 'type': 'errback', # Error from libtorrent
'value': lambda reader, data, data_all: CannotListenError('localhost', listen_port,
'Could not start deluge test client!\n%s' % data)},
{'expr': 'Traceback', 'type': 'errback',

View File

@ -107,4 +107,4 @@ class CommonTestCase(unittest.TestCase):
for human_size, byte_size in sizes:
parsed = parse_human_size(human_size)
self.assertEquals(parsed, byte_size, "Mismatch when converting '%s'" % human_size)
self.assertEquals(parsed, byte_size, 'Mismatch when converting: %s' % human_size)

View File

@ -221,8 +221,8 @@ class ComponentTestClass(BaseTestCase):
result = yield component.start()
self.failUnlessEqual([(result[0][0], result[0][1].value)],
[(defer.FAILURE,
component.ComponentException("Trying to start a component ('%s') not in "
"stopped state. Current state: '%s'" %
component.ComponentException('Trying to start component "%s" but it is '
'not in a stopped state. Current state: %s' %
('test_pause_c1', 'Paused'), ''))])
def test_shutdown(self):

View File

@ -244,8 +244,8 @@ class CoreTestCase(BaseTestCase):
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
val = yield self.core.remove_torrents(['invalidid1', 'invalidid2', torrent_id], False)
self.assertEqual(len(val), 2)
self.assertEqual(val[0], ('invalidid1', "torrent_id 'invalidid1' not in session."))
self.assertEqual(val[1], ('invalidid2', "torrent_id 'invalidid2' not in session."))
self.assertEqual(val[0], ('invalidid1', 'torrent_id invalidid1 not in session.'))
self.assertEqual(val[1], ('invalidid2', 'torrent_id invalidid2 not in session.'))
def test_get_session_status(self):
status = self.core.get_session_status(['upload_rate', 'download_rate'])

View File

@ -67,7 +67,7 @@ class PartialDownloadResource(Resource):
self.render_count = 0
def render(self, request):
# encoding = request.requestHeaders._rawHeaders.get("accept-encoding", None)
# encoding = request.requestHeaders._rawHeaders.get('accept-encoding', None)
if self.render_count == 0:
request.setHeader('content-length', '5')
else:

View File

@ -149,7 +149,7 @@ class RPCRaiseDelugeErrorJSONTestCase(JSONBase):
class TestClass(object):
@export()
def test(self):
raise DelugeError("DelugeERROR")
raise DelugeError('DelugeERROR')
test = TestClass()
daemon.rpcserver.register_object(test)
@ -199,7 +199,7 @@ class JSONRequestFailedTestCase(JSONBase, WebServerMockBase):
@export()
def test(self):
def test_raise_error():
raise DelugeError("DelugeERROR")
raise DelugeError('DelugeERROR')
return task.deferLater(reactor, 1, test_raise_error)

View File

@ -91,7 +91,7 @@ class TransferTestClass(DelugeTransferProtocol):
(len(data), len(data) - len(dobj.unused_data), len(dobj.unused_data)))
print('Packet count:', self.packet_count)
except Exception as ex:
# log.debug("Received possible invalid message (%r): %s", data, e)
# 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
@ -307,9 +307,9 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
# Needs file containing big data structure e.g. like thetorrent list as it is transfered by the daemon
# def test_simulate_big_transfer(self):
# filename = "../deluge.torrentlist"
# filename = '../deluge.torrentlist'
#
# f = open(filename, "r")
# f = open(filename, 'r')
# data = f.read()
# message_to_send = eval(data)
# self.transfer.transfer_message(message_to_send)
@ -331,7 +331,7 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
# self.assertTrue(transfered_message == message_to_send)
#
# f.close()
# f = open("rencode.torrentlist", "w")
# f = open('rencode.torrentlist', 'w')
# f.write(str(transfered_message))
# f.close()

View File

@ -38,7 +38,7 @@ sys_stdout = sys.stdout
# the file descriptors in sys and argparse._sys with StringFileDescriptor.
# Regular print statements from such tests will therefore write to the
# StringFileDescriptor object instead of the terminal.
# To print to terminal from the tests, use: print("Message...", file=sys_stdout)
# To print to terminal from the tests, use: print('Message...', file=sys_stdout)
class StringFileDescriptor(object):
@ -71,7 +71,7 @@ class UIBaseTestCase(object):
def exec_command(self):
if DEBUG_COMMAND:
print("Executing: '%s'\n" % sys.argv, file=sys_stdout)
print('Executing: %s\n' % sys.argv, file=sys_stdout)
return self.var['start_cmd']()

View File

@ -47,7 +47,7 @@ class WebServerTestCase(WebServerTestBase, WebServerMockBase):
try:
body = yield twisted.web.client.readBody(d)
except AttributeError:
raise SkipTest("This test requires 't.w.c.readBody()' in Twisted version >= 13.2")
raise SkipTest('This test requires "t.w.c.readBody()" in Twisted version >= 13.2')
json = json_lib.loads(body)
self.assertEqual(None, json['error'])

View File

@ -21,7 +21,7 @@ parts.
>>> import PIL.Image
>>> import Win32IconImagePlugin
>>> ico = PIL.Image.open("down.ico")
>>> ico = PIL.Image.open('down.ico')
>>> print ico.info['sizes']
set([(16, 16), (48, 48), (256, 256), (32, 32)])
>>> ico.size = (16, 16)

View File

@ -104,7 +104,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
if message_type == RPC_EVENT:
event = request[1]
# log.debug("Received RPCEvent: %s", event)
# log.debug('Received RPCEvent: %s', event)
# A RPCEvent was received from the daemon so run any handlers
# associated with it.
if event in self.factory.event_handlers:
@ -178,7 +178,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
# response to this request. We use the extra information when printing
# out the error for debugging purposes.
self.__rpc_requests[request.request_id] = request
# log.debug("Sending RPCRequest %s: %s", request.request_id, request)
# 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 as ex:
@ -453,7 +453,7 @@ class DaemonStandaloneProxy(DaemonProxy):
self.__daemon = None
def call(self, method, *args, **kwargs):
# log.debug("call: %s %s %s", method, args, kwargs)
# log.debug('call: %s %s %s', method, args, kwargs)
import copy
@ -503,7 +503,7 @@ class DottedObject(object):
self.base = method
def __call__(self, *args, **kwargs):
raise Exception("You must make calls in the form of 'component.method'!")
raise Exception('You must make calls in the form of "component.method"')
def __getattr__(self, name):
return RemoteMethod(self.daemon, self.base + '.' + name)
@ -637,8 +637,9 @@ class Client(object):
except OSError as ex:
from errno import 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."))
log.error(
_('Deluge cannot find the `deluged` executable, check that '
'the deluged package is installed, or added to your PATH.'))
else:
log.exception(ex)
raise ex

View File

@ -109,7 +109,7 @@ class Commander(object):
return
except OptionParserError as ex:
import traceback
log.warn("Error parsing command '%s': %s", args, ex)
log.warn('Error parsing command "%s": %s', args, ex)
self.write('{!error!} %s' % ex)
parser.print_help()
return

View File

@ -65,7 +65,7 @@ class Command(BaseCommand):
torrent = url2pathname(urlparse(torrent).path)
path = os.path.abspath(os.path.expanduser(torrent))
if not os.path.exists(path):
self.console.write("{!error!}%s doesn't exist!" % path)
self.console.write('{!error!}%s does not exist!' % path)
continue
if not os.path.isfile(path):
self.console.write('{!error!}This is a directory!')

View File

@ -122,7 +122,7 @@ class Command(BaseCommand):
return
if key not in config.keys():
self.console.write("{!error!}The key '%s' is invalid!" % key)
self.console.write('{!error!}Invalid key: %s' % key)
return
if not isinstance(config[key], type(val)):
@ -135,7 +135,7 @@ class Command(BaseCommand):
def on_set_config(result):
self.console.write('{!success!}Configuration value successfully updated.')
self.console.write("Setting '%s' to '%s'" % (key, val))
self.console.write('Setting "%s" to: %s' % (key, val))
return client.core.set_config({key: val}).addCallback(on_set_config)
def complete(self, text):

View File

@ -54,7 +54,7 @@ class Command(BaseCommand):
cmds_doc += parser.formatter.format_colors(cmd_doc)
self.console.write(cmds_doc)
self.console.write(' ')
self.console.write("For help on a specific command, use '<command> --help'")
self.console.write('For help on a specific command, use `<command> --help`')
self.console.set_batch_write(False)
return deferred

View File

@ -94,7 +94,7 @@ class Command(BaseCommand):
torrent_ids = self.console.match_torrent(options.torrent)
if key not in torrent_options:
self.console.write("{!error!}The key '%s' is invalid!" % key)
self.console.write('{!error!}Invalid key: %s' % key)
return
val = torrent_options[key](val)

View File

@ -20,7 +20,7 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
help=_("One or more torrent ids. '*' pauses all torrents"))
help=_('One or more torrent ids. Use "*" to pause all torrents'))
def handle(self, options):
self.console = component.get('ConsoleUI')

View File

@ -20,7 +20,7 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
help=_("One or more torrent ids. '*' resumes all torrents"))
help=_('One or more torrent ids. Use "*" to resume all torrents'))
def handle(self, options):
self.console = component.get('ConsoleUI')

View File

@ -23,7 +23,8 @@ class Command(BaseCommand):
aliases = ['del']
def add_arguments(self, parser):
parser.add_argument('--remove_data', action='store_true', default=False, help=_("remove the torrent's data"))
parser.add_argument('--remove_data', action='store_true', default=False,
help=_('Also removes the torrent data'))
parser.add_argument('-c', '--confirm', action='store_true', default=False,
help=_('List the matching torrents without removing.'))
parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids'))

View File

@ -25,10 +25,10 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('-r', '--raw', action='store_true', default=False, dest='raw',
help=_("Don't format upload/download rates in KiB/s "
help=_('Raw values for upload/download rates (without KiB/s suffix)'
'(useful for scripts that want to do their own parsing)'))
parser.add_argument('-n', '--no-torrents', action='store_false', default=True, dest='show_torrents',
help=_("Don't show torrent status (this will make the command a bit faster)"))
help=_('Do not show torrent status (Improves command speed)'))
def handle(self, options):
self.console = component.get('ConsoleUI')

View File

@ -249,10 +249,10 @@ Please use commands from the command line, e.g.:\n
return mode
def set_mode(self, mode_name, refresh=False):
log.debug("Setting console mode '%s'", mode_name)
log.debug('Setting console mode: %s', mode_name)
mode = self.modes.get(mode_name, None)
if mode is None:
log.error("Non-existent mode requested: '%s'", mode_name)
log.error('Non-existent mode requested: %s', mode_name)
return
self.stdscr.erase()
@ -268,7 +268,7 @@ Please use commands from the command line, e.g.:\n
# which can cause issues as the popup's screen will not be destroyed.
# This can lead to the popup border being visible for short periods
# while the current modes' screen is repainted.
log.error("Mode '%s' still has popups available after being paused."
log.error('Mode "%s" still has popups available after being paused.'
' Ensure all popups are removed on pause!', mode.popup.title)
d.addCallback(on_mode_paused, self.active_mode)
reactor.removeReader(self.active_mode)

View File

@ -28,7 +28,7 @@ def _bracket_fixup(path):
while path.find(unichr(sentinal)) != -1:
sentinal += 1
if sentinal > 65535:
log.error("Can't fix brackets in path, path contains all possible sentinal characters")
log.error('Cannot fix brackets in path, path contains all possible sentinal characters')
return path
newpath = path.replace(']', unichr(sentinal))
newpath = newpath.replace('[', '[[]')
@ -53,7 +53,7 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress):
ress['total'] = num_files
if num_files <= 0:
fail_cb("Doesn't exist", t_file, ress)
fail_cb('Does not exist', t_file, ress)
for f in files:
if is_url:
@ -62,7 +62,7 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress):
client.core.add_torrent_magnet(f, t_options).addCallback(success_cb, f, ress).addErrback(fail_cb, f, ress)
else:
if not os.path.exists(f):
fail_cb("Doesn't exist", f, ress)
fail_cb('Does not exist', f, ress)
continue
if not os.path.isfile(f):
fail_cb('Is a directory', f, ress)

View File

@ -189,7 +189,7 @@ class BaseMode(CursesStdIO, component.Component):
self.draw_statusbars()
# Update the status bars
self.add_string(1, "{!info!}Base Mode (or subclass hasn't overridden refresh)")
self.add_string(1, '{!info!}Base Mode (or subclass has not overridden refresh)')
self.stdscr.redrawwin()
self.stdscr.refresh()
@ -287,8 +287,8 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=' ', tri
screen.addstr(row, col, s, color)
except curses.error as ex:
import traceback
log.warn("FAILED on call screen.addstr(%s, %s, '%s', %s) - max_y: %s, max_x: %s, "
"curses.LINES: %s, curses.COLS: %s, Error: '%s', trace:\n%s",
log.warn('FAILED on call screen.addstr(%s, %s, "%s", %s) - max_y: %s, max_x: %s, '
'curses.LINES: %s, curses.COLS: %s, Error: %s, trace:\n%s',
row, col, s, color, max_y, max_x, curses.LINES, curses.COLS, ex,
''.join(traceback.format_stack(limit=5)))
@ -333,5 +333,5 @@ def move_cursor(screen, row, col):
screen.move(row, col)
except curses.error as ex:
import traceback
log.warn("Error on screen.move(%s, %s): (curses.LINES: %s, curses.COLS: %s) Error: '%s'\nStack: %s",
log.warn('Error on screen.move(%s, %s): (curses.LINES: %s, curses.COLS: %s) Error: %s\nStack: %s',
row, col, curses.LINES, curses.COLS, ex, ''.join(traceback.format_stack()))

View File

@ -788,7 +788,7 @@ class CmdLine(BaseMode, Commander):
# Let's avoid listing all torrents twice if there's no pattern
if not empty and torrent_id.startswith(line):
# Highlight the matching part
text = "{!info!}%s{!input!}%s - '%s'" % (torrent_id[:l], torrent_id[l:], torrent_name)
text = '{!info!}%s{!input!}%s - "%s"' % (torrent_id[:l], torrent_id[l:], torrent_name)
possible_matches.append(text)
if torrent_name.startswith(line):
text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (

View File

@ -128,13 +128,13 @@ class ConnectionManager(BaseMode, PopupsHandler):
try:
port = int(result['port']['value'])
except ValueError:
self.report_message("Can't add host", 'Invalid port. Must be an integer')
self.report_message('Cannot add host', 'Invalid port. Must be an integer')
return
username = result['username']['value']
password = result['password']['value']
for host in self.config['hosts']:
if (host[1], host[2], host[3]) == (hostname, port, username):
self.report_message("Can't add host", 'Host already in list')
self.report_message('Cannot add host', 'Host already in list')
return
newid = hashlib.sha1(str(time.time())).hexdigest()
self.config['hosts'].append((newid, hostname, port, username, password))

View File

@ -286,7 +286,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
fl = s[3]
fe[0] = new_folder.strip('/').rpartition('/')[-1]
# self.__get_file_by_name(old_folder, self.file_list)[0] = new_folder.strip("/")
# self.__get_file_by_name(old_folder, self.file_list)[0] = new_folder.strip('/')
component.get('SessionProxy').get_torrent_status(
self.torrentid, self._status_keys).addCallback(self.set_state)
@ -763,8 +763,8 @@ class TorrentDetail(BaseMode, PopupsHandler):
# Perhaps in the future: Renaming multiple files
if self.marked:
self.report_message('Error (Enter to close)',
"Sorry, you can't rename multiple files, please clear "
"selection with {!info!}'c'{!normal!} key")
'Sorry, you cannot rename multiple files, please clear '
'selection with {!info!}"c"{!normal!} key')
else:
_file = self.__get_file_by_num(self.current_file_idx, self.file_list)
old_filename = _file[0]

View File

@ -191,7 +191,7 @@ def parse_color_string(s, encoding='UTF-8'):
end = s.find('!}')
if end == -1:
raise BadColorString("Missing closing '!}'")
raise BadColorString('Missing closing "!}"')
# Get a list of attributes in the bracketed section
attrs = s[begin + 2:end].split(',')
@ -218,7 +218,7 @@ def parse_color_string(s, encoding='UTF-8'):
if attrs[0] in schemes:
pair = (schemes[attrs[0]][0], schemes[attrs[0]][1])
if pair not in color_pairs:
log.debug("Color pair doesn't exist: %s, attrs: %s", pair, attrs)
log.debug('Color pair does not exist: %s, attrs: %s', pair, attrs)
pair = ('white', 'black')
# Get the color pair number
color_pair = curses.color_pair(color_pairs[pair])
@ -248,7 +248,7 @@ def parse_color_string(s, encoding='UTF-8'):
# terminal settings allows no colors. If background is white, we
# assume this means selection, and use "white", "black" + reverse
# To have white background and black foreground
log.debug("Color pair doesn't exist: %s", pair)
log.debug('Color pair does not exist: %s', pair)
if pair[1] == 'white':
if attrs[2] == 'ignore':
attrs[2] = 'reverse'

View File

@ -257,7 +257,7 @@ def pad_string(string, length, character=' ', side='right'):
return '%s%s' % (string, character * diff)
def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/"):
def delete_alt_backspace(input_text, input_cursor, sep_chars=' *?!._~-#$^;\'"/'):
"""
Remove text from input_text on ALT+backspace
Stop removing when countering any of the sep chars

View File

@ -885,7 +885,7 @@ class ComboInput(InputField):
msg = c[1]
break
if msg is None:
log.warn("Setting a value '%s' found found in choices: %s", val, self.choices)
log.warn('Setting value "%s" found nothing in choices: %s', val, self.choices)
self.fmt_keys.update({'msg': msg})

View File

@ -48,7 +48,7 @@ class BaseInputPane(InputKeyHandler):
self.last_lineoff_move = 0
if not hasattr(self, 'visible_content_pane_height'):
log.error("The class '%s' does not have the attribute '%s' required by super class '%s'",
log.error('The class "%s" does not have the attribute "%s" required by super class "%s"',
self.__class__.__name__, 'visible_content_pane_height', BaseInputPane.__name__)
raise AttributeError('visible_content_pane_height')
@ -81,7 +81,7 @@ class BaseInputPane(InputKeyHandler):
continue
if e.name == input_element.name:
import traceback
log.warn("Input element with name '%s' already exists in input pane (%s):\n%s",
log.warn('Input element with name "%s" already exists in input pane (%s):\n%s',
input_element.name, e, ''.join(traceback.format_stack(limit=5)))
return

View File

@ -148,5 +148,5 @@ class BaseWindow(object):
self.screen.noutrefresh(pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol)
except curses.error as ex:
import traceback
log.warn("Error on screen.noutrefresh(%s, %s, %s, %s, %s, %s) Error: '%s'\nStack: %s",
log.warn('Error on screen.noutrefresh(%s, %s, %s, %s, %s, %s) Error: %s\nStack: %s',
pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol, ex, ''.join(traceback.format_stack()))

View File

@ -163,7 +163,7 @@ class AboutDialog(object):
'Pål-Eivind Johnsen', 'pano', 'Paolo Naldini', 'Paracelsus',
'Patryk13_03', 'Patryk Skorupa', 'PattogoTehen', 'Paul Lange',
'Pavcio', 'Paweł Wysocki', 'Pedro Brites Moita',
'Pedro Clemente Pereira Neto', 'Pekka \"PEXI\" Niemistö', 'Penegal',
'Pedro Clemente Pereira Neto', 'Pekka "PEXI" Niemistö', 'Penegal',
'Penzo', 'perdido', 'Peter Kotrcka', 'Peter Skov',
'Peter Van den Bosch', 'Petter Eklund', 'Petter Viklund',
'phatsphere', 'Phenomen', 'Philipi', 'Philippides Homer', 'phoenix',

View File

@ -223,7 +223,7 @@ def associate_magnet_links(overwrite=False):
gconf_client = gconf.client_get_default()
if (gconf_client.get(key) and overwrite) or not gconf_client.get(key):
# We are either going to overwrite the key, or do it if it hasn't been set yet
if gconf_client.set_string(key, "deluge '%s'"):
if gconf_client.set_string(key, 'deluge "%s"'):
gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/needs_terminal', False)
gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/enabled', True)
log.info('Deluge registered as default magnet uri handler!')

View File

@ -334,7 +334,7 @@ class ConnectionManager(component.Component):
self.__update_buttons()
row[HOSTLIST_COL_STATUS] = 'Connected'
log.debug("Query daemon's info")
log.debug('Query daemon info')
client.daemon.info().addCallback(on_info, row)
continue
@ -455,9 +455,9 @@ class ConnectionManager(component.Component):
if ex.errno == ENOENT:
ErrorDialog(
_('Unable to start daemon!'),
_("Deluge cannot find the 'deluged' executable, it is "
'likely that you forgot to install the deluged package '
"or it's not in your PATH.")).run()
_('Deluge cannot find the `deluged` executable, check that '
'the deluged package is installed, or added to your PATH.')).run()
return False
else:
raise ex

View File

@ -325,7 +325,7 @@ class FilesTab(Tab):
for select in selected:
path = self.get_file_path(select).split('/')
filepath = os.path.join(status['download_location'], *path)
log.debug("Open file '%s'", filepath)
log.debug('Open file: %s', filepath)
timestamp = gtk.get_current_event_time()
open_file(filepath, timestamp=timestamp)
@ -338,7 +338,7 @@ class FilesTab(Tab):
for select in selected:
path = self.get_file_path(select).split('/')
filepath = os.path.join(status['download_location'], *path)
log.debug("Show file '%s'", filepath)
log.debug('Show file: %s', filepath)
timestamp = gtk.get_current_event_time()
show_file(filepath, timestamp=timestamp)

View File

@ -143,18 +143,18 @@ class GtkUI(object):
# Setup signals
def on_die(*args):
log.debug("OS signal 'die' caught with args: %s", args)
log.debug('OS signal "die" caught with args: %s', args)
reactor.stop()
if windows_check():
from win32api import SetConsoleCtrlHandler
SetConsoleCtrlHandler(on_die, True)
log.debug("Win32 'die' handler registered")
log.debug('Win32 "die" handler registered')
elif osx_check() and WINDOWING == 'quartz':
import gtkosx_application
self.osxapp = gtkosx_application.gtkosx_application_get()
self.osxapp.connect('NSApplicationWillTerminate', on_die)
log.debug("OSX quartz 'die' handler registered")
log.debug('OSX quartz "die" handler registered')
# Set process name again to fix gtk issue
setproctitle(getproctitle())
@ -227,7 +227,7 @@ class GtkUI(object):
reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)
def gtkui_sigint_handler(num, frame):
log.debug("SIGINT signal caught - firing event: 'gtkui_close'")
log.debug('SIGINT signal caught, firing event: gtkui_close')
reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')
signal.signal(signal.SIGINT, gtkui_sigint_handler)

View File

@ -117,7 +117,7 @@ class IPCInterface(component.Component):
log.debug('Checking if lockfile exists: %s', lockfile)
if os.path.lexists(lockfile):
def delete_lockfile():
log.debug("Removing lockfile since it's stale.")
log.debug('Delete stale lockfile.')
try:
os.remove(lockfile)
os.remove(socket)

View File

@ -71,7 +71,7 @@ class MainWindow(component.Component):
def patched_connect_signals(*a, **k):
raise RuntimeError('In order to connect signals to this GtkBuilder instance please use '
"'component.get(\"MainWindow\").connect_signals()'")
'"component.get(\'MainWindow\').connect_signals()"')
self.main_builder.connect_signals = patched_connect_signals
# Get Gtk Builder files Main Window, New release dialog, and Tabs.

View File

@ -69,7 +69,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
try:
self.enable_plugin(name)
except Exception as ex:
log.warn("Failed to enable plugin '%s': ex: %s", name, ex)
log.warn('Failed to enable plugin "%s": ex: %s', name, ex)
self.run_on_show_prefs()

View File

@ -862,7 +862,7 @@ class Preferences(component.Component):
def on_plugin_action(arg):
if not value and arg is False:
log.warn("Failed to enable plugin '%s'", name)
log.warn('Failed to enable plugin: %s', name)
self.plugin_liststore.set_value(row, 1, False)
d.addBoth(on_plugin_action)

View File

@ -566,7 +566,7 @@ class TorrentView(ListView, component.Component):
def mark_dirty(self, torrent_id=None):
for row in self.liststore:
if not torrent_id or row[self.columns['torrent_id'].column_indices[0]] == torrent_id:
# log.debug("marking %s dirty", torrent_id)
# log.debug('marking %s dirty', torrent_id)
row[self.columns['dirty'].column_indices[0]] = True
if torrent_id:
break

View File

@ -289,7 +289,7 @@ class TrackerIcons(Component):
try:
os.remove(page)
except OSError as ex:
log.warning("Couldn't remove temp file: %s", ex)
log.warning('Could not remove temp file: %s', ex)
return parser.get_icons()

View File

@ -99,16 +99,16 @@ def start_ui():
try:
ui = ui_entrypoints[selected_ui](prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args)
except KeyError as ex:
log.error("Unable to find chosen UI: '%s'. Please choose a different UI "
"or use '--set-default-ui' to change default UI.", selected_ui)
log.error('Unable to find chosen UI: "%s". Please choose a different UI '
'or use "--set-default-ui" to change default UI.', selected_ui)
except ImportError as ex:
import traceback
error_type, error_value, tb = sys.exc_info()
stack = traceback.extract_tb(tb)
last_frame = stack[-1]
if last_frame[0] == __file__:
log.error("Unable to find chosen UI: '%s'. Please choose a different UI "
"or use '--set-default-ui' to change default UI.", selected_ui)
log.error('Unable to find chosen UI: "%s". Please choose a different UI '
'or use "--set-default-ui" to change default UI.', selected_ui)
else:
log.exception(ex)
log.error('Encountered an error launching the request UI: %s', selected_ui)

View File

@ -24,7 +24,7 @@ def set_dummy_trans(warn_msg=None):
def _func(*txt):
if warn_msg:
log.warn("'%s' has been marked for translation, but translation is unavailable.", txt[0])
log.warn('"%s" has been marked for translation, but translation is unavailable.', txt[0])
return txt[0]
__builtin__.__dict__['_'] = _func
__builtin__.__dict__['_n'] = _func

View File

@ -798,7 +798,7 @@ class WebApi(JSONComponent):
main_deferred = Deferred()
host = self._get_host(host_id)
if not host:
main_deferred.callback((False, _("Daemon doesn't exist")))
main_deferred.callback((False, _('Daemon does not exist')))
return main_deferred
try:
@ -895,7 +895,7 @@ class WebApi(JSONComponent):
web_config = component.get('DelugeWeb').config
for key in config.keys():
if key in ['sessions', 'pwd_salt', 'pwd_sha1']:
log.warn("Ignored attempt to overwrite web config key '%s'", key)
log.warn('Ignored attempt to overwrite web config key: %s', key)
continue
if isinstance(config[key], basestring):
config[key] = config[key].encode('utf8')

View File

@ -59,7 +59,7 @@ class PluginManager(PluginManagerBase, component.Component):
try:
plugin = component.get('WebPlugin.' + name)
except KeyError:
log.debug("'%s' plugin contains no WebUI code, ignoring WebUI disable call.", name)
log.debug('%s plugin contains no WebUI code, ignoring WebUI disable call.', name)
return
info = gather_info(plugin)
@ -81,7 +81,7 @@ class PluginManager(PluginManagerBase, component.Component):
try:
plugin = component.get('WebPlugin.' + name)
except KeyError:
log.info("'%s' plugin contains no WebUI code, ignoring WebUI enable call.", name)
log.info('%s plugin contains no WebUI code, ignoring WebUI enable call.', name)
return
info = gather_info(plugin)

View File

@ -219,7 +219,7 @@ class LookupResource(resource.Resource, component.Component):
return self
def render(self, request):
log.debug("Requested path: '%s'", request.lookup_path)
log.debug('Requested path: %s', request.lookup_path)
path = os.path.dirname(request.lookup_path)
if path not in self.__paths:
@ -230,7 +230,7 @@ class LookupResource(resource.Resource, component.Component):
for directory in self.__paths[path]:
if os.path.join(directory, filename):
path = os.path.join(directory, filename)
log.debug("Serving path: '%s'", path)
log.debug('Serving path: %s', path)
mime_type = mimetypes.guess_type(path)
request.setHeader('content-type', mime_type[0])
with open(path, 'rb') as _file:
@ -373,7 +373,7 @@ class ScriptResource(resource.Resource, component.Component):
return self
def render(self, request):
log.debug("Requested path: '%s'", request.lookup_path)
log.debug('Requested path: %s', request.lookup_path)
for script_type in ('dev', 'debug', 'normal'):
scripts = self.__scripts[script_type]['scripts']
@ -390,7 +390,7 @@ class ScriptResource(resource.Resource, component.Component):
if not os.path.isfile(path):
continue
log.debug("Serving path: '%s'", path)
log.debug('Serving path: %s', path)
mime_type = mimetypes.guess_type(path)
request.setHeader('content-type', mime_type[0])
with open(path, 'rb') as _file:
@ -517,13 +517,13 @@ class TopLevel(resource.Resource):
if not self.js.has_script_type_files(script_type):
if not dev_ver:
log.warning("Failed to enable WebUI '%s' mode, script files are missing!", script_type)
log.warning('Failed to enable WebUI "%s" mode, script files are missing!', script_type)
# Fallback to checking other types in order and selecting first with files available.
for alt_script_type in [x for x in ['normal', 'debug', 'dev'] if x != script_type]:
if self.js.has_script_type_files(alt_script_type):
script_type = alt_script_type
if not dev_ver:
log.warning("WebUI falling back to '%s' mode.", script_type)
log.warning('WebUI falling back to "%s" mode.', script_type)
break
scripts = component.get('Scripts').get_scripts(script_type)
@ -592,7 +592,7 @@ class DelugeWeb(component.Component):
self.plugins = PluginManager()
def _on_language_changed(self, key, value):
log.debug("Setting UI language '%s'", value)
log.debug('Setting UI language %s', value)
lang.set_language(value)
def install_signal_handlers(self):

View File

@ -58,7 +58,7 @@ def check_missing_markup(js_dir):
for match in string_re.finditer(line):
for string in match.groups():
# Ignore string that contains only digits or specificied strings in skip.
if not string or string.split("'")[1].isdigit() or any(x in string for x in skip):
if not string or string.split('\'')[1].isdigit() or any(x in string for x in skip):
continue
locations = strings.get(string, [])
locations.append((os.path.join(root, filename), str(lineno + 1)))
@ -97,7 +97,7 @@ def create_gettext_js(js_dir):
if __name__ == '__main__':
gettext_fname = create_gettext_js(WEBUI_JS_DIR)
print("Created '%s'" % gettext_fname)
print('Created: %s' % gettext_fname)
missed_markup = check_missing_markup(WEBUI_JS_DIR)
if missed_markup:
print('Possible missed text for translation markup:')

View File

@ -209,7 +209,7 @@ def main():
# do it
if not args:
print('No input file given', file=sys.stderr)
print("Try `msgfmt --help' for more information.", file=sys.stderr)
print('Try `msgfmt --help` for more information.', file=sys.stderr)
return
for filename in args:

View File

@ -237,7 +237,7 @@ class Build(_build):
class InstallData(_install_data):
"""Custom class to fix 'setup install' copying data files to incorrect location. (Bug #1389)"""
"""Custom class to fix `setup install` copying data files to incorrect location. (Bug #1389)"""
def finalize_options(self):
self.install_dir = None
@ -274,12 +274,12 @@ class CleanPlugins(cmd.Command):
# Delete the .eggs
if path[-4:] == '.egg':
print("Deleting egg file '%s'" % path)
print('Deleting egg file "%s"' % path)
os.remove(path)
# Delete the .egg-link
if path[-9:] == '.egg-link':
print("Deleting egg link '%s'" % path)
print('Deleting egg link "%s"' % path)
os.remove(path)
egg_info_dir_path = 'deluge/plugins/*/*.egg-info'