Skip to content

Commit abbc4d9

Browse files
victor-ruronreiter
authored andcommitted
added python 3 compatibility
1 parent 87d064d commit abbc4d9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+268
-280
lines changed

cert.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from reportlab.pdfbase import pdfmetrics
44
from reportlab.pdfbase.ttfonts import TTFont
55
from reportlab.lib.units import inch
6-
import StringIO
6+
import io
77

88

99
def create_cert(filename, name, course_name, date, logo_loc):

constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ def main(args: Array[String]) {
441441
}
442442

443443
# this will run once
444-
for domain, v in DOMAIN_DATA.iteritems():
444+
for domain, v in list(DOMAIN_DATA.items()):
445445
v["namespace"] = domain
446446
v["full_url"] = "https://www." + v["namespace"]
447447
v["contact_email"] = "admin@" + v["namespace"]

courses/process.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
for l in d:
1212
t = f[:-4]
13-
l = {x[0].lower().replace(" ", "_"): x[1] for x in l.items()}
13+
l = {x[0].lower().replace(" ", "_"): x[1] for x in list(l.items())}
1414
l["retail_price"] = float(l["retail_price"])
1515

1616
link = re.findall(r'<a href=\"(.*?)\">', l["link_code"])[0]
@@ -26,7 +26,7 @@
2626
data[t].append(l)
2727

2828
encoded = json.dumps(data, sort_keys=True, indent=4)
29-
print encoded
29+
print(encoded)
3030
with open("../courses.json", "w") as e:
3131
e.write(encoded)
3232

ideone/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,21 +108,21 @@ def _translate_language_name(self, language_name):
108108

109109
# Check for exact match first including the whole version
110110
# string
111-
for ideone_index, ideone_language in languages.items():
111+
for ideone_index, ideone_language in list(languages.items()):
112112
if ideone_language.lower() == language_name.lower():
113113
return ideone_index
114114

115115
# Check for a match of just the language name without any
116116
# version information
117117
simple_languages = dict((k,v.split('(')[0].strip())
118-
for (k,v) in languages.items())
119-
for ideone_index, simple_name in simple_languages.items():
118+
for (k,v) in list(languages.items()))
119+
for ideone_index, simple_name in list(simple_languages.items()):
120120
if simple_name.lower() == language_name.lower():
121121
return ideone_index
122122

123123
# Give up, but first find a similar name, suggest it and error
124124
# out
125-
language_choices = languages.values() + simple_languages.values()
125+
language_choices = list(languages.values()) + list(simple_languages.values())
126126
similar_choices = difflib.get_close_matches(language_name,
127127
language_choices,
128128
n=3,

main.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,14 @@
44
import markdown
55
import os
66
import cgi
7-
import urllib
7+
import urllib.request, urllib.parse, urllib.error
88
import time
99
import functools
1010
import logging
11+
import binascii
1112

1213
from flask import Flask, render_template, request, make_response, session, Response
13-
import sys
14-
if sys.version_info.major < 3:
15-
reload(sys)
16-
sys.setdefaultencoding('utf8')
14+
1715

1816
from ideone import Ideone
1917

@@ -40,7 +38,7 @@
4038
help="Default domain when running in development mode",
4139
default=current_domain,
4240
required=True,
43-
choices=constants.DOMAIN_DATA.keys()
41+
choices=list(constants.DOMAIN_DATA.keys())
4442
)
4543

4644
parser.add_argument("-p", "--port", help="port to listen to", default=5000, type=int)
@@ -100,7 +98,7 @@ def pageurl(value, language):
10098
if value.startswith("http"):
10199
return value
102100
else:
103-
return urllib.quote("/%s/%s" % (language, value.replace(' ', '_')))
101+
return urllib.parse.quote("/%s/%s" % (language, value.replace(' ', '_')))
104102

105103

106104
def _wikify_one(language, pat):
@@ -125,7 +123,7 @@ def _wikify_one(language, pat):
125123

126124
def wikify(text, language):
127125
text, count = WIKI_WORD_PATTERN.subn(functools.partial(_wikify_one, language), text)
128-
return markdown.markdown(text.decode("utf-8")).strip()
126+
return markdown.markdown(text).strip()
129127

130128

131129
def untab(text):
@@ -149,7 +147,7 @@ def init_tutorials():
149147
continue
150148

151149
if domain not in constants.DOMAIN_DATA:
152-
logging.warn("skipping domain %s beacause no domain data exists" % domain)
150+
logging.warning("skipping domain %s beacause no domain data exists" % domain)
153151
continue
154152

155153
for language in os.listdir(os.path.join(os.path.dirname(__file__), "tutorials", domain)):
@@ -188,15 +186,15 @@ def init_tutorials():
188186
tutorial_sections = sections.findall(tutorial_dict["text"])
189187
if tutorial_sections:
190188
text, code, output, solution = tutorial_sections[0]
191-
tutorial_dict["page_title"] = tutorial.decode("utf8")
189+
tutorial_dict["page_title"] = tutorial
192190
tutorial_dict["text"] = wikify(text, language)
193191
tutorial_dict["code"] = untab(code)
194192
tutorial_dict["output"] = untab(output)
195193
tutorial_dict["solution"] = untab(solution)
196194
tutorial_dict["is_tutorial"] = True
197195
else:
198196
if tutorial_file != "Welcome.md":
199-
logging.warn("File %s/%s/%s is not a tutorial", domain, language, tutorial_file)
197+
logging.warning("File %s/%s/%s is not a tutorial", domain, language, tutorial_file)
200198
tutorial_dict["page_title"] = ""
201199
tutorial_dict["text"] = wikify(tutorial_dict["text"], language)
202200
tutorial_dict["code"] = constants.DOMAIN_DATA[domain]["default_code"]
@@ -205,24 +203,24 @@ def init_tutorials():
205203
for link in links:
206204
if not link in tutorial_data[domain][language]:
207205
tutorial_data[domain][language][link] = {
208-
"page_title" : link.decode("utf8"),
206+
"page_title" : link,
209207
"text": contributing_tutorials,
210208
"code": ""
211209
}
212210

213211
if not "back_chapter" in tutorial_data[domain][language][link]:
214-
tutorial_data[domain][language][link]["back_chapter"] = tutorial.decode("utf-8").replace(" ", "_")
212+
tutorial_data[domain][language][link]["back_chapter"] = tutorial.replace(" ", "_")
215213
elif not link.startswith("http"):
216214
logging.info("Warning! duplicate links to tutorial %s from tutorial %s/%s", link, language, tutorial)
217215

218216
num_links = len(links)
219217
page_index = links.index(link)
220218
if page_index > 0:
221219
if not "previous_chapter" in tutorial_data[domain][language][link]:
222-
tutorial_data[domain][language][link]["previous_chapter"] = links[page_index - 1].decode("utf-8").replace(" ", "_")
220+
tutorial_data[domain][language][link]["previous_chapter"] = links[page_index - 1].replace(" ", "_")
223221
if page_index < (num_links - 1):
224222
if not "next_chapter" in tutorial_data[domain][language][link]:
225-
tutorial_data[domain][language][link]["next_chapter"] = links[page_index + 1].decode("utf-8").replace(" ", "_")
223+
tutorial_data[domain][language][link]["next_chapter"] = links[page_index + 1].replace(" ", "_")
226224

227225

228226
init_tutorials()
@@ -352,7 +350,7 @@ def progress(language):
352350
@app.route("/<title>", methods=["GET", "POST"])
353351
@app.route("/<language>/<title>", methods=["GET", "POST"])
354352
def index(title, language="en"):
355-
tutorial = title.replace("_", " ").encode("utf-8")
353+
tutorial = title.replace("_", " ")
356354
try:
357355
current_tutorial_data = get_tutorial(tutorial, language)
358356
except KeyError:
@@ -365,13 +363,13 @@ def index(title, language="en"):
365363
html_title = "%s - %s" % (title.replace("_", " "), title_suffix) if title != "Welcome" else title_suffix
366364

367365
if not "uid" in session:
368-
session["uid"] = os.urandom(16).encode("hex")
366+
session["uid"] = binascii.b2a_hex(os.urandom(16))
369367

370368
uid = session["uid"]
371369

372370
try:
373371
site_links = tutorial_data[get_host()][language]["Welcome"]["links"]
374-
except Exception, e:
372+
except Exception as e:
375373
site_links = []
376374
logging.error("cant get site links for %s %s" % (get_host(), language))
377375

markdown/__init__.py

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@
7474
DOC_TAG = "div" # Element used to wrap document - later removed
7575

7676
# Placeholders
77-
STX = u'\u0002' # Use STX ("Start of text") for start-of-placeholder
78-
ETX = u'\u0003' # Use ETX ("End of text") for end-of-placeholder
77+
STX = '\u0002' # Use STX ("Start of text") for start-of-placeholder
78+
ETX = '\u0003' # Use ETX ("End of text") for end-of-placeholder
7979
INLINE_PLACEHOLDER_PREFIX = STX+"klzzwxh:"
8080
INLINE_PLACEHOLDER = INLINE_PLACEHOLDER_PREFIX + "%s" + ETX
8181
AMP_SUBSTITUTE = STX+"amp"+ETX
@@ -86,11 +86,11 @@
8686
-----------------------------------------------------------------------------
8787
"""
8888

89-
RTL_BIDI_RANGES = ( (u'\u0590', u'\u07FF'),
89+
RTL_BIDI_RANGES = ( ('\u0590', '\u07FF'),
9090
# Hebrew (0590-05FF), Arabic (0600-06FF),
9191
# Syriac (0700-074F), Arabic supplement (0750-077F),
9292
# Thaana (0780-07BF), Nko (07C0-07FF).
93-
(u'\u2D30', u'\u2D7F'), # Tifinagh
93+
('\u2D30', '\u2D7F'), # Tifinagh
9494
)
9595

9696

@@ -109,7 +109,7 @@ def message(level, text):
109109
if level > WARN:
110110
sys.exit(0)
111111
elif level > WARN:
112-
raise MarkdownException, text
112+
raise MarkdownException(text)
113113
else:
114114
warnings.warn(text, MarkdownWarning)
115115

@@ -123,7 +123,7 @@ def isBlockLevel(tag):
123123
=============================================================================
124124
"""
125125

126-
class AtomicString(unicode):
126+
class AtomicString(str):
127127
"""A string which should not be further processed."""
128128
pass
129129

@@ -158,22 +158,22 @@ class MarkdownWarning(Warning):
158158
159159
"""
160160

161-
import preprocessors
162-
import blockprocessors
163-
import treeprocessors
164-
import inlinepatterns
165-
import postprocessors
166-
import blockparser
167-
import etree_loader
168-
import odict
161+
from . import preprocessors
162+
from . import blockprocessors
163+
from . import treeprocessors
164+
from . import inlinepatterns
165+
from . import postprocessors
166+
from . import blockparser
167+
from . import etree_loader
168+
from . import odict
169169

170170
# Extensions should use "markdown.etree" instead of "etree" (or do `from
171171
# markdown import etree`). Do not import it by yourself.
172172

173173
etree = etree_loader.importETree()
174174

175175
# Adds the ability to output html4
176-
import html4
176+
from . import html4
177177

178178

179179
class Markdown:
@@ -325,12 +325,12 @@ def registerExtensions(self, extensions, configs):
325325
326326
"""
327327
for ext in extensions:
328-
if isinstance(ext, basestring):
328+
if isinstance(ext, str):
329329
ext = load_extension(ext, configs.get(ext, []))
330330
if isinstance(ext, Extension):
331331
try:
332332
ext.extendMarkdown(self, globals())
333-
except NotImplementedError, e:
333+
except NotImplementedError as e:
334334
message(ERROR, e)
335335
else:
336336
message(ERROR, 'Extension "%s.%s" must be of type: "markdown.Extension".' \
@@ -356,7 +356,7 @@ def set_output_format(self, format):
356356
self.serializer = self.output_formats[format.lower()]
357357
except KeyError:
358358
message(CRITICAL, 'Invalid Output Format: "%s". Use one of %s.' \
359-
% (format, self.output_formats.keys()))
359+
% (format, list(self.output_formats.keys())))
360360

361361
def convert(self, source):
362362
"""
@@ -370,12 +370,12 @@ def convert(self, source):
370370

371371
# Fixup the source text
372372
if not source.strip():
373-
return u"" # a blank unicode string
373+
return "" # a blank unicode string
374374
try:
375-
source = unicode(source)
375+
source = str(source)
376376
except UnicodeDecodeError:
377377
message(CRITICAL, 'UnicodeDecodeError: Markdown only accepts unicode or ascii input.')
378-
return u""
378+
return ""
379379

380380
source = source.replace(STX, "").replace(ETX, "")
381381
source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n"
@@ -384,14 +384,14 @@ def convert(self, source):
384384

385385
# Split into lines and run the line preprocessors.
386386
self.lines = source.split("\n")
387-
for prep in self.preprocessors.values():
387+
for prep in list(self.preprocessors.values()):
388388
self.lines = prep.run(self.lines)
389389

390390
# Parse the high-level elements.
391391
root = self.parser.parseDocument(self.lines).getroot()
392392

393393
# Run the tree-processors
394-
for treeprocessor in self.treeprocessors.values():
394+
for treeprocessor in list(self.treeprocessors.values()):
395395
newRoot = treeprocessor.run(root)
396396
if newRoot:
397397
root = newRoot
@@ -412,7 +412,7 @@ def convert(self, source):
412412
message(CRITICAL, 'Failed to strip top level tags.')
413413

414414
# Run the text post-processors
415-
for pp in self.postprocessors.values():
415+
for pp in list(self.postprocessors.values()):
416416
output = pp.run(output)
417417

418418
return output.strip()
@@ -443,13 +443,13 @@ def convertFile(self, input=None, output=None, encoding=None):
443443
input_file = codecs.open(input, mode="r", encoding=encoding)
444444
text = input_file.read()
445445
input_file.close()
446-
text = text.lstrip(u'\ufeff') # remove the byte-order mark
446+
text = text.lstrip('\ufeff') # remove the byte-order mark
447447

448448
# Convert
449449
html = self.convert(text)
450450

451451
# Write to file or stdout
452-
if isinstance(output, (str, unicode)):
452+
if isinstance(output, str):
453453
output_file = codecs.open(output, "w", encoding=encoding)
454454
output_file.write(html)
455455
output_file.close()
@@ -482,7 +482,7 @@ def getConfig(self, key):
482482

483483
def getConfigInfo(self):
484484
""" Return all config settings as a list of tuples. """
485-
return [(key, self.config[key][1]) for key in self.config.keys()]
485+
return [(key, self.config[key][1]) for key in list(self.config.keys())]
486486

487487
def setConfig(self, key, value):
488488
""" Set a config setting for `key` with the given `value`. """
@@ -501,8 +501,8 @@ def extendMarkdown(self, md, md_globals):
501501
* md_globals: Global variables in the markdown module namespace.
502502
503503
"""
504-
raise NotImplementedError, 'Extension "%s.%s" must define an "extendMarkdown"' \
505-
'method.' % (self.__class__.__module__, self.__class__.__name__)
504+
raise NotImplementedError('Extension "%s.%s" must define an "extendMarkdown"' \
505+
'method.' % (self.__class__.__module__, self.__class__.__name__))
506506

507507

508508
def load_extension(ext_name, configs = []):
@@ -542,7 +542,7 @@ def load_extension(ext_name, configs = []):
542542
# If the module is loaded successfully, we expect it to define a
543543
# function called makeExtension()
544544
try:
545-
return module.makeExtension(configs.items())
545+
return module.makeExtension(list(configs.items()))
546546
except AttributeError:
547547
message(CRITICAL, "Failed to initiate extension '%s'" % ext_name)
548548

markdown/blockparser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def parseBlocks(self, parent, blocks):
8787
8888
"""
8989
while blocks:
90-
for processor in self.blockprocessors.values():
90+
for processor in list(self.blockprocessors.values()):
9191
if processor.test(parent, blocks[0]):
9292
processor.run(parent, blocks)
9393
break

markdown/commandline.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def parse_options():
3939
'extensions': [],
4040
'encoding': None }, CRITICAL
4141
else:
42-
print OPTPARSE_WARNING
42+
print(OPTPARSE_WARNING)
4343
return None, None
4444

4545
parser = optparse.OptionParser(usage="%prog INPUTFILE [options]")

0 commit comments

Comments
 (0)