소스 검색

port to python3 but keep py2 compatibility

Thomas B 2 달 전
부모
커밋
6bb17c26c8
4개의 변경된 파일128개의 추가작업 그리고 87개의 파일을 삭제
  1. 1
    1
      input/index.md
  2. 54
    38
      macros.py
  3. 30
    29
      page.html
  4. 43
    19
      poole.py

+ 1
- 1
input/index.md 파일 보기

@@ -28,7 +28,7 @@ start_date = datetime(1994,1,22,0,0)
28 28
 end_date = datetime.now()
29 29
 difference_in_years = date_as_float(end_date) - date_as_float(start_date)
30 30
 
31
-print int(difference_in_years)
31
+print(int(difference_in_years))
32 32
 
33 33
 %--> year old software developer from Germany.
34 34
 All of my projects are released as free or open-source software on [my Gitea Server](https://git.xythobuz.de/thomas), [my GitHub profile](https://github.com/xythobuz) and here on my website. Have fun!

+ 54
- 38
macros.py 파일 보기

@@ -1,5 +1,6 @@
1 1
 # -*- coding: utf-8 -*-
2 2
 
3
+import sys
3 4
 import re
4 5
 import itertools
5 6
 import email.utils
@@ -7,11 +8,26 @@ import os.path
7 8
 import time
8 9
 import codecs
9 10
 from datetime import datetime
10
-import urlparse
11 11
 
12 12
 DEFAULT_LANG = "en"
13 13
 BASE_URL = "https://www.xythobuz.de"
14 14
 
15
+# =============================================================================
16
+# Python 2/3 hacks
17
+# =============================================================================
18
+
19
+PY3 = sys.version_info[0] == 3
20
+
21
+if PY3:
22
+    import urllib
23
+    import urllib.request
24
+    def urlparse_foo(link):
25
+        return urllib.parse.parse_qs(urllib.parse.urlparse(link).query)['v'][0]
26
+else:
27
+    import urlparse
28
+    def urlparse_foo(link):
29
+        return urlparse.parse_qs(urlparse.urlparse(link).query)['v'][0]
30
+
15 31
 # -----------------------------------------------------------------------------
16 32
 # sub page helper macro
17 33
 # -----------------------------------------------------------------------------
@@ -30,24 +46,24 @@ def backToParent():
30 46
     # print if any parent link found
31 47
     if len(posts) > 0:
32 48
         p = posts[0]
33
-        print '<span class="listdesc">[...back to ' + p.title + ' overview](' + p.url + ')</span>'
49
+        print('<span class="listdesc">[...back to ' + p.title + ' overview](' + p.url + ')</span>')
34 50
 
35 51
 # -----------------------------------------------------------------------------
36 52
 # table helper macro
37 53
 # -----------------------------------------------------------------------------
38 54
 
39 55
 def tableHelper(style, header, content):
40
-    print "<table>"
56
+    print("<table>")
41 57
     if (header != None) and (len(header) == len(style)):
42
-        print "<tr>"
58
+        print("<tr>")
43 59
         for h in header:
44
-            print "<th>" + h + "</th>"
45
-        print "</tr>"
60
+            print("<th>" + h + "</th>")
61
+        print("</tr>")
46 62
     for ci in range(0, len(content)):
47 63
         if len(content[ci]) != len(style):
48 64
             # invalid call of table helper!
49 65
             continue
50
-        print "<tr>"
66
+        print("<tr>")
51 67
         for i in range(0, len(style)):
52 68
             s = style[i]
53 69
             td_style = ""
@@ -70,17 +86,17 @@ def tableHelper(style, header, content):
70 86
             if td_style != "":
71 87
                 td_args = " style=\"" + td_style + "\""
72 88
 
73
-            print "<td" + td_args + ">"
89
+            print("<td" + td_args + ">")
74 90
 
75 91
             if isinstance(content[ci][i], tuple):
76 92
                 text, link = content[ci][i]
77
-                print "<a href=\"" + link + "\">" + text + "</a>"
93
+                print("<a href=\"" + link + "\">" + text + "</a>")
78 94
             else:
79 95
                 text = content[ci][i]
80
-                print text
81
-            print "</td>"
82
-        print "</tr>"
83
-    print "</table>"
96
+                print(text)
97
+            print("</td>")
98
+        print("</tr>")
99
+    print("</table>")
84 100
 
85 101
 # -----------------------------------------------------------------------------
86 102
 # menu helper macro
@@ -112,7 +128,7 @@ def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStart
112 128
     if year != lastyear:
113 129
         lastyear = year
114 130
         if yearsAsHeading:
115
-            print "\n\n#### %s\n" % (year)
131
+            print("\n\n#### %s\n" % (year))
116 132
 
117 133
     dateto = ""
118 134
     if p.get("date", "" != ""):
@@ -127,19 +143,19 @@ def printMenuItem(p, yearsAsHeading = False, showDateSpan = False, showOnlyStart
127 143
         if nicelyFormatFullDate:
128 144
             dateto = " - " + datetime.strptime(p.get("update", p.date), "%Y-%m-%d").strftime("%B %d, %Y")
129 145
 
130
-    print "  * **[%s](%s)**%s" % (title, p.url, dateto)
146
+    print("  * **[%s](%s)**%s" % (title, p.url, dateto))
131 147
 
132 148
     if p.get("description", "") != "":
133 149
         description = p.get("description", "")
134 150
         if lang != "":
135 151
             if p.get("description_" + lang, "") != "":
136 152
                 description = p.get("description_" + lang, "")
137
-        print "<br><span class=\"listdesc\">" + description + "</span>"
153
+        print("<br><span class=\"listdesc\">" + description + "</span>")
138 154
 
139 155
     if showLastCommit:
140 156
         link = githubCommitBadge(p)
141 157
         if len(link) > 0:
142
-            print "<br>" + link
158
+            print("<br>" + link)
143 159
 
144 160
     return lastyear
145 161
 
@@ -318,14 +334,14 @@ def lightgallery(links):
318 334
     for v in videos:
319 335
         link, mime, thumb, poster, alt = v
320 336
         v_i += 1
321
-        print '<div style="display:none;" id="video' + str(v_i) + '_' + str(v_ii) + '">'
322
-        print '<video class="lg-video-object lg-html5" controls preload="none">'
323
-        print '<source src="' + link + '" type="' + mime + '">'
324
-        print '<a href="' + link + '">' + alt + '</a>'
325
-        print '</video>'
326
-        print '</div>'
337
+        print('<div style="display:none;" id="video' + str(v_i) + '_' + str(v_ii) + '">')
338
+        print('<video class="lg-video-object lg-html5" controls preload="none">')
339
+        print('<source src="' + link + '" type="' + mime + '">')
340
+        print('<a href="' + link + '">' + alt + '</a>')
341
+        print('</video>')
342
+        print('</div>')
327 343
         
328
-    print '<div class="lightgallery">'
344
+    print('<div class="lightgallery">')
329 345
     v_i = -1
330 346
     for l in links:
331 347
         if (len(l) == 3) or (len(l) == 2):
@@ -337,7 +353,7 @@ def lightgallery(links):
337 353
                 link, alt = l
338 354
                 if "youtube.com" in link:
339 355
                     img = "https://img.youtube.com/vi/"
340
-                    img += urlparse.parse_qs(urlparse.urlparse(link).query)['v'][0]
356
+                    img += urlparse_foo(link)
341 357
                     img += "/0.jpg" # full size preview
342 358
                     #img += "/default.jpg" # default thumbnail
343 359
                     style = ' style="width:300px;"'
@@ -346,7 +362,7 @@ def lightgallery(links):
346 362
                     x = link.rfind('.')
347 363
                     img = link[:x] + '_small' + link[x:]
348 364
             lightgallery_check_thumbnail(link, img)
349
-            print '<div class="border" style="position:relative;" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"' + style + '>' + img2 + '</a></div>'
365
+            print('<div class="border" style="position:relative;" data-src="' + link + '"><a href="' + link + '"><img class="pic" src="' + img + '" alt="' + alt + '"' + style + '>' + img2 + '</a></div>')
350 366
         elif len(l) == 5:
351 367
             v_i += 1
352 368
             link, mime, thumb, poster, alt = videos[v_i]
@@ -357,19 +373,19 @@ def lightgallery(links):
357 373
                 x = link.rfind('.')
358 374
                 poster = link[:x] + '_poster.png'
359 375
             lightgallery_check_thumbnail_video(link, thumb, poster)
360
-            print '<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '_' + str(v_ii) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>'
376
+            print('<div class="border" data-poster="' + poster + '" data-sub-html="' + alt + '" data-html="#video' + str(v_i) + '_' + str(v_ii) + '"><a href="' + link + '"><img class="pic" src="' + thumb + '"></a></div>')
361 377
         else:
362 378
             raise NameError('Invalid number of arguments for lightgallery')
363
-    print '</div>'
379
+    print('</div>')
364 380
 
365 381
 # -----------------------------------------------------------------------------
366 382
 # github helper macros
367 383
 # -----------------------------------------------------------------------------
368 384
 
369
-import urllib, json, sys
385
+import json, sys
370 386
 
371 387
 def restRequest(url):
372
-    response = urllib.urlopen(url)
388
+    response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
373 389
     if response.getcode() != 200:
374 390
         sys.stderr.write("\n")
375 391
         sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
@@ -430,11 +446,11 @@ def printLatestRelease(user, repo):
430 446
     print("</ul></div>")
431 447
 
432 448
 def include_url(url):
433
-    response = urllib.urlopen(url)
449
+    response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
434 450
     if response.getcode() != 200:
435 451
         raise Exception("invalid response code", response.getcode())
436 452
     data = response.read()
437
-    print data,
453
+    print(data,)
438 454
 
439 455
 # -----------------------------------------------------------------------------
440 456
 # preconvert hooks
@@ -457,7 +473,7 @@ def hook_preconvert_anotherlang():
457 473
                                         [lang.strip() for lang in text_lang[1::2]], \
458 474
                                         text_lang[::2]))
459 475
 
460
-        for lang, text in text_grouped.iteritems():
476
+        for lang, text in (iter(text_grouped.items()) if PY3 else text_grouped.iteritems()):
461 477
             spath = p.fname.split(os.path.sep)
462 478
             langs.append(lang)
463 479
 
@@ -469,19 +485,19 @@ def hook_preconvert_anotherlang():
469 485
             vp = Page(filename, virtual=text)
470 486
             # Copy real page attributes to the virtual page
471 487
             for attr in p:
472
-                if not vp.has_key(attr):
488
+                if not ((attr in vp) if PY3 else vp.has_key(attr)):
473 489
                     vp[attr] = p[attr]
474 490
             # Define a title in the proper language
475 491
             vp["title"] = p["title_%s" % lang] \
476
-                                    if p.has_key("title_%s" % lang) \
492
+                                    if ((("title_%s" % lang) in p) if PY3 else p.has_key("title_%s" % lang)) \
477 493
                                     else p["title"]
478 494
             # Keep track of the current lang of the virtual page
479 495
             vp["lang"] = lang
480 496
             page_vpages[lang] = vp
481 497
 
482 498
         # Each virtual page has to know about its sister vpages
483
-        for lang, vpage in page_vpages.iteritems():
484
-            vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
499
+        for lang, vpage in (iter(page_vpages.items()) if PY3 else page_vpages.iteritems()):
500
+            vpage["lang_links"] = dict([(l, v["url"]) for l, v in (iter(page_vpages.items()) if PY3 else page_vpages.iteritems())])
485 501
             vpage["other_lang"] = langs # set other langs and link
486 502
 
487 503
         vpages += page_vpages.values()
@@ -719,7 +735,7 @@ def hook_postconvert_size():
719 735
             else:
720 736
                 return  "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
721 737
         except:
722
-            print "Unable to estimate file size for %s" % matchobj.group(1)
738
+            print("Unable to estimate file size for %s" % matchobj.group(1))
723 739
             return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
724 740
     _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
725 741
     for p in pages:

+ 30
- 29
page.html 파일 보기

@@ -1,9 +1,9 @@
1 1
 <!DOCTYPE html>
2 2
 <!--%
3 3
 if page.get("lang", "en") == "de":
4
-    print '<html lang="de">'
4
+    print('<html lang="de">')
5 5
 else:
6
-    print '<html lang="en">'
6
+    print('<html lang="en">')
7 7
 %-->
8 8
 <head>
9 9
     <meta charset="{{ htmlspecialchars(__encoding__) }}" />
@@ -29,10 +29,10 @@ else:
29 29
 
30 30
         if link != "":
31 31
             # GitHub Fork-Me Ribbon
32
-            print '<div class="github-fork-ribbon-wrapper right-bottom">'
33
-            print '<div class="github-fork-ribbon"><a href="'
34
-            print link
35
-            print '">Fork this with Git</a></div></div>'
32
+            print('<div class="github-fork-ribbon-wrapper right-bottom">')
33
+            print('<div class="github-fork-ribbon"><a href="')
34
+            print(link)
35
+            print('">Fork this with Git</a></div></div>')
36 36
     %-->
37 37
     <div id="wrap"><div id="nav">
38 38
         <ul id="navbar">
@@ -55,11 +55,12 @@ else:
55 55
                 <li><a class="inc" href="#"><span class="font-small">A</span><span class="font-big">A</span></a></li>
56 56
             </div>
57 57
             <!--%
58
-                tmp = [p for p in page["lang_links"].iteritems()]
58
+                PY3 = sys.version_info[0] == 3
59
+                tmp = [p for p in ((iter(page["lang_links"].items())) if PY3 else (page["lang_links"].iteritems()))]
59 60
                 if len(tmp) > 1:
60
-                    print '            <li>'
61
-                    print " ".join(["<li><a href='%s'>%s</a></li>" % (url, lang) for lang, url in page["lang_links"].iteritems()]).replace(">en<", '><img src="img/en.png" alt="English"><').replace(">de<", '><img src="img/de.png" alt="Deutsch"><')
62
-                    print "</li>"
61
+                    print('            <li>')
62
+                    print(" ".join(["<li><a href='%s'>%s</a></li>" % (url, lang) for lang, url in ((iter(page["lang_links"].items())) if PY3 else (page["lang_links"].iteritems()))]).replace(">en<", '><img src="img/en.png" alt="English"><').replace(">de<", '><img src="img/de.png" alt="Deutsch"><'))
63
+                    print("</li>")
63 64
             %-->
64 65
         </ul>
65 66
     </div></div>
@@ -69,63 +70,63 @@ else:
69 70
 
70 71
             if page.get("noheader", "false") == "false":
71 72
                 if page.get("title", "") == "Blog":
72
-                    print "<h1>%s</h1>" % (page.get("post", ""))
73
+                    print("<h1>%s</h1>" % (page.get("post", "")))
73 74
                 else:
74 75
                     if page.get("lang", "en") == "de":
75
-                        print "<h1>%s</h1>" % (page.get("title_de", ""))
76
+                        print("<h1>%s</h1>" % (page.get("title_de", "")))
76 77
                     else:
77
-                        print "<h1>%s</h1>" % (page.get("title", ""))
78
+                        print("<h1>%s</h1>" % (page.get("title", "")))
78 79
 
79 80
                 if page.get("lang", "en") == "de":
80 81
                     if page.get("description_de", "") != "":
81
-                        print "<h5>%s</h5>" % (page.get("description_de", ""))
82
+                        print("<h5>%s</h5>" % (page.get("description_de", "")))
82 83
                     elif page.get("description", "") != "":
83
-                        print "<h5>%s</h5>" % (page.get("description", ""))
84
+                        print("<h5>%s</h5>" % (page.get("description", "")))
84 85
                 else:
85 86
                     if page.get("description", "") != "":
86
-                        print "<h5>%s</h5>" % (page.get("description", ""))
87
+                        print("<h5>%s</h5>" % (page.get("description", "")))
87 88
 
88 89
                 if page.get("date", "") != "":
89 90
                     if page.get("title", "") == "Blog":
90 91
                         if page.get("lang", "en") == "de":
91 92
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%d.%m.%Y")
92
-                            print "<i>Ver&ouml;ffentlicht am %s.</i>" % date
93
+                            print("<i>Ver&ouml;ffentlicht am %s.</i>" % date)
93 94
                         else:
94 95
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%B %d, %Y")
95
-                            print "<i>Published on %s.</i>" % date
96
+                            print("<i>Published on %s.</i>" % date)
96 97
                     else:
97 98
                         if page.get("lang", "en") == "de":
98 99
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%d.%m.%Y")
99
-                            print "<i>Projekt gestartet am %s.</i>" % date
100
+                            print("<i>Projekt gestartet am %s.</i>" % date)
100 101
                         else:
101 102
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%B %d, %Y")
102
-                            print "<i>Project started on %s.</i>" % date
103
+                            print("<i>Project started on %s.</i>" % date)
103 104
 
104 105
                 if page.get("date", "") != "" and page.get("update", "") != "":
105
-                    print "<br>"
106
+                    print("<br>")
106 107
 
107 108
                 if page.get("update", "") != "":
108 109
                     if page.get("lang", "en") == "de":
109 110
                         date = datetime.strptime(page["update"], "%Y-%m-%d").strftime("%d.%m.%Y")
110
-                        print "<i>Zuletzt aktualisiert am %s.</i>" % date
111
+                        print("<i>Zuletzt aktualisiert am %s.</i>" % date)
111 112
                     else:
112 113
                         date = datetime.strptime(page["update"], "%Y-%m-%d").strftime("%B %d, %Y")
113
-                        print "<i>Last updated on %s.</i>" % date
114
+                        print("<i>Last updated on %s.</i>" % date)
114 115
 
115 116
             link = githubCommitBadge(page, True)
116 117
             if len(link) > 0:
117
-                print "<p>Recent activity on GitHub: " + link + "</p>"
118
+                print("<p>Recent activity on GitHub: " + link + "</p>")
118 119
         %-->
119 120
         {{ __content__ }}
120 121
         <hr>
121 122
         <!--%
122 123
             # Comments
123 124
             if page.get("comments", "false") == "true":
124
-                print '<div id="commento"></div>'
125
-                print '<hr>'
125
+                print('<div id="commento"></div>')
126
+                print('<hr>')
126 127
             elif page.get("comments", "false") != "false":
127
-                print '<div style="text-align: center;"><a href="%s">Head over here to discuss this article!</a></div>' % page.get("comments", "false")
128
-                print '<hr>'
128
+                print('<div style="text-align: center;"><a href="%s">Head over here to discuss this article!</a></div>' % page.get("comments", "false"))
129
+                print('<hr>')
129 130
         %-->
130 131
     </div>
131 132
     <div id="footer">
@@ -173,7 +174,7 @@ else:
173 174
     <script type="text/javascript" src="js/jquery.min.js"></script>
174 175
     <!--%
175 176
         if page.get("comments", "false") == "true":
176
-            print '<script defer src="https://comments.xythobuz.de/js/commento.js"></script>'
177
+            print('<script defer src="https://comments.xythobuz.de/js/commento.js"></script>')
177 178
     %-->
178 179
     <script type="text/javascript">
179 180
         $(document).ready(function() {

+ 43
- 19
poole.py 파일 보기

@@ -1,4 +1,4 @@
1
-#!/usr/bin/env python2
1
+#!/usr/bin/env python
2 2
 # -*- coding: utf-8 -*-
3 3
 
4 4
 # =============================================================================
@@ -27,20 +27,14 @@ from __future__ import with_statement
27 27
 
28 28
 import codecs
29 29
 import glob
30
-import imp
31 30
 import optparse
32 31
 import os
33 32
 from os.path import join as opj
34 33
 from os.path import exists as opx
35 34
 import re
36 35
 import shutil
37
-import StringIO
38 36
 import sys
39 37
 import traceback
40
-import urlparse
41
-
42
-from SimpleHTTPServer import SimpleHTTPRequestHandler
43
-from BaseHTTPServer import HTTPServer
44 38
 
45 39
 try:
46 40
     import markdown
@@ -58,14 +52,39 @@ PY3 = sys.version_info[0] == 3
58 52
 if PY3:
59 53
     import builtins
60 54
     exec_ = getattr(builtins, "exec")
55
+    import importlib.util
56
+    import importlib.machinery
57
+    def imp_load_source(modname, filename):
58
+        loader = importlib.machinery.SourceFileLoader(modname, filename)
59
+        spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
60
+        module = importlib.util.module_from_spec(spec)
61
+        # The module is always executed and not cached in sys.modules.
62
+        # Uncomment the following line to cache the module.
63
+        # sys.modules[module.__name__] = module
64
+        loader.exec_module(module)
65
+        return module
66
+    import urllib
67
+    def urlparse_urljoin(a, b):
68
+        return urllib.parse.urljoin(a, b)
69
+    from io import StringIO
70
+    from http.server import HTTPServer, SimpleHTTPRequestHandler
61 71
 else:
62 72
     import tempfile
73
+    from StringIO import StringIO
74
+    from SimpleHTTPServer import SimpleHTTPRequestHandler
75
+    from BaseHTTPServer import HTTPServer
63 76
     def exec_(code, envdic):
64 77
         with tempfile.NamedTemporaryFile() as tf:
65 78
             tf.write('# -*- coding: utf-8 -*-\n')
66 79
             tf.write(code.encode('utf-8'))
67 80
             tf.flush()
68 81
             execfile(tf.name, envdic)
82
+    import imp
83
+    def imp_load_source(module_name, module_path):
84
+        imp.load_source(module_name, module_path)
85
+    import urlparse
86
+    def urlparse_urljoin(a, b):
87
+        return urlparse.urljoin(a, b)
69 88
 
70 89
 # =============================================================================
71 90
 # init site
@@ -402,7 +421,7 @@ def build(project, opts):
402 421
     regx_escp = re.compile(r'\\((?:(?:&lt;|<)!--|{)(?:{|%))') # escaped code
403 422
     repl_escp = r'\1'
404 423
     regx_rurl = re.compile(r'(?<=(?:(?:\n| )src|href)=")([^#/&%].*?)(?=")')
405
-    repl_rurl = lambda m: urlparse.urljoin(opts.base_url, m.group(1))
424
+    repl_rurl = lambda m: urlparse_urljoin(opts.base_url, m.group(1))
406 425
 
407 426
     regx_eval = re.compile(r'(?<!\\)(?:(?:<!--|{){)(.*?)(?:}(?:-->|}))', re.S)
408 427
 
@@ -415,10 +434,14 @@ def build(project, opts):
415 434
         except:
416 435
             abort_iex(page, "expression", expr, traceback.format_exc())
417 436
         else:
418
-            if not isinstance(repl, basestring): # e.g. numbers
419
-                repl = unicode(repl)
420
-            elif not isinstance(repl, unicode):
421
-                repl = repl.decode("utf-8")
437
+            if PY3:
438
+                if not isinstance(repl, str):
439
+                    repl = str(repl)
440
+            else:
441
+                if not isinstance(repl, basestring): # e.g. numbers
442
+                    repl = unicode(repl)
443
+                elif not isinstance(repl, unicode):
444
+                    repl = repl.decode("utf-8")
422 445
             return repl
423 446
 
424 447
     regx_exec = re.compile(r'(?<!\\)(?:(?:<!--|{)%)(.*?)(?:%(?:-->|}))', re.S)
@@ -434,7 +457,7 @@ def build(project, opts):
434 457
         stmt = ind_rex.sub('', stmt)
435 458
 
436 459
         # execute
437
-        sys.stdout = StringIO.StringIO()
460
+        sys.stdout = StringIO()
438 461
         try:
439 462
             exec_(stmt, macros.copy())
440 463
         except:
@@ -443,8 +466,9 @@ def build(project, opts):
443 466
         else:
444 467
             repl = sys.stdout.getvalue()[:-1] # remove last line break
445 468
             sys.stdout = sys.__stdout__
446
-            if not isinstance(repl, unicode):
447
-                repl = repl.decode(opts.input_enc)
469
+            if not PY3:
470
+                if not isinstance(repl, unicode):
471
+                    repl = repl.decode(opts.input_enc)
448 472
             return repl
449 473
 
450 474
     # -------------------------------------------------------------------------
@@ -473,7 +497,7 @@ def build(project, opts):
473 497
 
474 498
     # macro module
475 499
     fname = opj(opts.project, "macros.py")
476
-    macros = imp.load_source("macros", fname).__dict__ if opx(fname) else {}
500
+    macros = imp_load_source("macros", fname).__dict__ if opx(fname) else {}
477 501
 
478 502
     macros["__encoding__"] = opts.output_enc
479 503
     macros["options"] = opts
@@ -495,7 +519,7 @@ def build(project, opts):
495 519
     pages = []
496 520
     custom_converter = macros.get('converter', {})
497 521
 
498
-    for cwd, dirs, files in os.walk(dir_in.decode(opts.filename_enc)):
522
+    for cwd, dirs, files in os.walk(dir_in if PY3 else dir_in.decode(opts.filename_enc)):
499 523
         cwd_site = cwd[len(dir_in):].lstrip(os.path.sep)
500 524
         for sdir in dirs[:]:
501 525
             if re.search(opts.ignore, opj(cwd_site, sdir)):
@@ -621,7 +645,7 @@ def removeEmptyFolders(path):
621 645
     # if folder empty, delete it
622 646
     files = os.listdir(path)
623 647
     if len(files) == 0:
624
-        print "info   : removing empty folder: ", path
648
+        print("info   : removing empty folder: ", path)
625 649
         os.rmdir(path)
626 650
 
627 651
 # =============================================================================
@@ -666,7 +690,7 @@ def options():
666 690
     og.add_option("", "--base-url", default="/", metavar="URL",
667 691
                   help="base url for relative links (default: /)")
668 692
     og.add_option("" , "--ignore", default=r"^\.|~$", metavar="REGEX",
669
-                  help="input files to ignore (default: '^\.|~$')")
693
+                  help="input files to ignore (default: '^\\.|~$')")
670 694
     og.add_option("" , "--md-ext", default=[], metavar="EXT",
671 695
                   action="append", help="enable a markdown extension")
672 696
     og.add_option("", "--input-enc", default="utf-8", metavar="ENC",

Loading…
취소
저장