Warning: Can not open [/home/conf/public_html/cgi-bin/show_python.log]. Ignore if ret:
title = ''
for j in range(i+1, len(lines)):

Download script from show_python.py
Related files:


#!/usr/bin/python3

import sys
import re
import os
import glob
import cgi
import cgitb
#cgitb.enable()


from tklib.tkapplication_cgi import tkApplication_CGI
from tklib.tkutils import pint, pfloat, getarg, getintarg, getfloatarg, split_file_path



infile = None
web_root = "/home/conf/public_html"
url_root = "/"

# global variables
red1 = ''
red2 = '
'
blue1 = ''
blue2 = '
'
green1 = ''
green2 = '
'


app = tkApplication_CGI()


#=============================
# Treat argments
#=============================
def usage(app = None):
    print("")
    print("Usage: python {} infile".format(sys.argv[0]))
    print("")

def updatevars():
    global infile

    infile = getarg(1, infile)

def escape(t):
    return (t
        .replace("&", "&")
        .replace("<", "<")
        .replace(">", ">")
        .replace("'", "&#39;")
        .replace('"', """)
        .replace(" ", " ")
        )

def execute():
    global infile

#    debug = True
    debug = False

    app.init_html()

    logfile = app.replace_path(app.script_fullpath, template = ["{dirname}", "{filebody}.log"])
#    print("")
#    print(f"Open logfile [{logfile}]")
    try:
        app.redirect(targets = ["stdout", logfile], mode = 'w')
    except:
        print(f"

Warning: Can not write to log file [{logfile}]

")
        pass

    path = app.getfirst('path', None)
    if path is None:
        path = infile

    if debug:
        print(f"

Show python code from {path}

")

    if path is None:
        print("

Error: The argument path must be given

")
        app.end_html()
        app.terminate()

    str = app.validate_path(path, 'upper_dir|invalid_char|top_dir')
    if str != '':
        print("
")
        print(f"

{str}

")
        app.end_html()
        app.terminate()

    if not path:
        print("

Error: The argument path must be given

")
        app.end_html()
        app.terminate()

    infile = os.path.join(web_root, path)

#    debug = True
    if debug:
        print(f"path: {path}
")
        print(f"infile: {infile}
")

    fmask = re.sub(r'\.[^\.]*?$', '*.*', infile)
    imagefiles = glob.glob(fmask)

    nf = len(imagefiles)
    relatedfiles = []
    for i in range(nf-1, -1, -1):
        if not re.search(r'\.(jpg|jpeg|png)$', imagefiles[i]):
            if not re.search(r'\.(html|py)$', imagefiles[i]):
                relatedfiles.append(imagefiles[i])
            del imagefiles[i]

    if len(imagefiles) == 0:
        imagefiles.append(re.sub(r'\.[^\.]*?$', '.jpg', infile))
    imagefiles.sort()

    if debug:
        print("in file :", infile)
        print("Image files ({}):".format(fmask))
        for f in imagefiles:
            print(" ", f)
        print("Related files ({}):".format(fmask))
        for f in relatedfiles:
            print(" ", f)

    fin = open(infile, 'r', encoding='utf-8')
    lines = fin.readlines()
    fin.close()

    IsComment = False
    title = 'No title'
    title1 = 'No title'
    for i in range(len(lines)):
        line = lines[i]
        line = line.rstrip()
        ret = re.search(r"^(.*?)('''|\"\"\")(.*)$", line)
        if ret:
            title = ''
            for j in range(i+1, len(lines)):
                if re.search(r"('''
|\"\"\")", lines[j]):
                    break
                title += lines[j]
                if j == i+1:
                    title1 = lines[j]

            title = re.sub(r'\n', r'
\n', title.rstrip())
            break

    title1 = title1.strip()
    if debug:
        print("")
        print(f"Title(single line): {title1}
")
        print(f"Title(multi line) : {title}
")


    print("")

    print("")
    print('' + blue1 + title + blue2 + '

')
    infile_url = f"{url_root}{path}"
    dirname, basename, filebody, ext = split_file_path(path)
    print(f'Download script from {blue1}{basename}{blue2}')
    print('
')

    print("Related files:
")
    n = len(web_root)
    for f in relatedfiles:
        dirname, basename, filebody, ext = split_file_path(f)
        f_url = f"{url_root}{f[n+1:]}"
#        print(f"

{f_url}
")
        print(f'{basename}')
        print('
')
    print('
')
    print('')


    for i in range(len(lines)):
        line = lines[i]
        line = line.rstrip()

#    ret = re.search(r"^(\s*)(.*)$", line)
        ret = re.search(r"^(\s*#?\s*)(.*)$", line)
#    ret = re.search(r"^(#?\s*)(.*)$", line)
        if ret:
            spc = ret[1]
            line = ret[2]
            spc = re.sub(r' ', ' ', spc)
        else:
            spc = ''

        spc = re.sub('\t', '    ', spc)

        line = spc + line

        ret = re.search(r"^(.*?)(''')(.*)$", line)
        if ret:
            if not IsComment:
                IsComment = True
                line = ret[1] + '' + ret[2] + ret[3]
            else:
                IsComment = True
                line = ret[1] + ret[2] + '
' + ret[3]

        ret = re.search(r'^(.*?)(""")(.*)$', line)
        if ret:
            if not IsComment:
                IsComment = True
                line = ret[1] + '' + ret[2] + ret[3]
            else:
                IsComment = True
                line = ret[1] + ret[2] + '
' + ret[3]

#    print("line: ", line)
        if re.search(r'^(.*?)(#.*?\?\?\?.*)$', line):
            line = re.sub(r'^(.*?)(#.*?\?\?\?.*)$', r'\1\2', line)
        else:
            line = re.sub(r'^(.*?)(#)(.*)$', r'\1\2\3', line)

        line = re.sub(r'', red1, line)
        line = re.sub(r'
', red2, line)
        line = re.sub(r'', blue1, line)
        line = re.sub(r'
', blue2, line)
#    line = re.sub(r'(https?://\S+)', '$1', line)
        match = re.search(r'((http|ftp)s?://[^\s\"\'\<\>]+)', line)
        if match is not None:
            if debug:
                print("link = ", match[1])
            line = re.sub(r'(https?://[^\s\"\'\<\>]+)', '%s' % (match[1],match[1]), line)

        print(f"{line}
")

    print("
")

    print("")
    print("
")
    n = len(web_root)
    for f in imagefiles:
        dirname, basename, filebody, ext = split_file_path(f)
        f_url = f"{url_root}{f[n+1:]}"
#        print(f"
{f_url}
")

        print(f'\n')
        print('
')


    app.end_html()


def main():
    updatevars()

#    logfile = app.replace_path(outfile, template = ["{dirname}", "{filebody}-out.txt"])
#    print("")
#    print(f"Open logfile [{logfile}]")
#    app.redirect(targets = ["stdout", logfile], mode = 'w')

    execute()

    app.terminate()


if __name__ == "__main__":
    main()