2 Коміти

Автор SHA1 Повідомлення Дата
  Thomas B 6b1c517201 fixes for py2 py3 compat 4 місяці тому
  Thomas B 6bb17c26c8 port to python3 but keep py2 compatibility 4 місяці тому
4 змінених файлів з 134 додано та 89 видалено
  1. 1
    1
      input/index.md
  2. 59
    40
      macros.py
  3. 30
    29
      page.html
  4. 44
    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!

+ 59
- 40
macros.py Переглянути файл

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

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

Завантаження…
Відмінити
Зберегти