Skip to content

Commit 4b7db9b

Browse files
committed
Fix #23; get parse.py at least mostly working under Python 3.
This could badly do with refactoring; it's likely with some set of options this will still not work.
1 parent 172380c commit 4b7db9b

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

parse.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,15 @@ def parse():
3434
pass
3535
elif f == '-':
3636
f = sys.stdin
37+
if sys.version_info[0] >= 3:
38+
encoding = None
3739
else:
3840
try:
3941
# Try opening from file system
40-
f = open(f)
41-
except IOError: pass
42+
f = open(f, "rb")
43+
except IOError as e:
44+
sys.stderr.write("Unable to open file: %s\n" % e)
45+
sys.exit(1)
4246
except IndexError:
4347
sys.stderr.write("No filename provided. Use -h for help\n")
4448
sys.exit(1)
@@ -76,12 +80,16 @@ def parse():
7680
t0 = time.time()
7781
document = run(parseMethod, f, encoding)
7882
t1 = time.time()
79-
printOutput(p, document, opts)
80-
t2 = time.time()
81-
sys.stderr.write("\n\nRun took: %fs (plus %fs to print the output)"%(t1-t0, t2-t1))
83+
if document:
84+
printOutput(p, document, opts)
85+
t2 = time.time()
86+
sys.stderr.write("\n\nRun took: %fs (plus %fs to print the output)"%(t1-t0, t2-t1))
87+
else:
88+
sys.stderr.write("\n\nRun took: %fs"%(t1-t0))
8289
else:
8390
document = run(parseMethod, f, encoding)
84-
printOutput(p, document, opts)
91+
if document:
92+
printOutput(p, document, opts)
8593

8694
def run(parseMethod, f, encoding):
8795
try:
@@ -119,7 +127,11 @@ def printOutput(parser, document, opts):
119127
del kwargs['quote_char']
120128

121129
tokens = treewalkers.getTreeWalker(opts.treebuilder)(document)
122-
for text in serializer.HTMLSerializer(**kwargs).serialize(tokens, encoding='utf-8'):
130+
if sys.version_info[0] >= 3:
131+
encoding = None
132+
else:
133+
encoding = "utf-8"
134+
for text in serializer.HTMLSerializer(**kwargs).serialize(tokens, encoding=encoding):
123135
sys.stdout.write(text)
124136
if not text.endswith('\n'): sys.stdout.write('\n')
125137
if opts.error:

0 commit comments

Comments
 (0)