forked from wmcbrine/pytivo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2to3_pytivo.log
5374 lines (4855 loc) · 192 KB
/
2to3_pytivo.log
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--- pytivo/beacon.py (original)
+++ pytivo/beacon.py (refactored)
@@ -5,7 +5,7 @@
import time
import uuid
from threading import Timer
-from urllib import quote
+from urllib.parse import quote
import zeroconf
@@ -165,8 +165,8 @@
if result < 0:
break
packet = packet[result:]
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
def start(self):
self.send_beacon()
@@ -196,7 +196,7 @@
def listen(self):
""" For the direct-connect, TCP-style beacon """
- import thread
+ import _thread
def server():
TCPSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -215,7 +215,7 @@
client.close()
- thread.start_new_thread(server, ())
+ _thread.start_new_thread(server, ())
def get_name(self, address):
""" Exchange beacons, and extract the machine name. """
--- pytivo/config.py (original)
+++ pytivo/config.py (refactored)
@@ -1,4 +1,4 @@
-import ConfigParser
+import configparser
import getopt
import logging
import logging.config
@@ -7,7 +7,8 @@
import socket
import sys
import uuid
-from ConfigParser import NoOptionError
+from configparser import NoOptionError
+from functools import reduce
class Bdict(dict):
def getboolean(self, x):
@@ -28,8 +29,8 @@
try:
opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
- except getopt.GetoptError, msg:
- print msg
+ except getopt.GetoptError as msg:
+ print(msg)
for opt, value in opts:
if opt in ('-c', '--config'):
@@ -47,11 +48,11 @@
bin_paths = {}
- config = ConfigParser.ConfigParser()
+ config = configparser.ConfigParser()
configs_found = config.read(config_files)
if not configs_found:
- print ('WARNING: pyTivo.conf does not exist.\n' +
- 'Assuming default values.')
+ print(('WARNING: pyTivo.conf does not exist.\n' +
+ 'Assuming default values.'))
configs_found = config_files[-1:]
for section in config.sections():
@@ -71,7 +72,7 @@
f.close()
def tivos_by_ip(tivoIP):
- for key, value in tivos.items():
+ for key, value in list(tivos.items()):
if value['address'] == tivoIP:
return key
--- pytivo/httpserver.py (original)
+++ pytivo/httpserver.py (refactored)
@@ -1,5 +1,5 @@
-import BaseHTTPServer
-import SocketServer
+import http.server
+import socketserver
import cgi
import gzip
import logging
@@ -8,9 +8,9 @@
import shutil
import socket
import time
-from cStringIO import StringIO
+from io import StringIO
from email.utils import formatdate
-from urllib import unquote_plus, quote
+from urllib.parse import unquote_plus, quote
from xml.sax.saxutils import escape
from Cheetah.Template import Template
@@ -48,13 +48,13 @@
RELOAD = '<p>The <a href="%s">page</a> will reload in %d seconds.</p>'
UNSUP = '<h3>Unsupported Command</h3> <p>Query:</p> <ul>%s</ul>'
-class TivoHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
+class TivoHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
def __init__(self, server_address, RequestHandlerClass):
self.containers = {}
self.stop = False
self.restart = False
self.logger = logging.getLogger('pyTivo')
- BaseHTTPServer.HTTPServer.__init__(self, server_address,
+ http.server.HTTPServer.__init__(self, server_address,
RequestHandlerClass)
self.daemon_threads = True
@@ -81,13 +81,13 @@
def set_service_status(self, status):
self.in_service = status
-class TivoHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
+class TivoHTTPHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
self.wbufsize = 0x10000
self.server_version = 'pyTivo/1.0'
self.protocol_version = 'HTTP/1.1'
self.sys_version = ''
- BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request,
+ http.server.BaseHTTPRequestHandler.__init__(self, request,
client_address, server)
def address_string(self):
@@ -238,7 +238,7 @@
def handle_file(self, query, splitpath):
if '..' not in splitpath: # Protect against path exploits
## Pass it off to a plugin?
- for name, container in self.server.containers.items():
+ for name, container in list(self.server.containers.items()):
if splitpath[0] == name:
self.cname = name
self.container = container
@@ -313,7 +313,7 @@
'tivo-photos'):
settings['content_type'] = mime
tsncontainers.append((section, settings))
- except Exception, msg:
+ except Exception as msg:
self.server.logger.error(section + ' - ' + str(msg))
t = Template(file=os.path.join(SCRIPTDIR, 'templates',
'root_container.tmpl'),
@@ -358,7 +358,7 @@
def unsupported(self, query):
message = UNSUP % '\n'.join(['<li>%s: %s</li>' % (key, repr(value))
- for key, value in query.items()])
+ for key, value in list(query.items())])
text = BASE_HTML % message
self.send_html(text, code=404)
--- pytivo/lrucache.py (original)
+++ pytivo/lrucache.py (refactored)
@@ -38,7 +38,7 @@
"""
-from __future__ import generators
+
import time
from heapq import heappush, heappop, heapify
@@ -118,9 +118,9 @@
def __init__(self, size=DEFAULT_SIZE):
# Check arguments
if size <= 0:
- raise ValueError, size
- elif type(size) is not type(0):
- raise TypeError, size
+ raise ValueError(size)
+ elif not isinstance(size, type(0)):
+ raise TypeError(size)
object.__init__(self)
self.__heap = []
self.__dict = {}
@@ -133,10 +133,10 @@
return len(self.__heap)
def __contains__(self, key):
- return self.__dict.has_key(key)
+ return key in self.__dict
def __setitem__(self, key, obj):
- if self.__dict.has_key(key):
+ if key in self.__dict:
node = self.__dict[key]
node.obj = obj
node.atime = time.time()
@@ -145,7 +145,7 @@
else:
# size may have been reset, so we loop
overage = len(self.__heap) - self.size + 1
- for i in xrange(overage):
+ for i in range(overage):
lru = heappop(self.__heap)
del self.__dict[lru.key]
node = self.__Node(key, obj, time.time())
@@ -153,7 +153,7 @@
heappush(self.__heap, node)
def __getitem__(self, key):
- if not self.__dict.has_key(key):
+ if key not in self.__dict:
raise CacheKeyError(key)
else:
node = self.__dict[key]
@@ -162,7 +162,7 @@
return node.obj
def __delitem__(self, key):
- if not self.__dict.has_key(key):
+ if key not in self.__dict:
raise CacheKeyError(key)
else:
node = self.__dict[key]
@@ -183,7 +183,7 @@
# automagically shrink heap on resize
if name == 'size':
overage = len(self.__heap) - value
- for i in xrange(overage):
+ for i in range(overage):
lru = heappop(self.__heap)
del self.__dict[lru.key]
@@ -194,7 +194,7 @@
"""Return the last modification time for the cache record with key.
May be useful for cache instances where the stored values can get
'stale', such as caching file or network resource contents."""
- if not self.__dict.has_key(key):
+ if key not in self.__dict:
raise CacheKeyError(key)
else:
node = self.__dict[key]
@@ -202,21 +202,21 @@
if __name__ == "__main__":
cache = LRUCache(25)
- print cache
+ print(cache)
for i in range(50):
cache[i] = str(i)
- print cache
+ print(cache)
if 46 in cache:
del cache[46]
- print cache
+ print(cache)
cache.size = 10
- print cache
+ print(cache)
cache[46] = '46'
- print cache
- print len(cache)
+ print(cache)
+ print(len(cache))
for c in cache:
- print c
- print cache
- print cache.mtime(46)
+ print(c)
+ print(cache)
+ print(cache.mtime(46))
for c in cache:
- print c
+ print(c)
--- pytivo/metadata.py (original)
+++ pytivo/metadata.py (refactored)
@@ -133,7 +133,7 @@
len_desc = 0
try:
- mp4meta = mutagen.File(unicode(full_path, 'utf-8'))
+ mp4meta = mutagen.File(str(full_path, 'utf-8'))
assert(mp4meta)
except:
mp4_cache[full_path] = {}
@@ -148,8 +148,8 @@
isTVShow = (mp4meta['stik'] == mutagen.mp4.MediaKind.TV_SHOW)
else:
isTVShow = 'tvsh' in mp4meta
- for key, value in mp4meta.items():
- if type(value) == list:
+ for key, value in list(mp4meta.items()):
+ if isinstance(value, list):
value = value[0]
if key in keys:
metadata[keys[key]] = value
@@ -174,7 +174,7 @@
tves = '00'
if 'tves' in mp4meta:
tvesValue = mp4meta['tves']
- if type(tvesValue) == list:
+ if isinstance(tvesValue, list):
tvesValue = tvesValue[0]
tves = str(tvesValue)
if len(tves) < 2:
@@ -259,7 +259,7 @@
try:
if tag in rawmeta:
value = rawmeta[tag][0]
- if type(value) not in (str, unicode):
+ if type(value) not in (str, str):
value = str(value)
if value:
metadata[tagname] = value
@@ -292,7 +292,7 @@
return dvrms_cache[full_path]
try:
- rawmeta = mutagen.File(unicode(full_path, 'utf-8'))
+ rawmeta = mutagen.File(str(full_path, 'utf-8'))
assert(rawmeta)
except:
dvrms_cache[full_path] = {}
@@ -307,7 +307,7 @@
'DESCRIPTION': 'description', 'YEAR': 'movieYear',
'EPISODENUM': 'episodeNumber'}
metadata = {}
- path = os.path.dirname(unicode(full_path, 'utf-8'))
+ path = os.path.dirname(str(full_path, 'utf-8'))
eyetvp = [x for x in os.listdir(path) if x.endswith('.eyetvp')][0]
eyetvp = os.path.join(path, eyetvp)
try:
@@ -341,7 +341,7 @@
def from_text(full_path):
metadata = {}
- full_path = unicode(full_path, 'utf-8')
+ full_path = str(full_path, 'utf-8')
path, name = os.path.split(full_path)
title, ext = os.path.splitext(name)
@@ -400,7 +400,7 @@
base_path, name = os.path.split(full_path)
title, ext = os.path.splitext(name)
if not mtime:
- mtime = os.path.getmtime(unicode(full_path, 'utf-8'))
+ mtime = os.path.getmtime(str(full_path, 'utf-8'))
try:
originalAirDate = datetime.utcfromtimestamp(mtime)
except:
@@ -533,7 +533,7 @@
xmldoc = None
try:
xmldoc = minidom.parseString(os.linesep.join(nfo_data))
- except expat.ExpatError, err:
+ except expat.ExpatError as err:
if expat.ErrorString(err.code) == expat.errors.XML_ERROR_INVALID_TOKEN:
# might be a URL outside the xml
while len(nfo_data) > err.lineno:
@@ -699,7 +699,7 @@
return metadata
def _tdcat_bin(tdcat_path, full_path, tivo_mak):
- fname = unicode(full_path, 'utf-8')
+ fname = str(full_path, 'utf-8')
if mswindows:
fname = fname.encode('cp1252')
tcmd = [tdcat_path, '-m', tivo_mak, '-2', fname]
@@ -716,7 +716,7 @@
tfile.close()
count = 0
- for i in xrange(chunks):
+ for i in range(chunks):
chunk_size, data_size, id, enc = struct.unpack('>LLHH',
rawdata[count:count + 12])
count += 12
@@ -759,7 +759,7 @@
return metadata
def force_utf8(text):
- if type(text) == str:
+ if isinstance(text, str):
try:
text = text.decode('utf8')
except:
@@ -772,7 +772,7 @@
def dump(output, metadata):
for key in metadata:
value = metadata[key]
- if type(value) == list:
+ if isinstance(value, list):
for item in value:
output.write('%s: %s\n' % (key, item.encode('utf-8')))
else:
--- pytivo/plugin.py (original)
+++ pytivo/plugin.py (refactored)
@@ -5,17 +5,17 @@
import threading
import time
import unicodedata
-import urllib
+import urllib.request, urllib.parse, urllib.error
from Cheetah.Filters import Filter
from lrucache import LRUCache
if os.path.sep == '/':
- quote = urllib.quote
- unquote = urllib.unquote_plus
+ quote = urllib.parse.quote
+ unquote = urllib.parse.unquote_plus
else:
- quote = lambda x: urllib.quote(x.replace(os.path.sep, '/'))
- unquote = lambda x: os.path.normpath(urllib.unquote_plus(x))
+ quote = lambda x: urllib.parse.quote(x.replace(os.path.sep, '/'))
+ unquote = lambda x: os.path.normpath(urllib.parse.unquote_plus(x))
class Error:
CONTENT_TYPE = 'text/html'
@@ -27,8 +27,8 @@
plugin = getattr(module, module.CLASS_NAME)()
return plugin
except ImportError:
- print 'Error no', name, 'plugin exists. Check the type ' \
- 'setting for your share.'
+ print('Error no', name, 'plugin exists. Check the type ' \
+ 'setting for your share.')
return Error
class EncodeUnicode(Filter):
@@ -37,7 +37,7 @@
encoding = kw.get('encoding', 'utf8')
- if type(val) == str:
+ if isinstance(val, str):
try:
val = val.decode('utf8')
except:
@@ -45,7 +45,7 @@
val = val.decode('macroman')
else:
val = val.decode('cp1252')
- elif type(val) != unicode:
+ elif not isinstance(val, str):
val = str(val)
return val.encode(encoding)
@@ -70,7 +70,7 @@
pass
def send_file(self, handler, path, query):
- handler.send_content_file(unicode(path, 'utf-8'))
+ handler.send_content_file(str(path, 'utf-8'))
def get_local_base_path(self, handler, query):
return os.path.normpath(handler.container['path'])
@@ -112,7 +112,7 @@
if not '://' in anchor:
anchor = os.path.normpath(anchor)
- if type(files[0]) == str:
+ if isinstance(files[0], str):
filenames = files
else:
filenames = [x.name for x in files]
@@ -147,7 +147,7 @@
def __init__(self, name, isdir):
self.name = name
self.isdir = isdir
- st = os.stat(unicode(name, 'utf-8'))
+ st = os.stat(str(name, 'utf-8'))
self.mdate = st.st_mtime
self.size = st.st_size
@@ -160,7 +160,7 @@
def build_recursive_list(path, recurse=True):
files = []
- path = unicode(path, 'utf-8')
+ path = str(path, 'utf-8')
try:
for f in os.listdir(path):
if f.startswith('.'):
@@ -193,7 +193,7 @@
if path in rc and rc.mtime(path) + 300 >= time.time():
filelist = rc[path]
else:
- updated = os.path.getmtime(unicode(path, 'utf-8'))
+ updated = os.path.getmtime(str(path, 'utf-8'))
if path in dc and dc.mtime(path) >= updated:
filelist = dc[path]
for p in rc:
--- pytivo/turing.py (original)
+++ pytivo/turing.py (refactored)
@@ -69,7 +69,7 @@
__author__ = 'William McBrine <[email protected]>'
__version__ = '1.5'
-from itertools import izip
+
from struct import pack, unpack
# 8->32 _SBOX generated by Millan et. al. at Queensland University of
@@ -271,7 +271,7 @@
sh1 = 8 * l
sh2 = 24 - sh1
mask = (0xff << sh2) ^ 0xffffffff
- for j in xrange(256):
+ for j in range(256):
w = 0
k = j
for i, key in enumerate(mkey):
@@ -322,10 +322,10 @@
self._step()
things = _mixwords([self.lfsr[n] for n in (16, 13, 6, 1, 0)])
things = _mixwords([self._strans(i, n)
- for i, n in izip(things, (0, 1, 2, 3, 0))])
+ for i, n in zip(things, (0, 1, 2, 3, 0))])
self._step(3)
things = [(i + self.lfsr[n]) & 0xffffffff
- for i, n in izip(things, (14, 12, 8, 1, 0))]
+ for i, n in zip(things, (14, 12, 8, 1, 0))]
self._step()
return pack('>5L', *things)
@@ -352,4 +352,4 @@
fmt = '%dB' % len(source)
d2 = unpack(fmt, source)
x2 = unpack(fmt, xor_data)
- return pack(fmt, *(a ^ b for a, b in izip(d2, x2)))
+ return pack(fmt, *(a ^ b for a, b in zip(d2, x2)))
--- pytivo/zeroconf.py (original)
+++ pytivo/zeroconf.py (refactored)
@@ -32,6 +32,7 @@
import threading
import select
import traceback
+from functools import reduce
__all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"]
@@ -419,7 +420,7 @@
def readQuestions(self):
"""Reads questions section of packet"""
- for i in xrange(self.numQuestions):
+ for i in range(self.numQuestions):
name = self.readName()
type, clazz = self.unpack('!HH')
@@ -450,7 +451,7 @@
"""Reads the answers, authorities and additionals section of the
packet"""
n = self.numAnswers + self.numAuthorities + self.numAdditionals
- for i in xrange(n):
+ for i in range(n):
domain = self.readName()
type, clazz, ttl, length = self.unpack('!HHiH')
@@ -489,7 +490,7 @@
def readUTF(self, offset, length):
"""Reads a UTF-8 string of a given length from the packet"""
- return unicode(self.data[offset:offset+length], 'utf-8', 'replace')
+ return str(self.data[offset:offset+length], 'utf-8', 'replace')
def readName(self):
"""Reads a domain name from the packet"""
@@ -730,7 +731,7 @@
"""Returns a list of all entries"""
def add(x, y): return x + y
try:
- return reduce(add, self.cache.values())
+ return reduce(add, list(self.cache.values()))
except:
return []
@@ -779,7 +780,7 @@
def getReaders(self):
result = []
self.condition.acquire()
- result = self.readers.keys()
+ result = list(self.readers.keys())
self.condition.release()
return result
@@ -815,7 +816,7 @@
def handle_read(self):
try:
data, (addr, port) = self.zc.socket.recvfrom(_MAX_MSG_ABSOLUTE)
- except socket.error, e:
+ except socket.error as e:
# If the socket was closed by another thread -- which happens
# regularly on shutdown -- an EBADF exception is thrown here.
# Ignore it.
@@ -928,7 +929,7 @@
if self.nextTime <= now:
out = DNSOutgoing(_FLAGS_QR_QUERY)
out.addQuestion(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
- for record in self.services.values():
+ for record in list(self.services.values()):
if not record.isExpired(now):
out.addAnswerAtTime(record, now)
self.zc.send(out)
@@ -1339,7 +1340,7 @@
now = currentTimeMillis()
continue
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
- for info in self.services.values():
+ for info in list(self.services.values()):
out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR,
_CLASS_IN, 0, info.name), 0)
out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV,
@@ -1446,13 +1447,13 @@
for question in msg.questions:
if question.type == _TYPE_PTR:
if question.name == "_services._dns-sd._udp.local.":
- for stype in self.servicetypes.keys():
+ for stype in list(self.servicetypes.keys()):
if out is None:
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
out.addAnswer(msg,
DNSPointer("_services._dns-sd._udp.local.",
_TYPE_PTR, _CLASS_IN, _DNS_TTL, stype))
- for service in self.services.values():
+ for service in list(self.services.values()):
if question.name == service.type:
if out is None:
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
@@ -1466,7 +1467,7 @@
# Answer A record queries for any service addresses we know
if question.type in (_TYPE_A, _TYPE_ANY):
- for service in self.services.values():
+ for service in list(self.services.values()):
if service.server == question.name.lower():
out.addAnswer(msg, DNSAddress(question.name,
_TYPE_A, _CLASS_IN | _CLASS_UNIQUE,
@@ -1527,26 +1528,26 @@
# query (for Zoe), and service unregistration.
if __name__ == '__main__':
- print "Multicast DNS Service Discovery for Python, version", __version__
+ print("Multicast DNS Service Discovery for Python, version", __version__)
r = Zeroconf()
- print "1. Testing registration of a service..."
+ print("1. Testing registration of a service...")
desc = {'version':'0.10','a':'test value', 'b':'another value'}
info = ServiceInfo("_http._tcp.local.",
"My Service Name._http._tcp.local.",
socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc)
- print " Registering service..."
+ print(" Registering service...")
r.registerService(info)
- print " Registration done."
- print "2. Testing query of service information..."
- print " Getting ZOE service:",
- print str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))
- print " Query done."
- print "3. Testing query of own service..."
- print " Getting self:",
- print str(r.getServiceInfo("_http._tcp.local.",
- "My Service Name._http._tcp.local."))
- print " Query done."
- print "4. Testing unregister of service information..."
+ print(" Registration done.")
+ print("2. Testing query of service information...")
+ print(" Getting ZOE service:", end=' ')
+ print(str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local.")))
+ print(" Query done.")
+ print("3. Testing query of own service...")
+ print(" Getting self:", end=' ')
+ print(str(r.getServiceInfo("_http._tcp.local.",
+ "My Service Name._http._tcp.local.")))
+ print(" Query done.")
+ print("4. Testing unregister of service information...")
r.unregisterService(info)
- print " Unregister done."
+ print(" Unregister done.")
r.close()
--- pytivo/Cheetah/CacheRegion.py (original)
+++ pytivo/Cheetah/CacheRegion.py (refactored)
@@ -118,7 +118,7 @@
def clear(self):
" drop all the caches stored in this cache region "
- for cacheItemId in self._cacheItems.keys():
+ for cacheItemId in list(self._cacheItems.keys()):
cacheItem = self._cacheItems[cacheItemId]
cacheItem.clear()
del self._cacheItems[cacheItemId]
@@ -133,7 +133,7 @@
"""
cacheItemID = hashlib.md5(str(cacheItemID)).hexdigest()
- if not self._cacheItems.has_key(cacheItemID):
+ if cacheItemID not in self._cacheItems:
cacheItem = self._cacheItemClass(
cacheItemID=cacheItemID, cacheStore=self._wrappedCacheDataStore)
self._cacheItems[cacheItemID] = cacheItem
--- pytivo/Cheetah/CacheStore.py (original)
+++ pytivo/Cheetah/CacheStore.py (refactored)
@@ -46,12 +46,12 @@
self._data[key] = (val, time)
def add(self, key, val, time=0):
- if self._data.has_key(key):
+ if key in self._data:
raise Error('a value for key %r is already in the cache'%key)
self._data[key] = (val, time)
def replace(self, key, val, time=0):
- if self._data.has_key(key):
+ if key in self._data:
raise Error('a value for key %r is already in the cache'%key)
self._data[key] = (val, time)
--- pytivo/Cheetah/Compiler.py (original)
+++ pytivo/Cheetah/Compiler.py (refactored)
@@ -27,7 +27,7 @@
import time
import random
import warnings
-import __builtin__
+import builtins
import copy
from Cheetah.Version import Version, VersionTuple
@@ -36,8 +36,8 @@
from Cheetah import ErrorCatchers
from Cheetah import NameMapper
from Cheetah.Parser import Parser, ParseError, specialVarRE, \
- STATIC_CACHE, REFRESH_CACHE, SET_LOCAL, SET_GLOBAL,SET_MODULE, \
- unicodeDirectiveRE, encodingDirectiveRE,escapedNewlineRE
+ STATIC_CACHE, REFRESH_CACHE, SET_LOCAL, SET_GLOBAL, SET_MODULE, \
+ unicodeDirectiveRE, encodingDirectiveRE, escapedNewlineRE
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
VFFSL=valueFromFrameOrSearchList
@@ -59,35 +59,35 @@
'useAutocalling': True, # detect and call callable()'s, requires NameMapper
'useStackFrames': True, # use NameMapper.valueFromFrameOrSearchList
# rather than NameMapper.valueFromSearchList
- 'useErrorCatcher':False,
- 'alwaysFilterNone':True, # filter out None, before the filter is called
- 'useFilters':True, # use str instead if =False
- 'includeRawExprInFilterArgs':True,
+ 'useErrorCatcher': False,
+ 'alwaysFilterNone': True, # filter out None, before the filter is called
+ 'useFilters': True, # use str instead if =False
+ 'includeRawExprInFilterArgs': True,
#'lookForTransactionAttr':False,
- 'autoAssignDummyTransactionToSelf':False,
- 'useKWsDictArgForPassingTrans':True,
+ 'autoAssignDummyTransactionToSelf': False,
+ 'useKWsDictArgForPassingTrans': True,
## controlling the aesthetic appearance / behaviour of generated code
'commentOffset': 1,
- 'outputRowColComments':True,
+ 'outputRowColComments': True,
# should #block's be wrapped in a comment in the template's output
'includeBlockMarkers': False,
- 'blockMarkerStart':('\n<!-- START BLOCK: ',' -->\n'),
- 'blockMarkerEnd':('\n<!-- END BLOCK: ',' -->\n'),
- 'defDocStrMsg':'Autogenerated by CHEETAH: The Python-Powered Template Engine',
+ 'blockMarkerStart': ('\n<!-- START BLOCK: ', ' -->\n'),
+ 'blockMarkerEnd': ('\n<!-- END BLOCK: ', ' -->\n'),
+ 'defDocStrMsg': 'Autogenerated by CHEETAH: The Python-Powered Template Engine',
'setup__str__method': False,
- 'mainMethodName':'respond',
- 'mainMethodNameForSubclasses':'writeBody',
+ 'mainMethodName': 'respond',
+ 'mainMethodNameForSubclasses': 'writeBody',
'indentationStep': ' '*4,
'initialMethIndentLevel': 2,
- 'monitorSrcFile':False,
+ 'monitorSrcFile': False,
'outputMethodsBeforeAttributes': True,
'addTimestampsToCompilerOutput': True,
## customizing the #extends directive
- 'autoImportForExtendsDirective':True,
- 'handlerForExtendsDirective':None, # baseClassName = handler(compiler, baseClassName)
+ 'autoImportForExtendsDirective': True,
+ 'handlerForExtendsDirective': None, # baseClassName = handler(compiler, baseClassName)
# a callback hook for customizing the
# #extends directive. It can manipulate
# the compiler's state if needed.
@@ -96,39 +96,39 @@
# input filtering/restriction
# use lower case keys here!!
- 'disabledDirectives':[], # list of directive keys, without the start token
- 'enabledDirectives':[], # list of directive keys, without the start token
-
- 'disabledDirectiveHooks':[], # callable(parser, directiveKey)
- 'preparseDirectiveHooks':[], # callable(parser, directiveKey)
- 'postparseDirectiveHooks':[], # callable(parser, directiveKey)
- 'preparsePlaceholderHooks':[], # callable(parser)
- 'postparsePlaceholderHooks':[], # callable(parser)
+ 'disabledDirectives': [], # list of directive keys, without the start token
+ 'enabledDirectives': [], # list of directive keys, without the start token
+
+ 'disabledDirectiveHooks': [], # callable(parser, directiveKey)
+ 'preparseDirectiveHooks': [], # callable(parser, directiveKey)
+ 'postparseDirectiveHooks': [], # callable(parser, directiveKey)
+ 'preparsePlaceholderHooks': [], # callable(parser)
+ 'postparsePlaceholderHooks': [], # callable(parser)
# the above hooks don't need to return anything
- 'expressionFilterHooks':[], # callable(parser, expr, exprType, rawExpr=None, startPos=None)
+ 'expressionFilterHooks': [], # callable(parser, expr, exprType, rawExpr=None, startPos=None)
# exprType is the name of the directive, 'psp', or 'placeholder'. all
# lowercase. The filters *must* return the expr or raise an exception.
# They can modify the expr if needed.
- 'templateMetaclass':None, # strictly optional. Only works with new-style baseclasses
-
-
- 'i18NFunctionName':'self.i18n',
+ 'templateMetaclass': None, # strictly optional. Only works with new-style baseclasses
+
+
+ 'i18NFunctionName': 'self.i18n',
## These are used in the parser, but I've put them here for the time being to
## facilitate separating the parser and compiler:
- 'cheetahVarStartToken':'$',
- 'commentStartToken':'##',
- 'multiLineCommentStartToken':'#*',
- 'multiLineCommentEndToken':'*#',
- 'gobbleWhitespaceAroundMultiLineComments':True,
- 'directiveStartToken':'#',
- 'directiveEndToken':'#',
- 'allowWhitespaceAfterDirectiveStartToken':False,
- 'PSPStartToken':'<%',
- 'PSPEndToken':'%>',
- 'EOLSlurpToken':'#',
+ 'cheetahVarStartToken': '$',
+ 'commentStartToken': '##',
+ 'multiLineCommentStartToken': '#*',
+ 'multiLineCommentEndToken': '*#',
+ 'gobbleWhitespaceAroundMultiLineComments': True,
+ 'directiveStartToken': '#',
+ 'directiveEndToken': '#',
+ 'allowWhitespaceAfterDirectiveStartToken': False,
+ 'PSPStartToken': '<%',
+ 'PSPEndToken': '%>',
+ 'EOLSlurpToken': '#',
'gettextTokens': ["_", "N_", "ngettext"],
'allowExpressionsInExtendsDirective': False, # the default restricts it to
# accepting dotted names
@@ -419,13 +419,13 @@
ind = self._indent*2
docStr = (ind + '"""\n' + ind +
- ('\n' + ind).join([ln.replace('"""',"'''") for ln in self._docStringLines]) +
+ ('\n' + ind).join([ln.replace('"""', "'''") for ln in self._docStringLines]) +
'\n' + ind + '"""\n')
return docStr
## methods for adding code
def addMethDocString(self, line):
- self._docStringLines.append(line.replace('%','%%'))
+ self._docStringLines.append(line.replace('%', '%%'))
def addChunk(self, chunk):
self.commitStrConst()
@@ -458,7 +458,7 @@
self.addChunk("if _v is not None: write(str(_v))")
else:
if self.setting('useFilters'):
- self.addChunk("write(_filter(%s%s))"%(chunk,filterArgs))
+ self.addChunk("write(_filter(%s%s))"%(chunk, filterArgs))
else:
self.addChunk("write(str(%s))"%chunk)
@@ -493,7 +493,7 @@
if not strConst:
return
else:
- reprstr = repr(strConst).replace('\\012','\n')
+ reprstr = repr(strConst).replace('\\012', '\n')
i = 0
out = []
if reprstr.startswith('u'):
@@ -585,7 +585,7 @@
splitPos2 = LVALUE.find('[')
if splitPos1 > 0 and splitPos2==-1:
splitPos = splitPos1
- elif splitPos1 > 0 and splitPos1 < max(splitPos2,0):
+ elif splitPos1 > 0 and splitPos1 < max(splitPos2, 0):
splitPos = splitPos1
else:
splitPos = splitPos2
@@ -619,7 +619,7 @@
def addRepeat(self, expr, lineCol=None):
#the _repeatCount stuff here allows nesting of #repeat directives
self._repeatCount = getattr(self, "_repeatCount", -1) + 1
- self.addFor('for __i%s in range(%s)' % (self._repeatCount,expr), lineCol=lineCol)
+ self.addFor('for __i%s in range(%s)' % (self._repeatCount, expr), lineCol=lineCol)
def addIndentingDirective(self, expr, lineCol=None):
if expr and not expr[-1] == ':':
@@ -663,7 +663,7 @@
self.dedent()
def addElse(self, expr, dedent=True, lineCol=None):
- expr = re.sub(r'else[ \f\t]+if','elif', expr)
+ expr = re.sub(r'else[ \f\t]+if', 'elif', expr)
self.addReIndentingDirective(expr, dedent=dedent, lineCol=lineCol)
def addElif(self, expr, dedent=True, lineCol=None):
@@ -700,7 +700,7 @@
def addYield(self, expr):
assert not self._hasReturnStatement
self._isGenerator = True
- if expr.replace('yield','').strip():
+ if expr.replace('yield', '').strip():
self.addChunk(expr)
else:
self.addChunk('if _dummyTrans:')
@@ -767,9 +767,9 @@
# @@TR: we should add some runtime logging to this
ID = self.nextCacheID()
- interval = cacheInfo.get('interval',None)
- test = cacheInfo.get('test',None)
- customID = cacheInfo.get('id',None)
+ interval = cacheInfo.get('interval', None)
+ test = cacheInfo.get('test', None)
+ customID = cacheInfo.get('id', None)
if customID:
ID = customID
varyBy = cacheInfo.get('varyBy', repr(ID))
@@ -934,7 +934,7 @@
captureDetails.assignTo = assignTo
captureDetails.lineCol = lineCol
- self._captureRegionsStack.append((ID,captureDetails)) # attrib of current methodCompiler
+ self._captureRegionsStack.append((ID, captureDetails)) # attrib of current methodCompiler
self.addChunk('## START CAPTURE REGION: '+ID
+' '+assignTo
+' at line %s, col %s'%lineCol + ' in the source.')
@@ -1013,11 +1013,11 @@
def _setupState(self):
MethodCompiler._setupState(self)
- self._argStringList = [ ("self",None) ]
+ self._argStringList = [ ("self", None) ]
self._streamingEnabled = True
def _useKWsDictArgForPassingTrans(self):
- alreadyHasTransArg = [argname for argname,defval in self._argStringList
+ alreadyHasTransArg = [argname for argname, defval in self._argStringList
if argname=='trans']
return (self.methodName()!='respond'
and not alreadyHasTransArg
@@ -1034,12 +1034,12 @@
if self._streamingEnabled:
kwargsName = None
positionalArgsListName = None
- for argname,defval in self._argStringList:
+ for argname, defval in self._argStringList:
if argname.strip().startswith('**'):
- kwargsName = argname.strip().replace('**','')
+ kwargsName = argname.strip().replace('**', '')
break
elif argname.strip().startswith('*'):
- positionalArgsListName = argname.strip().replace('*','')
+ positionalArgsListName = argname.strip().replace('*', '')
if not kwargsName and self._useKWsDictArgForPassingTrans():
kwargsName = 'KWS'
@@ -1114,7 +1114,7 @@
self.addChunk('return _dummyTrans and trans.response().getvalue() or ""')
def addMethArg(self, name, defVal=None):
- self._argStringList.append( (name,defVal) )
+ self._argStringList.append( (name, defVal) )
def methodSignature(self):