Permalink
Browse files

2to3 on event manager and smaller fixes

* runs with python3 without instant death
  • Loading branch information...
1 parent b68ee81 commit c5c5b17d434202250ef8ffad11530c278e27309d @keis keis committed Feb 19, 2012
View
11 Makefile
@@ -17,7 +17,8 @@ else
CPPFLAGS =
endif
-PYTHON=$(shell if which python2 > /dev/null; then echo python2; else echo python; fi)
+#PYTHON=$(shell if which python2 > /dev/null; then echo python2; else echo python; fi)
+PYTHON=python3
PYTHONV=$(shell $PYTHON --version | sed -n /[0-9].[0-9]/p)
# --- configuration ends here ---
@@ -98,16 +99,16 @@ test-uzbl-core-sandbox: sandbox uzbl-core sandbox-install-uzbl-core sandbox-inst
rm -rf ./sandbox/usr
test-uzbl-browser-sandbox: sandbox uzbl-browser sandbox-install-uzbl-browser sandbox-install-example-data
- . ./sandbox/env.sh && python -S `which uzbl-event-manager` restart -avv
+ . ./sandbox/env.sh && ${PYTHON} -S `which uzbl-event-manager` restart -navv &
. ./sandbox/env.sh && uzbl-browser --uri http://www.uzbl.org --verbose
- . ./sandbox/env.sh && python -S `which uzbl-event-manager` stop -vv -o /dev/null
+ . ./sandbox/env.sh && ${PYTHON} -S `which uzbl-event-manager` stop -vv -o /dev/null
make DESTDIR=./sandbox uninstall
rm -rf ./sandbox/usr
test-uzbl-tabbed-sandbox: sandbox uzbl-browser sandbox-install-uzbl-browser sandbox-install-uzbl-tabbed sandbox-install-example-data
- . ./sandbox/env.sh && python -S `which uzbl-event-manager` restart -avv
+ . ./sandbox/env.sh && ${PYTHON} -S `which uzbl-event-manager` restart -avv
. ./sandbox/env.sh && uzbl-tabbed
- . ./sandbox/env.sh && python -S `which uzbl-event-manager` stop -ivv
+ . ./sandbox/env.sh && ${PYTHON} -S `which uzbl-event-manager` stop -ivv
make DESTDIR=./sandbox uninstall
rm -rf ./sandbox/usr
View
2 misc/env.sh
@@ -29,7 +29,7 @@ export XDG_CONFIG_HOME
PATH="$(pwd)/sandbox/usr/local/bin:$PATH"
export PATH
-PYTHONLIB=$(python -c 'from distutils.sysconfig import get_python_lib; print get_python_lib(prefix="/usr/local")')
+PYTHONLIB=$(python3 -c 'from distutils.sysconfig import get_python_lib; print(get_python_lib(prefix="/usr/local"))')
UZBL_PLUGIN_PATH="$(pwd)/sandbox/$PYTHONLIB/uzbl/plugins"
export UZBL_PLUGIN_PATH
View
20 tests/event-manager/testarguments.py
@@ -7,19 +7,19 @@
class ArgumentsTest(unittest.TestCase):
def test_empty(self):
a = Arguments('')
- self.assertEquals(len(a), 0)
- self.assertEquals(a.raw(), '')
+ self.assertEqual(len(a), 0)
+ self.assertEqual(a.raw(), '')
def test_space(self):
a = Arguments(' foo bar')
- self.assertEquals(len(a), 2)
- self.assertEquals(a.raw(), 'foo bar')
- self.assertEquals(a.raw(0, 0), 'foo')
- self.assertEquals(a.raw(1, 1), 'bar')
+ self.assertEqual(len(a), 2)
+ self.assertEqual(a.raw(), 'foo bar')
+ self.assertEqual(a.raw(0, 0), 'foo')
+ self.assertEqual(a.raw(1, 1), 'bar')
def test_tab(self):
a = Arguments('\tfoo\t\tbar')
- self.assertEquals(len(a), 2)
- self.assertEquals(a.raw(), 'foo\t\tbar')
- self.assertEquals(a.raw(0, 0), 'foo')
- self.assertEquals(a.raw(1, 1), 'bar')
+ self.assertEqual(len(a), 2)
+ self.assertEqual(a.raw(), 'foo\t\tbar')
+ self.assertEqual(a.raw(0, 0), 'foo')
+ self.assertEqual(a.raw(1, 1), 'bar')
View
2 tests/event-manager/testbind.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-from __future__ import print_function
+
import sys
if '' not in sys.path:
View
16 tests/event-manager/testcompletion.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# vi: set et ts=4:
-from __future__ import print_function
+
import unittest
from emtest import EventManagerMock
@@ -54,23 +54,23 @@ def test_incomplete_keyword(self):
k.keylet.cursor = len(k.keylet.keycmd)
r = c.get_incomplete_keyword()
- self.assertEquals(r, ('sp', False))
+ self.assertEqual(r, ('sp', False))
def test_incomplete_keyword_var(self):
k, c = KeyCmd[self.uzbl], CompletionPlugin[self.uzbl]
k.keylet.keycmd = 'set @sp'
k.keylet.cursor = len(k.keylet.keycmd)
r = c.get_incomplete_keyword()
- self.assertEquals(r, ('@sp', False))
+ self.assertEqual(r, ('@sp', False))
def test_incomplete_keyword_var_noat(self):
k, c = KeyCmd[self.uzbl], CompletionPlugin[self.uzbl]
k.keylet.keycmd = 'set Some'
k.keylet.cursor = len(k.keylet.keycmd)
r = c.get_incomplete_keyword()
- self.assertEquals(r, ('@Some', True))
+ self.assertEqual(r, ('@Some', True))
def test_stop_completion(self):
config, c = Config[self.uzbl], CompletionPlugin[self.uzbl]
@@ -79,7 +79,7 @@ def test_stop_completion(self):
c.stop_completion()
self.assertNotIn('completion_list', config)
- self.assertEquals(c.completion.level, 0)
+ self.assertEqual(c.completion.level, 0)
def test_completion(self):
k, c = KeyCmd[self.uzbl], CompletionPlugin[self.uzbl]
@@ -96,7 +96,7 @@ def test_completion(self):
k.keylet.cursor = len(k.keylet.keycmd)
c.start_completion()
- self.assertEquals(k.keylet.keycmd, o)
+ self.assertEqual(k.keylet.keycmd, o)
c.start_completion()
self.assertNotIn('completion_list', config)
@@ -113,6 +113,6 @@ def test_completion_list(self):
k.keylet.cursor = len(k.keylet.keycmd)
c.start_completion()
- self.assertEquals(k.keylet.keycmd, o)
+ self.assertEqual(k.keylet.keycmd, o)
c.start_completion()
- self.assertEquals(config['completion_list'], l)
+ self.assertEqual(config['completion_list'], l)
View
6 tests/event-manager/testconfig.py
@@ -1,4 +1,4 @@
-from __future__ import print_function
+
import unittest
from emtest import EventManagerMock
@@ -44,7 +44,7 @@ def test_parse(self):
for input, ekey, evalue in cases:
c.parse_set_event(input)
self.assertIn(ekey, c)
- self.assertEquals(c[ekey], evalue)
+ self.assertEqual(c[ekey], evalue)
self.uzbl.event.assert_called_once_with(
'CONFIG_CHANGED', ekey, evalue)
self.uzbl.event.reset_mock()
@@ -74,4 +74,4 @@ def test_parse_invalid(self):
c = Config[self.uzbl]
for input, exception in cases:
self.assertRaises(exception, c.parse_set_event, input)
- self.assertEquals(len(list(c.keys())), 0)
+ self.assertEqual(len(list(c.keys())), 0)
View
2 tests/event-manager/testcookie.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-from __future__ import print_function
+
import sys
if '' not in sys.path:
View
4 tests/event-manager/testcore.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# vi: set et ts=4:
-from __future__ import print_function
+
import unittest
from mock import Mock
@@ -15,7 +15,7 @@ def setUp(self):
def test_repr(self):
r = '%r' % self.uzbl
- self.assertRegexpMatches(r, r'<uzbl\(.*\)>')
+ self.assertRegex(r, r'<uzbl\(.*\)>')
def test_event_handler(self):
handler = Mock()
View
4 tests/event-manager/testdownload.py
@@ -1,6 +1,6 @@
# vi: set et ts=4:
-from __future__ import print_function
+
import unittest
from emtest import EventManagerMock
@@ -23,7 +23,7 @@ def test_start(self):
for input, key, section in cases:
d.download_started(input)
self.assertIn(key, d.active_downloads)
- self.assertEquals(d.active_downloads[key], 0)
+ self.assertEqual(d.active_downloads[key], 0)
self.uzbl.send.assert_called_once()
self.assertIn(section, self.uzbl.send.call_args[0][0])
self.uzbl.reset_mock()
View
88 tests/event-manager/testhistory.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# vi: set et ts=4:
-from __future__ import print_function
+
import sys
if '' not in sys.path:
@@ -32,18 +32,18 @@ def test_add_and_get(self):
s.addline('foo', 'bar')
s.addline('foo', 'baz')
s.addline('foo', 'bap')
- self.assertEquals(s.get_line_number('foo'), 3)
- self.assertEquals(s.get_line_number('other'), 0)
- self.assertEquals(s.getline('foo', 0), 'bar')
- self.assertEquals(s.getline('foo', 1), 'baz')
- self.assertEquals(s.getline('foo', 2), 'bap')
- self.assertEquals(s.getline('foo', -1), 'bap')
+ self.assertEqual(s.get_line_number('foo'), 3)
+ self.assertEqual(s.get_line_number('other'), 0)
+ self.assertEqual(s.getline('foo', 0), 'bar')
+ self.assertEqual(s.getline('foo', 1), 'baz')
+ self.assertEqual(s.getline('foo', 2), 'bap')
+ self.assertEqual(s.getline('foo', -1), 'bap')
def test_empty_line_number(self):
s = SharedHistory[self.uzbl]
s.addline('foo', 'bar')
- self.assertEquals(s.get_line_number(''), 0)
- self.assertEquals(s.get_line_number('other'), 0)
+ self.assertEqual(s.get_line_number(''), 0)
+ self.assertEqual(s.get_line_number('other'), 0)
def test_get_missing_prompt(self):
s = SharedHistory[self.uzbl]
@@ -74,36 +74,36 @@ def setUp(self):
def test_step(self):
h = History[self.uzbl]
- self.assertEquals('', h.next())
- self.assertEquals('', h.next())
- self.assertEquals('foo', h.prev())
- self.assertEquals('bar', h.prev())
- self.assertEquals('foo', h.next())
- self.assertEquals('bar', h.prev())
- self.assertEquals('doop', h.prev())
- self.assertEquals('woop', h.prev())
+ self.assertEqual('', next(h))
+ self.assertEqual('', next(h))
+ self.assertEqual('foo', h.prev())
+ self.assertEqual('bar', h.prev())
+ self.assertEqual('foo', next(h))
+ self.assertEqual('bar', h.prev())
+ self.assertEqual('doop', h.prev())
+ self.assertEqual('woop', h.prev())
self.assertTrue(len(h.prev()) > 0)
self.assertTrue(len(h.prev()) > 0)
- self.assertEquals('woop', h.next())
+ self.assertEqual('woop', next(h))
def test_step_prompt(self):
h = History[self.uzbl]
h.change_prompt('git')
- self.assertEquals('', h.next())
- self.assertEquals('', h.next())
- self.assertEquals('egg', h.prev())
- self.assertEquals('spam', h.prev())
+ self.assertEqual('', next(h))
+ self.assertEqual('', next(h))
+ self.assertEqual('egg', h.prev())
+ self.assertEqual('spam', h.prev())
self.assertTrue(len(h.prev()) > 0)
self.assertTrue(len(h.prev()) > 0)
- self.assertEquals('spam', h.next())
+ self.assertEqual('spam', next(h))
def test_change_prompt(self):
h = History[self.uzbl]
- self.assertEquals('foo', h.prev())
- self.assertEquals('bar', h.prev())
+ self.assertEqual('foo', h.prev())
+ self.assertEqual('bar', h.prev())
h.change_prompt('git')
- self.assertEquals('egg', h.prev())
- self.assertEquals('spam', h.prev())
+ self.assertEqual('egg', h.prev())
+ self.assertEqual('spam', h.prev())
def test_exec(self):
modstate = set()
@@ -115,31 +115,31 @@ def test_exec(self):
def test_exec_from_history(self):
h = History[self.uzbl]
- self.assertEquals('foo', h.prev())
- self.assertEquals('bar', h.prev())
- self.assertEquals('doop', h.prev())
+ self.assertEqual('foo', h.prev())
+ self.assertEqual('bar', h.prev())
+ self.assertEqual('doop', h.prev())
modstate = set()
keylet = Keylet()
keylet.set_keycmd('doop')
h.keycmd_exec(modstate, keylet)
- self.assertEquals('doop', h.prev())
- self.assertEquals('foo', h.prev())
- self.assertEquals('bar', h.prev())
+ self.assertEqual('doop', h.prev())
+ self.assertEqual('foo', h.prev())
+ self.assertEqual('bar', h.prev())
# do we really want this one here ?
- self.assertEquals('doop', h.prev())
- self.assertEquals('woop', h.prev())
+ self.assertEqual('doop', h.prev())
+ self.assertEqual('woop', h.prev())
def test_search(self):
h = History[self.uzbl]
h.search('oop')
- self.assertEquals('doop', h.prev())
- self.assertEquals('woop', h.prev())
+ self.assertEqual('doop', h.prev())
+ self.assertEqual('woop', h.prev())
self.assertTrue(len(h.prev()) > 0)
- self.assertEquals('woop', h.next())
- self.assertEquals('doop', h.next())
+ self.assertEqual('woop', next(h))
+ self.assertEqual('doop', next(h))
# this reset the search
- self.assertEquals('', h.next())
- self.assertEquals('foo', h.prev())
+ self.assertEqual('', next(h))
+ self.assertEqual('foo', h.prev())
def test_temp(self):
kl = KeyCmd[self.uzbl].keylet
@@ -149,6 +149,6 @@ def test_temp(self):
# Why is the preserve current logic in this method?
h.history_prev(None)
self.assertTrue(len(h.prev()) > 0)
- self.assertEquals('foo', h.next())
- self.assertEquals('uzbl', h.next())
- self.assertEquals('', h.next()) # this clears the keycmd
+ self.assertEqual('foo', next(h))
+ self.assertEqual('uzbl', next(h))
+ self.assertEqual('', next(h)) # this clears the keycmd
View
22 tests/event-manager/testmode.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# vi: set et ts=4:
-from __future__ import print_function
+
import unittest
from emtest import EventManagerMock
@@ -58,9 +58,9 @@ def test_mode_sets_vars(self):
self.assertIn('foo', config)
self.assertIn('bar', config)
self.assertIn('baz', config)
- self.assertEquals(config['foo'], 'xxx')
- self.assertEquals(config['bar'], 'yyy')
- self.assertEquals(config['baz'], 'zzz')
+ self.assertEqual(config['foo'], 'xxx')
+ self.assertEqual(config['bar'], 'yyy')
+ self.assertEqual(config['baz'], 'zzz')
def test_mode_overwrite_vars(self):
mode, config = ModePlugin[self.uzbl], Config[self.uzbl]
@@ -73,10 +73,10 @@ def test_mode_overwrite_vars(self):
self.assertIn('bar', config)
self.assertIn('baz', config)
self.assertIn('spam', config)
- self.assertEquals(config['foo'], 'XXX')
- self.assertEquals(config['bar'], 'yyy')
- self.assertEquals(config['baz'], 'zzz')
- self.assertEquals(config['spam'], 'spam')
+ self.assertEqual(config['foo'], 'XXX')
+ self.assertEqual(config['bar'], 'yyy')
+ self.assertEqual(config['baz'], 'zzz')
+ self.assertEqual(config['spam'], 'spam')
def test_default_mode(self):
''' Setting to mode to nothing should enter the default mode'''
@@ -85,7 +85,7 @@ def test_default_mode(self):
config['foo'] = 'nthth'
config['mode'] = ''
mode.mode_updated(None, '')
- self.assertEquals(config['mode'], 'mode0')
+ self.assertEqual(config['mode'], 'mode0')
mode.mode_updated(None, config['mode'])
- self.assertEquals(config['mode'], 'mode0')
- self.assertEquals(config['foo'], 'default')
+ self.assertEqual(config['mode'], 'mode0')
+ self.assertEqual(config['foo'], 'default')
View
4 tests/event-manager/testonevent.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# vi: set et ts=4:
-from __future__ import print_function
+
import unittest
from emtest import EventManagerMock
@@ -56,4 +56,4 @@ def test_parse_pattern(self):
self.assertIn(event, oe.events)
commands = oe.events[event]
self.assertIn(command, commands)
- self.assertEquals(commands[command], [pattern])
+ self.assertEqual(commands[command], [pattern])
View
10 tests/event-manager/testprogressbar.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# vi: set et ts=4:
-from __future__ import print_function
+
import sys
if '' not in sys.path:
@@ -36,7 +36,7 @@ def test_percent_done(self):
for i, o in inout:
p.update_progress(i)
- self.assertEquals(c['progress.output'], o)
+ self.assertEqual(c['progress.output'], o)
def test_done_char(self):
uzbl = self.uzbl
@@ -54,7 +54,7 @@ def test_done_char(self):
for i, o in inout:
p.update_progress(i)
- self.assertEquals(c['progress.output'], o)
+ self.assertEqual(c['progress.output'], o)
def test_pending_char(self):
uzbl = self.uzbl
@@ -73,7 +73,7 @@ def test_pending_char(self):
for i, o in inout:
p.update_progress(i)
- self.assertEquals(c['progress.output'], o)
+ self.assertEqual(c['progress.output'], o)
def test_percent_pending(self):
uzbl = self.uzbl
@@ -91,4 +91,4 @@ def test_percent_pending(self):
for i, o in inout:
p.update_progress(i)
- self.assertEquals(c['progress.output'], o)
+ self.assertEqual(c['progress.output'], o)
View
27 uzbl/arguments.py
@@ -5,6 +5,7 @@
'''
import re
+import ast
class Arguments(tuple):
@@ -13,24 +14,24 @@ class Arguments(tuple):
honoring common quotation and escaping rules
>>> Arguments(r"simple 'quoted string'")
- (u'simple', u'quoted string')
+ ('simple', 'quoted string')
'''
_splitquoted = re.compile("(\s+|\"(?:\\\\.|[^\"])*?\"|'(?:\\\\.|[^'])*?')")
def __new__(cls, s):
'''
>>> Arguments(r"one two three")
- (u'one', u'two', u'three')
+ ('one', 'two', 'three')
>>> Arguments(r"spam 'escaping \\'works\\''")
- (u'spam', u"escaping 'works'")
+ ('spam', "escaping 'works'")
>>> # For testing purposes we can pass a preparsed tuple
- >>> Arguments((u'foo', u'bar', u'baz az'))
- (u'foo', u'bar', u'baz az')
+ >>> Arguments(('foo', 'bar', 'baz az'))
+ ('foo', 'bar', 'baz az')
'''
if isinstance(s, tuple):
self = tuple.__new__(cls, s)
- self._raw, self._ref = s, range(len(s))
+ self._raw, self._ref = s, list(range(len(s)))
return self
raw = cls._splitquoted.split(s)
ref = []
@@ -71,7 +72,7 @@ def raw(self, frm=0, to=None):
>>> args = Arguments(r"'spam, spam' egg sausage and 'spam'")
>>> args
- (u'spam, spam', u'egg', u'sausage', u'and', u'spam')
+ ('spam, spam', 'egg', 'sausage', 'and', 'spam')
>>> args.raw(1)
"egg sausage and 'spam'"
'''
@@ -87,8 +88,12 @@ def raw(self, frm=0, to=None):
splitquoted = Arguments # or define a function?
def unquote(s):
- '''Removes quotation marks around strings if any and interprets
- \\-escape sequences using `string_escape`'''
+ '''
+ Returns the input string without quotations and with
+ escape sequences interpreted
+ '''
+
if s and s[0] == s[-1] and s[0] in ['"', "'"]:
- s = s[1:-1]
- return s.encode('utf-8').decode('string_escape').decode('utf-8')
+ return ast.literal_eval(s)
+ return ast.literal_eval('"' + s + '"')
+
View
17 uzbl/core.py
@@ -10,7 +10,7 @@ def __init__(self, socket, uzbl):
asynchat.async_chat.__init__(self, socket)
self.uzbl = uzbl
self.buffer = bytearray()
- self.set_terminator('\n')
+ self.set_terminator(b'\n')
def collect_incoming_data(self, data):
self.buffer += data
@@ -20,6 +20,9 @@ def found_terminator(self):
del self.buffer[:]
self.uzbl.parse_msg(val)
+ def handle_error(self):
+ raise
+
class Uzbl(object):
@@ -50,7 +53,7 @@ def __repr__(self):
'pid=%s' % (self.pid if self.pid else "Unknown"),
'name=%s' % ('%r' % self.name if self.name else "Unknown"),
'uptime=%f' % (time.time() - self.time),
- '%d handlers' % sum([len(l) for l in self.handlers.values()])])
+ '%d handlers' % sum([len(l) for l in list(self.handlers.values())])])
def init_plugins(self):
'''Creates instances of per-instance plugins'''
@@ -70,7 +73,7 @@ def send(self, msg):
msg = msg.strip()
if self.opts.print_events:
- print(u'%s<-- %s' % (' ' * self._depth, msg))
+ print(('%s<-- %s' % (' ' * self._depth, msg)))
self.proto.push((msg+'\n').encode('utf-8'))
@@ -85,7 +88,7 @@ def parse_msg(self, line):
if elems[0] != 'EVENT':
self.logger.info('non-event message: %r', line)
if self.opts.print_events:
- print('--- %s' % line)
+ print(('--- %s' % line))
return
# Check event string elements
@@ -109,10 +112,10 @@ def event(self, event, *args, **kargs):
if not self.opts.daemon_mode and self.opts.print_events:
elems = [event]
if args:
- elems.append(unicode(args))
+ elems.append(str(args))
if kargs:
- elems.append(unicode(kargs))
- print(u'%s--> %s' % (' ' * self._depth, ' '.join(elems)))
+ elems.append(str(kargs))
+ print(('%s--> %s' % (' ' * self._depth, ' '.join(elems))))
if event == "INSTANCE_START" and args:
assert not self.instance_start, 'instance already started'
View
18 uzbl/event_manager.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-from __future__ import print_function
+
# Event Manager for Uzbl
# Copyright (c) 2009-2010, Mason Larobina <mason.larobina@gmail.com>
@@ -54,7 +54,7 @@ def xdghome(key, default):
use $HOME and the default path.'''
xdgkey = "XDG_%s_HOME" % key
- if xdgkey in os.environ.keys() and os.environ[xdgkey]:
+ if xdgkey in list(os.environ.keys()) and os.environ[xdgkey]:
return os.environ[xdgkey]
return os.path.join(os.environ['HOME'], default)
@@ -110,9 +110,9 @@ def daemonize():
sys.stderr.flush()
devnull = '/dev/null'
- stdin = file(devnull, 'r')
- stdout = file(devnull, 'a+')
- stderr = file(devnull, 'a+', 0)
+ stdin = open(devnull, 'r')
+ stdout = open(devnull, 'a+')
+ stderr = open(devnull, 'a+')
os.dup2(stdin.fileno(), sys.stdin.fileno())
os.dup2(stdout.fileno(), sys.stdout.fileno())
@@ -138,7 +138,7 @@ class EventHandler(object):
'''Event handler class. Used to store args and kwargs which are merged
come time to call the callback with the event args and kwargs.'''
- nextid = count().next
+ nextid = count().__next__
def __init__(self, plugin, event, callback, args, kwargs):
self.id = self.nextid()
@@ -159,13 +159,13 @@ def __repr__(self):
elems.append('kwargs=%s' % repr(self.kwargs))
elems.append('plugin=%s' % self.plugin.name)
- return u'<handler(%s)>' % ', '.join(elems)
+ return '<handler(%s)>' % ', '.join(elems)
def call(self, uzbl, *args, **kwargs):
'''Execute the handler function and merge argument lists.'''
args = args + self.args
- kwargs = dict(self.kwargs.items() + kwargs.items())
+ kwargs = dict(list(self.kwargs.items()) + list(kwargs.items()))
self.callback(uzbl, *args, **kwargs)
class Listener(asyncore.dispatcher):
@@ -305,7 +305,7 @@ def quit(self, sigint=None, *args):
self.close_server_socket()
- for uzbl in self.uzbls.values():
+ for uzbl in list(self.uzbls.values()):
uzbl.close()
if not self._quit:
View
3 uzbl/ext.py
@@ -33,9 +33,8 @@ def __getitem__(self, owner):
return self._get_instance(owner)
-class BasePlugin(object):
+class BasePlugin(object, metaclass=PluginMeta):
"""Base class for all uzbl plugins"""
- __metaclass__ = PluginMeta
class PerInstancePlugin(BasePlugin):
View
27 uzbl/plugins/bind.py
@@ -18,6 +18,7 @@
from .cmd_expand import cmd_expand
from .config import Config
from .keycmd import KeyCmd
+import collections
# Commonly used regular expressions.
MOD_START = re.compile('^<([A-Z][A-Za-z0-9-_]*)>').match
@@ -27,7 +28,7 @@
VALID_MODE = re.compile('^(-|)[A-Za-z0-9][A-Za-z0-9_]*$').match
# For accessing a bind glob stack.
-ON_EXEC, HAS_ARGS, MOD_CMD, GLOB, MORE = range(5)
+ON_EXEC, HAS_ARGS, MOD_CMD, GLOB, MORE = list(range(5))
# Custom errors.
@@ -125,10 +126,10 @@ def get_binds(self, mode=None):
globals = self.binds['global']
if mode not in self.binds or mode == 'global':
- return filter(None, globals.values())
+ return [_f for _f in list(globals.values()) if _f]
- binds = dict(globals.items() + self.binds[mode].items())
- return filter(None, binds.values())
+ binds = dict(list(globals.items()) + list(self.binds[mode].items()))
+ return [_f for _f in list(binds.values()) if _f]
def add_bind(self, mode, glob, bind=None):
@@ -144,7 +145,7 @@ def add_bind(self, mode, glob, bind=None):
if mode == 'global':
# Regen the global-globals list.
self.globals = []
- for bind in binds.values():
+ for bind in list(binds.values()):
if bind is not None and bind.is_global:
self.globals.append(bind)
@@ -178,7 +179,7 @@ class Bind(object):
counter = [0,]
def __init__(self, glob, handler, *args, **kargs):
- self.is_callable = callable(handler)
+ self.is_callable = isinstance(handler, collections.Callable)
self._repr_cache = None
if not glob:
@@ -192,7 +193,7 @@ def __init__(self, glob, handler, *args, **kargs):
elif kargs:
raise ArgumentError('cannot supply kargs for uzbl commands')
- elif hasattr(handler, '__iter__'):
+ elif not isinstance(handler, str):
self.commands = handler
else:
@@ -207,7 +208,7 @@ def __init__(self, glob, handler, *args, **kargs):
self.split = split = FIND_PROMPTS(glob)
self.prompts = []
for (prompt, cmd, set) in zip(split[1::4], split[2::4], split[3::4]):
- prompt, set = map(unquote, [prompt, set])
+ prompt, set = list(map(unquote, [prompt, set]))
cmd = True if cmd == '!' else False
if prompt and prompt[-1] != ":":
prompt = "%s:" % prompt
@@ -307,7 +308,7 @@ def exec_bind(self, bind, *args, **kargs):
if bind.is_callable:
args += bind.args
- kargs = dict(bind.kargs.items()+kargs.items())
+ kargs = dict(list(bind.kargs.items())+list(kargs.items()))
bind.function(self.uzbl, *args, **kargs)
return
@@ -324,13 +325,13 @@ def mode_bind(self, modes, glob, handler=None, *args, **kargs):
bindlet = self.bindlet
- if not hasattr(modes, '__iter__'):
- modes = unicode(modes).split(',')
+ if isinstance(modes, str):
+ modes = modes.split(',')
# Sort and filter binds.
- modes = filter(None, map(unicode.strip, modes))
+ modes = [_f for _f in map(str.strip, modes) if _f]
- if callable(handler) or (handler is not None and handler.strip()):
+ if isinstance(handler, collections.Callable) or (handler is not None and handler.strip()):
bind = Bind(glob, handler, *args, **kargs)
else:
View
4 uzbl/plugins/cmd_expand.py
@@ -17,7 +17,7 @@ def cmd_expand(cmd, args):
'''
# Ensure (1) all string representable and (2) correct string encoding.
- args = map(unicode, args)
+ args = list(map(str, args))
# Direct string replace.
if '%s' in cmd:
@@ -31,6 +31,6 @@ def cmd_expand(cmd, args):
for (index, arg) in enumerate(args):
index += 1
if '%%%d' % index in cmd:
- cmd = cmd.replace('%%%d' % index, unicode(arg))
+ cmd = cmd.replace('%%%d' % index, str(arg))
return cmd
View
6 uzbl/plugins/completion.py
@@ -8,7 +8,7 @@
from .keycmd import KeyCmd
# Completion level
-NONE, ONCE, LIST, COMPLETE = range(4)
+NONE, ONCE, LIST, COMPLETE = list(range(4))
# The reverse keyword finding re.
FIND_SEGMENT = re.compile("(\@[\w_]+|set[\s]+[\w_]+|[\w_]+)$").findall
@@ -117,7 +117,7 @@ def update_completion_list(self, *args):
config = Config[self.uzbl]
- hints = filter(lambda h: h.startswith(partial), self.completion)
+ hints = [h for h in self.completion if h.startswith(partial)]
if not hints:
del config['completion_list']
return
@@ -135,7 +135,7 @@ def start_completion(self, *args):
if self.completion.level < COMPLETE:
self.completion.level += 1
- hints = filter(lambda h: h.startswith(partial), self.completion)
+ hints = [h for h in self.completion if h.startswith(partial)]
if not hints:
return
View
12 uzbl/plugins/config.py
@@ -3,7 +3,7 @@
from uzbl.arguments import splitquoted
from uzbl.ext import PerInstancePlugin
-types = {'int': int, 'float': float, 'str': unicode}
+types = {'int': int, 'float': float, 'str': str}
valid_key = compile('^[A-Za-z0-9_\.]+$').match
@@ -38,16 +38,16 @@ def __contains__(self, key):
return key in self.data
def keys(self):
- return self.data.iterkeys()
+ return iter(self.data.keys())
def items(self):
- return self.data.iteritems()
+ return iter(self.data.items())
def update(self, other=None, **kwargs):
if other is None:
other = {}
- for (key, value) in dict(other).items() + kwargs.items():
+ for (key, value) in list(dict(other).items()) + list(kwargs.items()):
self[key] = value
@@ -65,13 +65,13 @@ def set(self, key, value='', force=False):
value = int(value)
else:
- value = unicode(value)
+ value = str(value)
assert '\n' not in value
if not force and key in self and self[key] == value:
return
- self.uzbl.send(u'set %s = %s' % (key, value))
+ self.uzbl.send('set %s = %s' % (key, value))
def parse_set_event(self, args):
View
8 uzbl/plugins/cookies.py
@@ -110,8 +110,8 @@ def add_cookie(self, rawcookie, cookie):
first = not os.path.exists(self.filename)
with open(self.filename, 'a') as f:
if first:
- print >> f, "# HTTP Cookie File"
- print >> f, '\t'.join(self.as_file(cookie))
+ print("# HTTP Cookie File", file=f)
+ print('\t'.join(self.as_file(cookie)), file=f)
def delete_cookie(self, rkey, key):
if not os.path.exists(self.filename):
@@ -126,7 +126,7 @@ def delete_cookie(self, rkey, key):
for l in cookies:
c = self.as_event(l.split('\t'))
if c is None or not match(key, c):
- print >> f, l,
+ print(l, end=' ', file=f)
xdg_data_home = os.environ.get('XDG_DATA_HOME', os.path.join(os.environ['HOME'], '.local/share'))
DefaultStore = TextStore(os.path.join(xdg_data_home, 'uzbl/cookies.txt'))
@@ -161,7 +161,7 @@ def expires_with_session(self, cookie):
def get_recipents(self):
""" get a list of Uzbl instances to send the cookie too. """
# This could be a lot more interesting
- return [u for u in self.uzbl.parent.uzbls.values() if u is not self.uzbl]
+ return [u for u in list(self.uzbl.parent.uzbls.values()) if u is not self.uzbl]
def get_store(self, session=False):
if session:
View
6 uzbl/plugins/downloads.py
@@ -2,7 +2,7 @@
# @downloads to your status_format.
import os
-from cgi import escape as htmlescape
+import html
from uzbl.arguments import splitquoted
from .config import Config
@@ -25,7 +25,7 @@ def update_download_section(self):
if self.active_downloads:
# add a newline before we list downloads
result = '&#10;downloads:'
- for path, progress in self.active_downloads.items():
+ for path, progress in list(self.active_downloads.items()):
# add each download
fn = os.path.basename(path)
@@ -34,7 +34,7 @@ def update_download_section(self):
# replace entities to make sure we don't break our markup
# (this could be done with an @[]@ expansion in uzbl, but then we
# can't use the &#10; above to make a new line)
- dl = htmlescape(dl)
+ dl = html.escape(dl)
result += dl
else:
result = ''
View
4 uzbl/plugins/history.py
@@ -66,7 +66,7 @@ def prev(self):
self.cursor = -1
return random.choice(end_messages)
- def next(self):
+ def __next__(self):
if self.cursor is None:
return ''
shared = SharedHistory[self.uzbl]
@@ -118,7 +118,7 @@ def history_prev(self, _x):
KeyCmd[self.uzbl].set_keycmd(val)
def history_next(self, _x):
- KeyCmd[self.uzbl].set_keycmd(self.next())
+ KeyCmd[self.uzbl].set_keycmd(next(self))
def history_search(self, key):
self.search(key)
View
23 uzbl/plugins/keycmd.py
@@ -32,12 +32,12 @@ class Keylet(object):
>>> k = Keylet()
>>> k.set_keycmd('spam')
- >>> print k
+ >>> print(k)
<keylet(keycmd='spam')>
>>> k.append_keycmd(' and egg')
- >>> print k
+ >>> print(k)
<keylet(keycmd='spam and egg')>
- >>> print k.cursor
+ >>> print(k.cursor)
12
'''
@@ -84,9 +84,9 @@ def insert_keycmd(self, s):
>>> k.set_keycmd('spam')
>>> k.cursor = 1
>>> k.insert_keycmd('egg')
- >>> print k
+ >>> print(k)
<keylet(keycmd='seggpam')>
- >>> print k.cursor
+ >>> print(k.cursor)
4
'''
@@ -100,9 +100,9 @@ def append_keycmd(self, s):
>>> k.set_keycmd('spam')
>>> k.cursor = 1
>>> k.append_keycmd('egg')
- >>> print k
+ >>> print(k)
<keylet(keycmd='spamegg')>
- >>> print k.cursor
+ >>> print(k.cursor)
7
'''
@@ -134,11 +134,11 @@ def strip_word(self, seps=' '):
>>> k.set_keycmd('spam and egg')
>>> k.strip_word()
'egg'
- >>> print k
+ >>> print(k)
<keylet(keycmd='spam and ')>
>>> k.strip_word()
'and'
- >>> print k
+ >>> print(k)
<keylet(keycmd='spam ')>
'''
if not self.keycmd:
@@ -264,7 +264,7 @@ def modmap_key(self, key):
def key_ignored(self, key):
'''Check if the given key is ignored by any ignore rules.'''
- for (glob, match) in self.ignores.items():
+ for (glob, match) in list(self.ignores.items()):
if match(key):
return True
@@ -379,7 +379,7 @@ def update_event(self, modstate, k, execute=True):
elif new_keycmd == keycmd:
# Generate the pango markup for the cursor in the keycmd.
- config['keycmd'] = unicode(k.markup())
+ config['keycmd'] = str(k.markup())
def parse_key_event(self, key):
''' Build a set from the modstate part of the event, and pass all keys through modmap '''
@@ -499,3 +499,4 @@ def set_cursor_pos(self, args):
self.update_event(set(), self.keylet, False)
# vi: set et ts=4:
+
View
4 uzbl/plugins/on_event.py
@@ -49,15 +49,15 @@ def event_handler(self, *args, **kargs):
on_event definitions and responds accordingly.'''
# Could be connected to a EM internal event that can use anything as args
- if len(args) == 1 and isinstance(args[0], basestring):
+ if len(args) == 1 and isinstance(args[0], str):
args = splitquoted(args[0])
event = kargs['on_event']
if event not in self.events:
return
commands = self.events[event]
- for cmd, pattern in commands.items():
+ for cmd, pattern in list(commands.items()):
if not pattern or match_args(pattern, args):
cmd = cmd_expand(cmd, args)
self.uzbl.send(cmd)
View
9 uzbl/plugins/on_set.py
@@ -5,6 +5,7 @@
from .cmd_expand import cmd_expand
from uzbl.arguments import splitquoted
from uzbl.ext import PerInstancePlugin
+import collections
valid_glob = compile('^[A-Za-z0-9_\*\.]+$').match
@@ -27,15 +28,15 @@ def _exec_handlers(self, handlers, key, arg):
'''Execute the on_set handlers that matched the key.'''
for handler in handlers:
- if callable(handler):
+ if isinstance(handler, collections.Callable):
handler(key, arg)
else:
self.uzbl.send(cmd_expand(handler, [key, arg]))
def check_for_handlers(self, key, arg):
'''Check for handlers for the current key.'''
- for (matcher, handlers) in self.on_sets.values():
+ for (matcher, handlers) in list(self.on_sets.values()):
if matcher(key):
self._exec_handlers(handlers, key, arg)
@@ -51,13 +52,13 @@ def on_set(self, glob, handler, prepend=True):
while '**' in glob:
glob = glob.replace('**', '*')
- if callable(handler):
+ if isinstance(handler, collections.Callable):
orig_handler = handler
if prepend:
handler = partial(handler, self.uzbl)
else:
- orig_handler = handler = unicode(handler)
+ orig_handler = handler = str(handler)
if glob in self.on_sets:
(matcher, handlers) = self.on_sets[glob]

0 comments on commit c5c5b17

Please sign in to comment.