Browse Source

port to python3 but keep py2 compatibility

Thomas B 2 months ago
parent
commit
6bb17c26c8
4 changed files with 128 additions and 87 deletions
  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 View File

28
 end_date = datetime.now()
28
 end_date = datetime.now()
29
 difference_in_years = date_as_float(end_date) - date_as_float(start_date)
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
 %--> year old software developer from Germany.
33
 %--> year old software developer from Germany.
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!
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 View File

1
 # -*- coding: utf-8 -*-
1
 # -*- coding: utf-8 -*-
2
 
2
 
3
+import sys
3
 import re
4
 import re
4
 import itertools
5
 import itertools
5
 import email.utils
6
 import email.utils
7
 import time
8
 import time
8
 import codecs
9
 import codecs
9
 from datetime import datetime
10
 from datetime import datetime
10
-import urlparse
11
 
11
 
12
 DEFAULT_LANG = "en"
12
 DEFAULT_LANG = "en"
13
 BASE_URL = "https://www.xythobuz.de"
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
 # sub page helper macro
32
 # sub page helper macro
17
 # -----------------------------------------------------------------------------
33
 # -----------------------------------------------------------------------------
30
     # print if any parent link found
46
     # print if any parent link found
31
     if len(posts) > 0:
47
     if len(posts) > 0:
32
         p = posts[0]
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
 # table helper macro
52
 # table helper macro
37
 # -----------------------------------------------------------------------------
53
 # -----------------------------------------------------------------------------
38
 
54
 
39
 def tableHelper(style, header, content):
55
 def tableHelper(style, header, content):
40
-    print "<table>"
56
+    print("<table>")
41
     if (header != None) and (len(header) == len(style)):
57
     if (header != None) and (len(header) == len(style)):
42
-        print "<tr>"
58
+        print("<tr>")
43
         for h in header:
59
         for h in header:
44
-            print "<th>" + h + "</th>"
45
-        print "</tr>"
60
+            print("<th>" + h + "</th>")
61
+        print("</tr>")
46
     for ci in range(0, len(content)):
62
     for ci in range(0, len(content)):
47
         if len(content[ci]) != len(style):
63
         if len(content[ci]) != len(style):
48
             # invalid call of table helper!
64
             # invalid call of table helper!
49
             continue
65
             continue
50
-        print "<tr>"
66
+        print("<tr>")
51
         for i in range(0, len(style)):
67
         for i in range(0, len(style)):
52
             s = style[i]
68
             s = style[i]
53
             td_style = ""
69
             td_style = ""
70
             if td_style != "":
86
             if td_style != "":
71
                 td_args = " style=\"" + td_style + "\""
87
                 td_args = " style=\"" + td_style + "\""
72
 
88
 
73
-            print "<td" + td_args + ">"
89
+            print("<td" + td_args + ">")
74
 
90
 
75
             if isinstance(content[ci][i], tuple):
91
             if isinstance(content[ci][i], tuple):
76
                 text, link = content[ci][i]
92
                 text, link = content[ci][i]
77
-                print "<a href=\"" + link + "\">" + text + "</a>"
93
+                print("<a href=\"" + link + "\">" + text + "</a>")
78
             else:
94
             else:
79
                 text = content[ci][i]
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
 # menu helper macro
102
 # menu helper macro
112
     if year != lastyear:
128
     if year != lastyear:
113
         lastyear = year
129
         lastyear = year
114
         if yearsAsHeading:
130
         if yearsAsHeading:
115
-            print "\n\n#### %s\n" % (year)
131
+            print("\n\n#### %s\n" % (year))
116
 
132
 
117
     dateto = ""
133
     dateto = ""
118
     if p.get("date", "" != ""):
134
     if p.get("date", "" != ""):
127
         if nicelyFormatFullDate:
143
         if nicelyFormatFullDate:
128
             dateto = " - " + datetime.strptime(p.get("update", p.date), "%Y-%m-%d").strftime("%B %d, %Y")
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
     if p.get("description", "") != "":
148
     if p.get("description", "") != "":
133
         description = p.get("description", "")
149
         description = p.get("description", "")
134
         if lang != "":
150
         if lang != "":
135
             if p.get("description_" + lang, "") != "":
151
             if p.get("description_" + lang, "") != "":
136
                 description = p.get("description_" + lang, "")
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
     if showLastCommit:
155
     if showLastCommit:
140
         link = githubCommitBadge(p)
156
         link = githubCommitBadge(p)
141
         if len(link) > 0:
157
         if len(link) > 0:
142
-            print "<br>" + link
158
+            print("<br>" + link)
143
 
159
 
144
     return lastyear
160
     return lastyear
145
 
161
 
318
     for v in videos:
334
     for v in videos:
319
         link, mime, thumb, poster, alt = v
335
         link, mime, thumb, poster, alt = v
320
         v_i += 1
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
     v_i = -1
345
     v_i = -1
330
     for l in links:
346
     for l in links:
331
         if (len(l) == 3) or (len(l) == 2):
347
         if (len(l) == 3) or (len(l) == 2):
337
                 link, alt = l
353
                 link, alt = l
338
                 if "youtube.com" in link:
354
                 if "youtube.com" in link:
339
                     img = "https://img.youtube.com/vi/"
355
                     img = "https://img.youtube.com/vi/"
340
-                    img += urlparse.parse_qs(urlparse.urlparse(link).query)['v'][0]
356
+                    img += urlparse_foo(link)
341
                     img += "/0.jpg" # full size preview
357
                     img += "/0.jpg" # full size preview
342
                     #img += "/default.jpg" # default thumbnail
358
                     #img += "/default.jpg" # default thumbnail
343
                     style = ' style="width:300px;"'
359
                     style = ' style="width:300px;"'
346
                     x = link.rfind('.')
362
                     x = link.rfind('.')
347
                     img = link[:x] + '_small' + link[x:]
363
                     img = link[:x] + '_small' + link[x:]
348
             lightgallery_check_thumbnail(link, img)
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
         elif len(l) == 5:
366
         elif len(l) == 5:
351
             v_i += 1
367
             v_i += 1
352
             link, mime, thumb, poster, alt = videos[v_i]
368
             link, mime, thumb, poster, alt = videos[v_i]
357
                 x = link.rfind('.')
373
                 x = link.rfind('.')
358
                 poster = link[:x] + '_poster.png'
374
                 poster = link[:x] + '_poster.png'
359
             lightgallery_check_thumbnail_video(link, thumb, poster)
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
         else:
377
         else:
362
             raise NameError('Invalid number of arguments for lightgallery')
378
             raise NameError('Invalid number of arguments for lightgallery')
363
-    print '</div>'
379
+    print('</div>')
364
 
380
 
365
 # -----------------------------------------------------------------------------
381
 # -----------------------------------------------------------------------------
366
 # github helper macros
382
 # github helper macros
367
 # -----------------------------------------------------------------------------
383
 # -----------------------------------------------------------------------------
368
 
384
 
369
-import urllib, json, sys
385
+import json, sys
370
 
386
 
371
 def restRequest(url):
387
 def restRequest(url):
372
-    response = urllib.urlopen(url)
388
+    response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
373
     if response.getcode() != 200:
389
     if response.getcode() != 200:
374
         sys.stderr.write("\n")
390
         sys.stderr.write("\n")
375
         sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
391
         sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
430
     print("</ul></div>")
446
     print("</ul></div>")
431
 
447
 
432
 def include_url(url):
448
 def include_url(url):
433
-    response = urllib.urlopen(url)
449
+    response = urllib.request.urlopen(url) if PY3 else urllib.urlopen(url)
434
     if response.getcode() != 200:
450
     if response.getcode() != 200:
435
         raise Exception("invalid response code", response.getcode())
451
         raise Exception("invalid response code", response.getcode())
436
     data = response.read()
452
     data = response.read()
437
-    print data,
453
+    print(data,)
438
 
454
 
439
 # -----------------------------------------------------------------------------
455
 # -----------------------------------------------------------------------------
440
 # preconvert hooks
456
 # preconvert hooks
457
                                         [lang.strip() for lang in text_lang[1::2]], \
473
                                         [lang.strip() for lang in text_lang[1::2]], \
458
                                         text_lang[::2]))
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
             spath = p.fname.split(os.path.sep)
477
             spath = p.fname.split(os.path.sep)
462
             langs.append(lang)
478
             langs.append(lang)
463
 
479
 
469
             vp = Page(filename, virtual=text)
485
             vp = Page(filename, virtual=text)
470
             # Copy real page attributes to the virtual page
486
             # Copy real page attributes to the virtual page
471
             for attr in p:
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
                     vp[attr] = p[attr]
489
                     vp[attr] = p[attr]
474
             # Define a title in the proper language
490
             # Define a title in the proper language
475
             vp["title"] = p["title_%s" % lang] \
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
                                     else p["title"]
493
                                     else p["title"]
478
             # Keep track of the current lang of the virtual page
494
             # Keep track of the current lang of the virtual page
479
             vp["lang"] = lang
495
             vp["lang"] = lang
480
             page_vpages[lang] = vp
496
             page_vpages[lang] = vp
481
 
497
 
482
         # Each virtual page has to know about its sister vpages
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
             vpage["other_lang"] = langs # set other langs and link
501
             vpage["other_lang"] = langs # set other langs and link
486
 
502
 
487
         vpages += page_vpages.values()
503
         vpages += page_vpages.values()
719
             else:
735
             else:
720
                 return  "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
736
                 return  "<a href=\"%s\">%s</a>&nbsp;(%d Byte)" % (matchobj.group(1), matchobj.group(3), size)
721
         except:
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
             return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
739
             return '<a href=\"%s\">%s</a>' % (matchobj.group(1), matchobj.group(3))
724
     _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
740
     _re_url = '<a href=\"([^\"]*?\.(%s))\">(.*?)<\/a>' % file_ext
725
     for p in pages:
741
     for p in pages:

+ 30
- 29
page.html View File

1
 <!DOCTYPE html>
1
 <!DOCTYPE html>
2
 <!--%
2
 <!--%
3
 if page.get("lang", "en") == "de":
3
 if page.get("lang", "en") == "de":
4
-    print '<html lang="de">'
4
+    print('<html lang="de">')
5
 else:
5
 else:
6
-    print '<html lang="en">'
6
+    print('<html lang="en">')
7
 %-->
7
 %-->
8
 <head>
8
 <head>
9
     <meta charset="{{ htmlspecialchars(__encoding__) }}" />
9
     <meta charset="{{ htmlspecialchars(__encoding__) }}" />
29
 
29
 
30
         if link != "":
30
         if link != "":
31
             # GitHub Fork-Me Ribbon
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
     <div id="wrap"><div id="nav">
37
     <div id="wrap"><div id="nav">
38
         <ul id="navbar">
38
         <ul id="navbar">
55
                 <li><a class="inc" href="#"><span class="font-small">A</span><span class="font-big">A</span></a></li>
55
                 <li><a class="inc" href="#"><span class="font-small">A</span><span class="font-big">A</span></a></li>
56
             </div>
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
                 if len(tmp) > 1:
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
         </ul>
65
         </ul>
65
     </div></div>
66
     </div></div>
69
 
70
 
70
             if page.get("noheader", "false") == "false":
71
             if page.get("noheader", "false") == "false":
71
                 if page.get("title", "") == "Blog":
72
                 if page.get("title", "") == "Blog":
72
-                    print "<h1>%s</h1>" % (page.get("post", ""))
73
+                    print("<h1>%s</h1>" % (page.get("post", "")))
73
                 else:
74
                 else:
74
                     if page.get("lang", "en") == "de":
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
                     else:
77
                     else:
77
-                        print "<h1>%s</h1>" % (page.get("title", ""))
78
+                        print("<h1>%s</h1>" % (page.get("title", "")))
78
 
79
 
79
                 if page.get("lang", "en") == "de":
80
                 if page.get("lang", "en") == "de":
80
                     if page.get("description_de", "") != "":
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
                     elif page.get("description", "") != "":
83
                     elif page.get("description", "") != "":
83
-                        print "<h5>%s</h5>" % (page.get("description", ""))
84
+                        print("<h5>%s</h5>" % (page.get("description", "")))
84
                 else:
85
                 else:
85
                     if page.get("description", "") != "":
86
                     if page.get("description", "") != "":
86
-                        print "<h5>%s</h5>" % (page.get("description", ""))
87
+                        print("<h5>%s</h5>" % (page.get("description", "")))
87
 
88
 
88
                 if page.get("date", "") != "":
89
                 if page.get("date", "") != "":
89
                     if page.get("title", "") == "Blog":
90
                     if page.get("title", "") == "Blog":
90
                         if page.get("lang", "en") == "de":
91
                         if page.get("lang", "en") == "de":
91
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%d.%m.%Y")
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
                         else:
94
                         else:
94
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%B %d, %Y")
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
                     else:
97
                     else:
97
                         if page.get("lang", "en") == "de":
98
                         if page.get("lang", "en") == "de":
98
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%d.%m.%Y")
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
                         else:
101
                         else:
101
                             date = datetime.strptime(page["date"], "%Y-%m-%d").strftime("%B %d, %Y")
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
                 if page.get("date", "") != "" and page.get("update", "") != "":
105
                 if page.get("date", "") != "" and page.get("update", "") != "":
105
-                    print "<br>"
106
+                    print("<br>")
106
 
107
 
107
                 if page.get("update", "") != "":
108
                 if page.get("update", "") != "":
108
                     if page.get("lang", "en") == "de":
109
                     if page.get("lang", "en") == "de":
109
                         date = datetime.strptime(page["update"], "%Y-%m-%d").strftime("%d.%m.%Y")
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
                     else:
112
                     else:
112
                         date = datetime.strptime(page["update"], "%Y-%m-%d").strftime("%B %d, %Y")
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
             link = githubCommitBadge(page, True)
116
             link = githubCommitBadge(page, True)
116
             if len(link) > 0:
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
         {{ __content__ }}
120
         {{ __content__ }}
120
         <hr>
121
         <hr>
121
         <!--%
122
         <!--%
122
             # Comments
123
             # Comments
123
             if page.get("comments", "false") == "true":
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
             elif page.get("comments", "false") != "false":
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
     </div>
131
     </div>
131
     <div id="footer">
132
     <div id="footer">
173
     <script type="text/javascript" src="js/jquery.min.js"></script>
174
     <script type="text/javascript" src="js/jquery.min.js"></script>
174
     <!--%
175
     <!--%
175
         if page.get("comments", "false") == "true":
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
     <script type="text/javascript">
179
     <script type="text/javascript">
179
         $(document).ready(function() {
180
         $(document).ready(function() {

+ 43
- 19
poole.py View File

1
-#!/usr/bin/env python2
1
+#!/usr/bin/env python
2
 # -*- coding: utf-8 -*-
2
 # -*- coding: utf-8 -*-
3
 
3
 
4
 # =============================================================================
4
 # =============================================================================
27
 
27
 
28
 import codecs
28
 import codecs
29
 import glob
29
 import glob
30
-import imp
31
 import optparse
30
 import optparse
32
 import os
31
 import os
33
 from os.path import join as opj
32
 from os.path import join as opj
34
 from os.path import exists as opx
33
 from os.path import exists as opx
35
 import re
34
 import re
36
 import shutil
35
 import shutil
37
-import StringIO
38
 import sys
36
 import sys
39
 import traceback
37
 import traceback
40
-import urlparse
41
-
42
-from SimpleHTTPServer import SimpleHTTPRequestHandler
43
-from BaseHTTPServer import HTTPServer
44
 
38
 
45
 try:
39
 try:
46
     import markdown
40
     import markdown
58
 if PY3:
52
 if PY3:
59
     import builtins
53
     import builtins
60
     exec_ = getattr(builtins, "exec")
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
 else:
71
 else:
62
     import tempfile
72
     import tempfile
73
+    from StringIO import StringIO
74
+    from SimpleHTTPServer import SimpleHTTPRequestHandler
75
+    from BaseHTTPServer import HTTPServer
63
     def exec_(code, envdic):
76
     def exec_(code, envdic):
64
         with tempfile.NamedTemporaryFile() as tf:
77
         with tempfile.NamedTemporaryFile() as tf:
65
             tf.write('# -*- coding: utf-8 -*-\n')
78
             tf.write('# -*- coding: utf-8 -*-\n')
66
             tf.write(code.encode('utf-8'))
79
             tf.write(code.encode('utf-8'))
67
             tf.flush()
80
             tf.flush()
68
             execfile(tf.name, envdic)
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
 # init site
90
 # init site
402
     regx_escp = re.compile(r'\\((?:(?:&lt;|<)!--|{)(?:{|%))') # escaped code
421
     regx_escp = re.compile(r'\\((?:(?:&lt;|<)!--|{)(?:{|%))') # escaped code
403
     repl_escp = r'\1'
422
     repl_escp = r'\1'
404
     regx_rurl = re.compile(r'(?<=(?:(?:\n| )src|href)=")([^#/&%].*?)(?=")')
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
     regx_eval = re.compile(r'(?<!\\)(?:(?:<!--|{){)(.*?)(?:}(?:-->|}))', re.S)
426
     regx_eval = re.compile(r'(?<!\\)(?:(?:<!--|{){)(.*?)(?:}(?:-->|}))', re.S)
408
 
427
 
415
         except:
434
         except:
416
             abort_iex(page, "expression", expr, traceback.format_exc())
435
             abort_iex(page, "expression", expr, traceback.format_exc())
417
         else:
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
             return repl
445
             return repl
423
 
446
 
424
     regx_exec = re.compile(r'(?<!\\)(?:(?:<!--|{)%)(.*?)(?:%(?:-->|}))', re.S)
447
     regx_exec = re.compile(r'(?<!\\)(?:(?:<!--|{)%)(.*?)(?:%(?:-->|}))', re.S)
434
         stmt = ind_rex.sub('', stmt)
457
         stmt = ind_rex.sub('', stmt)
435
 
458
 
436
         # execute
459
         # execute
437
-        sys.stdout = StringIO.StringIO()
460
+        sys.stdout = StringIO()
438
         try:
461
         try:
439
             exec_(stmt, macros.copy())
462
             exec_(stmt, macros.copy())
440
         except:
463
         except:
443
         else:
466
         else:
444
             repl = sys.stdout.getvalue()[:-1] # remove last line break
467
             repl = sys.stdout.getvalue()[:-1] # remove last line break
445
             sys.stdout = sys.__stdout__
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
             return repl
472
             return repl
449
 
473
 
450
     # -------------------------------------------------------------------------
474
     # -------------------------------------------------------------------------
473
 
497
 
474
     # macro module
498
     # macro module
475
     fname = opj(opts.project, "macros.py")
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
     macros["__encoding__"] = opts.output_enc
502
     macros["__encoding__"] = opts.output_enc
479
     macros["options"] = opts
503
     macros["options"] = opts
495
     pages = []
519
     pages = []
496
     custom_converter = macros.get('converter', {})
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
         cwd_site = cwd[len(dir_in):].lstrip(os.path.sep)
523
         cwd_site = cwd[len(dir_in):].lstrip(os.path.sep)
500
         for sdir in dirs[:]:
524
         for sdir in dirs[:]:
501
             if re.search(opts.ignore, opj(cwd_site, sdir)):
525
             if re.search(opts.ignore, opj(cwd_site, sdir)):
621
     # if folder empty, delete it
645
     # if folder empty, delete it
622
     files = os.listdir(path)
646
     files = os.listdir(path)
623
     if len(files) == 0:
647
     if len(files) == 0:
624
-        print "info   : removing empty folder: ", path
648
+        print("info   : removing empty folder: ", path)
625
         os.rmdir(path)
649
         os.rmdir(path)
626
 
650
 
627
 # =============================================================================
651
 # =============================================================================
666
     og.add_option("", "--base-url", default="/", metavar="URL",
690
     og.add_option("", "--base-url", default="/", metavar="URL",
667
                   help="base url for relative links (default: /)")
691
                   help="base url for relative links (default: /)")
668
     og.add_option("" , "--ignore", default=r"^\.|~$", metavar="REGEX",
692
     og.add_option("" , "--ignore", default=r"^\.|~$", metavar="REGEX",
669
-                  help="input files to ignore (default: '^\.|~$')")
693
+                  help="input files to ignore (default: '^\\.|~$')")
670
     og.add_option("" , "--md-ext", default=[], metavar="EXT",
694
     og.add_option("" , "--md-ext", default=[], metavar="EXT",
671
                   action="append", help="enable a markdown extension")
695
                   action="append", help="enable a markdown extension")
672
     og.add_option("", "--input-enc", default="utf-8", metavar="ENC",
696
     og.add_option("", "--input-enc", default="utf-8", metavar="ENC",

Loading…
Cancel
Save