Skip to content

Commit 482c936

Browse files
committedSep 12, 2016
Twisted client works with python 3
1 parent 2ee99a0 commit 482c936

File tree

2 files changed

+25
-27
lines changed

2 files changed

+25
-27
lines changed
 

‎examples/twisted_example.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@ def __init__(self, protocol):
1212

1313
def __call__(self, result):
1414
# idle result callback
15-
print(result)
15+
print('Subsystems: {}'.format(list(result)))
1616

1717
def status_success(result):
1818
# status query success
19-
print(result)
19+
print('Status success: {}'.format(result))
2020

2121
def status_error(result):
2222
# status query failure
23-
print(result)
23+
print('Status error: {}'.format(result))
2424

2525
# query player status
2626
self.protocol.status()\
@@ -32,22 +32,23 @@ class MPDClientFactory(protocol.ClientFactory):
3232
protocol = MPDProtocol
3333

3434
def buildProtocol(self, addr):
35-
print("Create MPD protocol")
35+
print('Create MPD protocol')
3636
protocol = self.protocol()
3737
protocol.factory = self
3838
protocol.idle_result = MPDApp(protocol)
3939
return protocol
4040

4141
def clientConnectionFailed(self, connector, reason):
42-
print("Connection failed - goodbye!: %s" % reason)
42+
print('Connection failed - goodbye!: {}'.format(reason))
4343
reactor.stop()
4444

4545
def clientConnectionLost(self, connector, reason):
46-
print("Connection lost - goodbye!: %s" % reason)
47-
reactor.stop()
46+
print('Connection lost - goodbye!: {}'.format(reason))
47+
if reactor.running:
48+
reactor.stop()
4849

4950

5051
if __name__ == '__main__':
5152
factory = MPDClientFactory()
52-
reactor.connectTCP("localhost", 6600, factory)
53+
reactor.connectTCP('localhost', 6600, factory)
5354
reactor.run()

‎mpd/twisted.py

+16-19
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
# https://github.com/Mic92/python-mpd2/issues
2424

2525
from __future__ import absolute_import
26+
from __future__ import unicode_literals
2627
from mpd.base import CommandError
2728
from mpd.base import CommandListError
2829
from mpd.base import ERROR_PREFIX
@@ -36,7 +37,7 @@
3637
from mpd.base import mpd_commands
3738
from twisted.internet import defer
3839
from twisted.protocols import basic
39-
from types import GeneratorType
40+
import types
4041

4142

4243
def _create_command(wrapper, name, callback):
@@ -49,7 +50,7 @@ def bound_callback(lines):
4950

5051
@mpd_command_provider
5152
class MPDProtocol(basic.LineReceiver, MPDClientBase):
52-
delimiter = "\n"
53+
delimiter = b'\n'
5354

5455
def __init__(self, default_idle=True, idle_result=None):
5556
super(MPDProtocol, self).__init__(use_unicode=True)
@@ -74,7 +75,7 @@ def add_command(cls, name, callback):
7475
return
7576
# create command and hook it on class
7677
func = _create_command(cls._execute, name, callback)
77-
escaped_name = name.replace(" ", "_")
78+
escaped_name = name.replace(' ', '_')
7879
setattr(cls, escaped_name, func)
7980

8081
def lineReceived(self, line):
@@ -92,7 +93,7 @@ def lineReceived(self, line):
9293
state_list[0].errback(CommandError(error))
9394
for state in state_list[1:-1]:
9495
state.errback(
95-
CommandListError("An earlier command failed."))
96+
CommandListError('An earlier command failed.'))
9697
state_list[-1].errback(CommandListError(error))
9798
del self._state[0]
9899
del self._command_list_results[0]
@@ -112,10 +113,10 @@ def lineReceived(self, line):
112113
def _execute(self, command, args, parser):
113114
# close or kill command in command list not allowed
114115
if self._command_list and not callable(parser):
115-
msg = "{} not allowed in command list".format(command)
116+
msg = '{} not allowed in command list'.format(command)
116117
raise CommandListError(msg)
117118
# default state idle and currently in idle state, trigger noidle
118-
if self._default_idle and self._idle and command != "idle":
119+
if self._default_idle and self._idle and command != 'idle':
119120
self.noidle().addCallback(self._dispatch_noidle_result)
120121
# write command to MPD
121122
self._write_command(command, args)
@@ -134,15 +135,11 @@ def _execute(self, command, args, parser):
134135
return deferred
135136

136137
def _write_command(self, command, args=[]):
137-
parts = [command]
138-
parts += ['"{}"'.format(escape(arg.encode('utf-8'))
139-
if isinstance(arg, unicode) else str(arg)) for arg in args]
140-
cmd = " ".join(parts)
141-
self.sendLine(cmd)
138+
parts = [command] + ['"{}"'.format(escape(arg)) for arg in args]
139+
self.sendLine(' '.join(parts).encode('utf-8'))
142140

143141
def _parse_command_list_item(self, result):
144-
# TODO: find a better way to do this
145-
if type(result) == GeneratorType:
142+
if isinstance(result, types.GeneratorType):
146143
result = list(result)
147144
self._command_list_results[0].append(result)
148145
return result
@@ -177,13 +174,13 @@ def _dispatch_idle_result(self, result):
177174

178175
def idle(self):
179176
if self._idle:
180-
raise CommandError("Already in idle state")
177+
raise CommandError('Already in idle state')
181178
self._idle = True
182179
return self._execute('idle', [], self._parse_list)
183180

184181
def noidle(self):
185182
if not self._idle:
186-
raise CommandError("Not in idle state")
183+
raise CommandError('Not in idle state')
187184
# delete first pending deferred, idle returns nothing when
188185
# noidle gets called
189186
self._state.pop(0)
@@ -192,18 +189,18 @@ def noidle(self):
192189

193190
def command_list_ok_begin(self):
194191
if self._command_list:
195-
raise CommandListError("Already in command list")
192+
raise CommandListError('Already in command list')
196193
if self._default_idle and self._idle:
197194
self.noidle().addCallback(self._dispatch_noidle_result)
198-
self._write_command("command_list_ok_begin")
195+
self._write_command('command_list_ok_begin')
199196
self._command_list = True
200197
self._command_list_results.append([])
201198
self._state.append([])
202199

203200
def command_list_end(self):
204201
if not self._command_list:
205-
raise CommandListError("Not in command list")
206-
self._write_command("command_list_end")
202+
raise CommandListError('Not in command list')
203+
self._write_command('command_list_end')
207204
deferred = defer.Deferred()
208205
deferred.addCallback(self._parse_command_list_end)
209206
self._state[-1].append(deferred)

0 commit comments

Comments
 (0)
Please sign in to comment.