Skip to content

Commit 9979bc6

Browse files
committed
feat: initial py2 to 3 work
1 parent 2d349c0 commit 9979bc6

12 files changed

Lines changed: 300 additions & 290 deletions

File tree

code/planet-cache.py

Lines changed: 45 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
#!/usr/bin/env python
2-
# -*- coding: UTF-8 -*-
1+
#!/usr/bin/env python3
32
"""Planet cache tool.
43
54
"""
@@ -12,48 +11,48 @@
1211
import os
1312
import sys
1413
import time
15-
import dbhash
16-
import ConfigParser
14+
import dbm
15+
import configparser
1716

1817
import planet
1918

2019

2120
def usage():
22-
print "Usage: planet-cache [options] CACHEFILE [ITEMID]..."
23-
print
24-
print "Examine and modify information in the Planet cache."
25-
print
26-
print "Channel Commands:"
27-
print " -C, --channel Display known information on the channel"
28-
print " -L, --list List items in the channel"
29-
print " -K, --keys List all keys found in channel items"
30-
print
31-
print "Item Commands (need ITEMID):"
32-
print " -I, --item Display known information about the item(s)"
33-
print " -H, --hide Mark the item(s) as hidden"
34-
print " -U, --unhide Mark the item(s) as not hidden"
35-
print
36-
print "Other Options:"
37-
print " -h, --help Display this help message and exit"
21+
print("Usage: planet-cache [options] CACHEFILE [ITEMID]...")
22+
print()
23+
print("Examine and modify information in the Planet cache.")
24+
print()
25+
print("Channel Commands:")
26+
print(" -C, --channel Display known information on the channel")
27+
print(" -L, --list List items in the channel")
28+
print(" -K, --keys List all keys found in channel items")
29+
print()
30+
print("Item Commands (need ITEMID):")
31+
print(" -I, --item Display known information about the item(s)")
32+
print(" -H, --hide Mark the item(s) as hidden")
33+
print(" -U, --unhide Mark the item(s) as not hidden")
34+
print()
35+
print("Other Options:")
36+
print(" -h, --help Display this help message and exit")
3837
sys.exit(0)
3938

4039
def usage_error(msg, *args):
41-
print >>sys.stderr, msg, " ".join(args)
42-
print >>sys.stderr, "Perhaps you need --help ?"
40+
print(msg, " ".join(args), file=sys.stderr)
41+
print("Perhaps you need --help ?", file=sys.stderr)
4342
sys.exit(1)
4443

4544
def print_keys(item, title):
4645
keys = item.keys()
4746
keys.sort()
4847
key_len = max([ len(k) for k in keys ])
4948

50-
print title + ":"
49+
print(title + ":")
5150
for key in keys:
5251
if item.key_type(key) == item.DATE:
5352
value = time.strftime(planet.TIMEFMT_ISO, item[key])
5453
else:
5554
value = str(item[key])
56-
print " %-*s %s" % (key_len, key, fit_str(value, 74 - key_len))
55+
print(" %-*s %s" % (key_len, key, fit_str(value, 74 - key_len)))
5756

5857
def fit_str(string, length):
5958
if len(string) <= length:
@@ -116,24 +115,23 @@ def fit_str(string, length):
116115

117116
# Open the cache file directly to get the URL it represents
118117
try:
119-
db = dbhash.open(cache_file)
120-
url = db["url"]
121-
db.close()
122-
except dbhash.bsddb._db.DBError, e:
123-
print >>sys.stderr, cache_file + ":", e.args[1]
118+
with dbm.open(cache_file, 'r') as db:
119+
url = db[b"url"].decode('utf-8')
120+
except dbm.error as e:
121+
print(f"{cache_file}: {str(e)}", file=sys.stderr)
124122
sys.exit(1)
125123
except KeyError:
126-
print >>sys.stderr, cache_file + ": Probably not a cache file"
124+
print(f"{cache_file}: Probably not a cache file", file=sys.stderr)
127125
sys.exit(1)
128126

129127
# Now do it the right way :-)
130-
my_planet = planet.Planet(ConfigParser.ConfigParser())
128+
my_planet = planet.Planet(configparser.ConfigParser())
131129
my_planet.cache_directory = os.path.dirname(cache_file)
132130
channel = planet.Channel(my_planet, url)
133131

134132
for item_id in ids:
135133
if not channel.has_item(item_id):
136-
print >>sys.stderr, item_id + ": Not in channel"
134+
print(item_id + ": Not in channel", file=sys.stderr)
137135
sys.exit(1)
138136

139137
# Do the user's bidding
@@ -146,49 +144,48 @@ def fit_str(string, length):
146144
print_keys(item, "Item Keys for %s" % item_id)
147145

148146
elif command == "list":
149-
print "Items in Channel:"
147+
print("Items in Channel:")
150148
for item in channel.items(hidden=1, sorted=1):
151-
print " " + item.id
152-
print " " + time.strftime(planet.TIMEFMT_ISO, item.date)
149+
print(" " + item.id)
150+
print(" " + time.strftime(planet.TIMEFMT_ISO, item.date))
153151
if hasattr(item, "title"):
154-
print " " + fit_str(item.title, 70)
152+
print(" " + fit_str(item.title, 70))
155153
if hasattr(item, "hidden"):
156-
print " (hidden)"
154+
print(" (hidden)")
157155

158156
elif command == "keys":
159157
keys = {}
160158
for item in channel.items():
161159
for key in item.keys():
162160
keys[key] = 1
163161

164-
keys = keys.keys()
165-
keys.sort()
162+
keys = sorted(keys.keys())
166163

167-
print "Keys used in Channel:"
164+
print("Keys used in Channel:")
168165
for key in keys:
169-
print " " + key
170-
print
166+
print(" " + key)
167+
print()
171168

172-
print "Use --item to output values of particular items."
169+
print("Use --item to output values of particular items.")
173170

174171
elif command == "hide":
175172
for item_id in ids:
176173
item = channel.get_item(item_id)
177174
if hasattr(item, "hidden"):
178-
print item_id + ": Already hidden."
175+
print(item_id + ": Already hidden.")
179176
else:
180177
item.hidden = "yes"
181178

182179
channel.cache_write()
183-
print "Done."
180+
print("Done.")
184181

185182
elif command == "unhide":
186183
for item_id in ids:
187184
item = channel.get_item(item_id)
188185
if hasattr(item, "hidden"):
189-
del(item.hidden)
186+
del item.hidden
190187
else:
191-
print item_id + ": Not hidden."
188+
print(item_id + ": Not hidden.")
192189

193190
channel.cache_write()
194-
print "Done."
191+
print("Done.")

code/planet.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
"""The Planet aggregator.
33
44
A flexible and easy-to-use aggregator for generating websites.
@@ -16,14 +16,13 @@
1616

1717
import os
1818
import sys
19-
import time
2019
import locale
2120
import socket
22-
import urlparse
21+
import configparser
22+
from urllib.parse import urljoin
2323

2424
import planet
2525

26-
from ConfigParser import ConfigParser
2726

2827
# Default configuration file path
2928
CONFIG_FILE = "config.ini"
@@ -56,29 +55,29 @@ def main():
5655

5756
for arg in sys.argv[1:]:
5857
if arg == "-h" or arg == "--help":
59-
print "Usage: planet [options] [CONFIGFILE]"
60-
print
61-
print "Options:"
62-
print " -v, --verbose DEBUG level logging during update"
63-
print " -o, --offline Update the Planet from the cache only"
64-
print " -h, --help Display this help message and exit"
65-
print
58+
print("Usage: planet [options] [CONFIGFILE]")
59+
print()
60+
print("Options:")
61+
print(" -v, --verbose DEBUG level logging during update")
62+
print(" -o, --offline Update the Planet from the cache only")
63+
print(" -h, --help Display this help message and exit")
64+
print()
6665
sys.exit(0)
6766
elif arg == "-v" or arg == "--verbose":
6867
verbose = 1
6968
elif arg == "-o" or arg == "--offline":
7069
offline = 1
7170
elif arg.startswith("-"):
72-
print >>sys.stderr, "Unknown option:", arg
71+
print("Unknown option:", arg, file=sys.stderr)
7372
sys.exit(1)
7473
else:
7574
config_file = arg
7675

7776
# Read the configuration file
78-
config = ConfigParser()
77+
config = configparser()
7978
config.read(config_file)
8079
if not config.has_section("Planet"):
81-
print >>sys.stderr, "Configuration missing [Planet] section."
80+
print("Configuration missing [Planet] section.", file=sys.stderr)
8281
sys.exit(1)
8382

8483
# Read the [Planet] config section
@@ -100,7 +99,7 @@ def main():
10099
for template_file in template_files:
101100
name = os.path.splitext(os.path.basename(template_file))[0]
102101
if name.find('atom')>=0 or name.find('rss')>=0:
103-
planet_feed = urlparse.urljoin(planet_link, name)
102+
planet_feed = urljoin(planet_link, name)
104103
break
105104

106105
# Define locale
@@ -118,7 +117,7 @@ def main():
118117
locale_ok = True
119118
break
120119
if not locale_ok:
121-
print >>sys.stderr, "Unsupported locale setting."
120+
print("Unsupported locale setting.", file=sys.stderr)
122121
sys.exit(1)
123122

124123
# Activate logging

code/planet/__init__.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
#!/usr/bin/env python
2-
# -*- coding: UTF-8 -*-
1+
#!/usr/bin/env python3
32
"""Planet aggregator library.
43
54
This package is a library for developing web sites or software that
@@ -18,7 +17,6 @@
1817
import feedparser
1918
import sanitize
2019
import htmltmpl
21-
import sgmllib
2220
try:
2321
import logging
2422
except:
@@ -29,10 +27,11 @@
2927
"Planet", "Channel", "NewsItem")
3028

3129

30+
from html.parser import HTMLParser
3231
import os
33-
import md5
32+
from hashlib import md5
3433
import time
35-
import dbhash
34+
import dbm
3635
import re
3736

3837
try:
@@ -74,15 +73,18 @@ def escape(data):
7473
NEW_DATE_FORMAT = "%B %d, %Y"
7574
ACTIVITY_THRESHOLD = 0
7675

77-
class stripHtml(sgmllib.SGMLParser):
76+
77+
class stripHtml(HTMLParser):
7878
"remove all tags from the data"
79-
def __init__(self, data):
80-
sgmllib.SGMLParser.__init__(self)
81-
self.result=''
82-
self.feed(data)
83-
self.close()
79+
def __init__(self):
80+
super().__init__()
81+
self.result = []
82+
8483
def handle_data(self, data):
85-
if data: self.result+=data
84+
self.result.append(data)
85+
86+
def get_data(self):
87+
return "".join(self.result)
8688

8789
def template_info(item, date_format):
8890
"""Produce a dictionary of template information."""
@@ -504,7 +506,7 @@ def __init__(self, planet, url):
504506
if not os.path.isdir(planet.cache_directory):
505507
os.makedirs(planet.cache_directory)
506508
cache_filename = cache.filename(planet.cache_directory, url)
507-
cache_file = dbhash.open(cache_filename, "c", 0666)
509+
cache_file = dbm.open(cache_filename, "c", 0o666)
508510

509511
cache.CachedInfo.__init__(self, cache_file, url, root=1)
510512

@@ -695,7 +697,7 @@ def update_info(self, feed):
695697
self.set_as_string(key + "_width", str(feed[key].width))
696698
if feed[key].has_key("height"):
697699
self.set_as_string(key + "_height", str(feed[key].height))
698-
elif isinstance(feed[key], (str, unicode)):
700+
elif isinstance(feed[key], str):
699701
# String fields
700702
try:
701703
detail = key + '_detail'
@@ -890,7 +892,7 @@ def update(self, entry):
890892
self.set_as_string(key + "_language", item.language)
891893
value += cache.utf8(item.value)
892894
self.set_as_string(key, value)
893-
elif isinstance(entry[key], (str, unicode)):
895+
elif isinstance(entry[key], str):
894896
# String fields
895897
try:
896898
detail = key + '_detail'

code/planet/atomstyler.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from xml.dom import minidom, Node
2-
from urlparse import urlparse, urlunparse
2+
from urllib.parse import urlparse, urlunparse
33
from xml.parsers.expat import ExpatError
4-
from htmlentitydefs import name2codepoint
4+
from html.entities import name2codepoint
55
import re
66

77
# select and apply an xml:base for this entry
@@ -75,20 +75,20 @@ def retype(parent):
7575
elif len(node.childNodes)==1:
7676

7777
# replace html entity defs with utf-8
78-
chunks=re.split('&(\w+);', node.childNodes[0].nodeValue)
78+
chunks=re.split(r'&(\w+);', node.childNodes[0].nodeValue)
7979
for i in range(1,len(chunks),2):
8080
if chunks[i] in ['amp', 'lt', 'gt', 'apos', 'quot']:
8181
chunks[i] ='&' + chunks[i] +';'
8282
elif chunks[i] in name2codepoint:
83-
chunks[i]=unichr(name2codepoint[chunks[i]])
83+
chunks[i] = chr(name2codepoint[chunks[i]])
8484
else:
8585
chunks[i]='&' + chunks[i] + ';'
86-
text = u"".join(chunks)
86+
text = "".join(chunks)
8787

8888
try:
8989
# see if the resulting text is a well-formed XML fragment
9090
div = '<div xmlns="http://www.w3.org/1999/xhtml">%s</div>'
91-
data = minidom.parseString((div % text.encode('utf-8')))
91+
data = minidom.parseString(div % text.encode('utf-8'))
9292

9393
if text.find('<') < 0:
9494
# plain text

0 commit comments

Comments
 (0)