Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 9a99aa7

Browse filesBrowse files
committed
Add Python 3 support
1 parent 09a1f4f commit 9a99aa7
Copy full SHA for 9a99aa7

File tree

Expand file treeCollapse file tree

4 files changed

+96
-60
lines changed
Filter options
Expand file treeCollapse file tree

4 files changed

+96
-60
lines changed

‎test_zeroconf.py

Copy file name to clipboardExpand all lines: test_zeroconf.py
+5-3Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import struct
77
import unittest
88

9+
from zeroconf import byte_ord, xrange
10+
911

1012
class PacketGeneration(unittest.TestCase):
1113

@@ -43,19 +45,19 @@ def testTransactionID(self):
4345
"""ID must be zero in a DNS-SD packet"""
4446
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
4547
bytes = generated.packet()
46-
id = ord(bytes[0]) << 8 | ord(bytes[1])
48+
id = byte_ord(bytes[0]) << 8 | byte_ord(bytes[1])
4749
self.assertEqual(id, 0)
4850

4951
def testQueryHeaderBits(self):
5052
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
5153
bytes = generated.packet()
52-
flags = ord(bytes[2]) << 8 | ord(bytes[3])
54+
flags = byte_ord(bytes[2]) << 8 | byte_ord(bytes[3])
5355
self.assertEqual(flags, 0x0)
5456

5557
def testResponseHeaderBits(self):
5658
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
5759
bytes = generated.packet()
58-
flags = ord(bytes[2]) << 8 | ord(bytes[3])
60+
flags = byte_ord(bytes[2]) << 8 | byte_ord(bytes[3])
5961
self.assertEqual(flags, 0x8000)
6062

6163
def testNumbers(self):

‎zeroconf.py

Copy file name to clipboardExpand all lines: zeroconf.py
+70-41Lines changed: 70 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import absolute_import, division, print_function, unicode_literals
2+
13
""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine
24
Copyright 2003 Paul Scott-Murphy, 2014 William McBrine
35
@@ -31,9 +33,30 @@
3133
import threading
3234
import select
3335
import traceback
36+
from functools import reduce
3437

3538
__all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"]
3639

40+
try:
41+
xrange = xrange
42+
except NameError:
43+
xrange = range
44+
45+
try:
46+
unicode
47+
except NameError:
48+
unicode = str
49+
50+
if isinstance(chr(8), unicode):
51+
byte_chr = lambda num: bytes([num])
52+
else:
53+
byte_chr = chr
54+
55+
if isinstance(bytes([8])[0], int):
56+
byte_ord = lambda x: x
57+
else:
58+
byte_ord = ord
59+
3760
# hook for threads
3861

3962
_GLOBAL_DONE = False
@@ -359,6 +382,7 @@ class DNSText(DNSRecord):
359382
"""A DNS text record"""
360383

361384
def __init__(self, name, type, clazz, ttl, text):
385+
assert isinstance(text, bytes)
362386
DNSRecord.__init__(self, name, type, clazz, ttl)
363387
self.text = text
364388

@@ -437,24 +461,24 @@ def unpack(self, format):
437461
def readHeader(self):
438462
"""Reads header portion of packet"""
439463
(self.id, self.flags, self.numQuestions, self.numAnswers,
440-
self.numAuthorities, self.numAdditionals) = self.unpack('!6H')
464+
self.numAuthorities, self.numAdditionals) = self.unpack(b'!6H')
441465

442466
def readQuestions(self):
443467
"""Reads questions section of packet"""
444468
for i in xrange(self.numQuestions):
445469
name = self.readName()
446-
type, clazz = self.unpack('!HH')
470+
type, clazz = self.unpack(b'!HH')
447471

448472
question = DNSQuestion(name, type, clazz)
449473
self.questions.append(question)
450474

451475
def readInt(self):
452476
"""Reads an integer from the packet"""
453-
return self.unpack('!I')[0]
477+
return self.unpack(b'!I')[0]
454478

455479
def readCharacterString(self):
456480
"""Reads a character string from the packet"""
457-
length = ord(self.data[self.offset])
481+
length = byte_ord(self.data[self.offset])
458482
self.offset += 1
459483
return self.readString(length)
460484

@@ -466,15 +490,15 @@ def readString(self, length):
466490

467491
def readUnsignedShort(self):
468492
"""Reads an unsigned short from the packet"""
469-
return self.unpack('!H')[0]
493+
return self.unpack(b'!H')[0]
470494

471495
def readOthers(self):
472496
"""Reads the answers, authorities and additionals section of the
473497
packet"""
474498
n = self.numAnswers + self.numAuthorities + self.numAdditionals
475499
for i in xrange(n):
476500
domain = self.readName()
477-
type, clazz, ttl, length = self.unpack('!HHiH')
501+
type, clazz, ttl, length = self.unpack(b'!HHiH')
478502

479503
rec = None
480504
if type == _TYPE_A:
@@ -521,7 +545,7 @@ def readName(self):
521545
first = off
522546

523547
while True:
524-
length = ord(self.data[off])
548+
length = byte_ord(self.data[off])
525549
off += 1
526550
if length == 0:
527551
break
@@ -532,12 +556,14 @@ def readName(self):
532556
elif t == 0xC0:
533557
if next < 0:
534558
next = off + 1
535-
off = ((length & 0x3F) << 8) | ord(self.data[off])
559+
off = ((length & 0x3F) << 8) | byte_ord(self.data[off])
536560
if off >= first:
537-
raise "Bad domain name (circular) at " + str(off)
561+
# TODO raise more specific exception
562+
raise Exception("Bad domain name (circular) at %s" % (off,))
538563
first = off
539564
else:
540-
raise "Bad domain name at " + str(off)
565+
# TODO raise more specific exception
566+
raise Exception("Bad domain name at %s" % (off,))
541567

542568
if next >= 0:
543569
self.offset = next
@@ -594,23 +620,24 @@ def pack(self, format, value):
594620

595621
def writeByte(self, value):
596622
"""Writes a single byte to the packet"""
597-
self.pack('!c', chr(value))
623+
self.pack(b'!c', byte_chr(value))
598624

599625
def insertShort(self, index, value):
600626
"""Inserts an unsigned short in a certain position in the packet"""
601-
self.data.insert(index, struct.pack('!H', value))
627+
self.data.insert(index, struct.pack(b'!H', value))
602628
self.size += 2
603629

604630
def writeShort(self, value):
605631
"""Writes an unsigned short to the packet"""
606-
self.pack('!H', value)
632+
self.pack(b'!H', value)
607633

608634
def writeInt(self, value):
609635
"""Writes an unsigned integer to the packet"""
610-
self.pack('!I', int(value))
636+
self.pack(b'!I', int(value))
611637

612638
def writeString(self, value):
613639
"""Writes a string to the packet"""
640+
assert isinstance(value, bytes)
614641
self.data.append(value)
615642
self.size += len(value)
616643

@@ -674,7 +701,7 @@ def writeRecord(self, record, now):
674701
record.write(self)
675702
self.size -= 2
676703

677-
length = len(''.join(self.data[index:]))
704+
length = len(b''.join(self.data[index:]))
678705
self.insertShort(index, length) # Here is the short we adjusted for
679706

680707
def packet(self):
@@ -702,7 +729,7 @@ def packet(self):
702729
self.insertShort(0, 0)
703730
else:
704731
self.insertShort(0, self.id)
705-
return ''.join(self.data)
732+
return b''.join(self.data)
706733

707734

708735
class DNSCache(object):
@@ -843,7 +870,7 @@ def __init__(self, zc):
843870
def handle_read(self):
844871
try:
845872
data, (addr, port) = self.zc.socket.recvfrom(_MAX_MSG_ABSOLUTE)
846-
except socket.error, e:
873+
except socket.error as e:
847874
# If the socket was closed by another thread -- which happens
848875
# regularly on shutdown -- an EBADF exception is thrown here.
849876
# Ignore it.
@@ -1009,23 +1036,26 @@ def setProperties(self, properties):
10091036
if isinstance(properties, dict):
10101037
self.properties = properties
10111038
list = []
1012-
result = ''
1039+
result = b''
10131040
for key in properties:
10141041
value = properties[key]
1042+
if isinstance(key, unicode):
1043+
key = key.encode('utf-8')
1044+
10151045
if value is None:
1016-
suffix = ''.encode('utf-8')
1017-
elif isinstance(value, str):
1046+
suffix = b''
1047+
elif isinstance(value, unicode):
10181048
suffix = value.encode('utf-8')
10191049
elif isinstance(value, int):
10201050
if value:
1021-
suffix = 'true'
1051+
suffix = b'true'
10221052
else:
1023-
suffix = 'false'
1053+
suffix = b'false'
10241054
else:
1025-
suffix = ''.encode('utf-8')
1026-
list.append('='.join((key, suffix)))
1055+
suffix = b''
1056+
list.append(b'='.join((key, suffix)))
10271057
for item in list:
1028-
result = ''.join((result, chr(len(item)), item))
1058+
result = b''.join((result, byte_chr(len(item)), item))
10291059
self.text = result
10301060
else:
10311061
self.text = properties
@@ -1039,7 +1069,7 @@ def setText(self, text):
10391069
index = 0
10401070
strs = []
10411071
while index < end:
1042-
length = ord(text[index])
1072+
length = byte_ord(text[index])
10431073
index += 1
10441074
strs.append(text[index:index + length])
10451075
index += length
@@ -1561,26 +1591,25 @@ def close(self):
15611591
# query (for Zoe), and service unregistration.
15621592

15631593
if __name__ == '__main__':
1564-
print "Multicast DNS Service Discovery for Python, version", __version__
1594+
print("Multicast DNS Service Discovery for Python, version %s" % __version__)
15651595
r = Zeroconf()
1566-
print "1. Testing registration of a service..."
1596+
print("1. Testing registration of a service...")
15671597
desc = {'version': '0.10', 'a': 'test value', 'b': 'another value'}
15681598
info = ServiceInfo("_http._tcp.local.",
15691599
"My Service Name._http._tcp.local.",
15701600
socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc)
1571-
print " Registering service..."
1601+
print(" Registering service...")
15721602
r.registerService(info)
1573-
print " Registration done."
1574-
print "2. Testing query of service information..."
1575-
print " Getting ZOE service:",
1576-
print str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))
1577-
print " Query done."
1578-
print "3. Testing query of own service..."
1579-
print " Getting self:",
1580-
print str(r.getServiceInfo("_http._tcp.local.",
1581-
"My Service Name._http._tcp.local."))
1582-
print " Query done."
1583-
print "4. Testing unregister of service information..."
1603+
print(" Registration done.")
1604+
print("2. Testing query of service information...")
1605+
print(" Getting ZOE service: %s" % (
1606+
r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local.")))
1607+
print(" Query done.")
1608+
print("3. Testing query of own service...")
1609+
print(" Getting self: %s" % (
1610+
r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.")),)
1611+
print(" Query done.")
1612+
print("4. Testing unregister of service information...")
15841613
r.unregisterService(info)
1585-
print " Unregister done."
1614+
print(" Unregister done.")
15861615
r.close()

‎zwebbrowse.py

Copy file name to clipboardExpand all lines: zwebbrowse.py
+14-14Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,30 +14,30 @@ def __init__(self):
1414
self.r = Zeroconf()
1515

1616
def removeService(self, zeroconf, type, name):
17-
print
18-
print "Service", name, "removed"
17+
print()
18+
print("Service %s removed" % (name,))
1919

2020
def addService(self, zeroconf, type, name):
21-
print
22-
print "Service", name, "added"
23-
print " Type is", type
21+
print()
22+
print("Service %s added" % (name,))
23+
print(" Type is %s" % (type,))
2424
info = self.r.getServiceInfo(type, name)
2525
if info:
26-
print " Address is %s:%d" % (socket.inet_ntoa(info.getAddress()),
27-
info.getPort())
28-
print " Weight is %d, Priority is %d" % (info.getWeight(),
29-
info.getPriority())
30-
print " Server is", info.getServer()
26+
print(" Address is %s:%d" % (socket.inet_ntoa(info.getAddress()),
27+
info.getPort()))
28+
print(" Weight is %d, Priority is %d" % (info.getWeight(),
29+
info.getPriority()))
30+
print(" Server is", info.getServer())
3131
prop = info.getProperties()
3232
if prop:
33-
print " Properties are"
33+
print(" Properties are")
3434
for key, value in prop.items():
35-
print " %s: %s" % (key, value)
35+
print(" %s: %s" % (key, value))
3636

3737
if __name__ == '__main__':
38-
print "Multicast DNS Service Discovery for Python Browser test"
38+
print("Multicast DNS Service Discovery for Python Browser test")
3939
r = Zeroconf()
40-
print "Testing browsing for a service..."
40+
print("Testing browsing for a service...")
4141
type = "_http._tcp.local."
4242
listener = MyListener()
4343
browser = ServiceBrowser(r, type, listener)

‎zwebtest.py

Copy file name to clipboardExpand all lines: zwebtest.py
+7-2Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66

77
from zeroconf import ServiceInfo, Zeroconf
88

9+
try:
10+
raw_input
11+
except NameError:
12+
raw_input = input
13+
914
desc = {'path': '/~paulsm/'}
1015

1116
info = ServiceInfo("_http._tcp.local.",
@@ -14,9 +19,9 @@
1419
desc, "ash-2.local.")
1520

1621
r = Zeroconf()
17-
print "Registration of a service..."
22+
print("Registration of a service...")
1823
r.registerService(info)
1924
raw_input("Waiting (press Enter to exit)...")
20-
print "Unregistering..."
25+
print("Unregistering...")
2126
r.unregisterService(info)
2227
r.close()

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.