From 4332e67fdc6aac0ba08379e3526c798454bf6fe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Fri, 20 Nov 2020 15:18:04 +0100 Subject: highlight traceback with pygments if available Install pygments via pip if you want to use the highlighter. --- lib.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) (limited to 'lib.py') diff --git a/lib.py b/lib.py index e95265f..2ceb51d 100644 --- a/lib.py +++ b/lib.py @@ -4,10 +4,28 @@ import sys import traceback from http.server import HTTPServer, BaseHTTPRequestHandler +try: + from pygments import highlight + from pygments.lexers import PythonLexer + from pygments.formatters import HtmlFormatter + have_pygment = True +except ModuleNotFoundError: + have_pygment = False + posts = {} gets = {} +def format_py(code): + if have_pygment: + formatter = HtmlFormatter() + formatter.noclasses = True # inline styles + return highlight(code, PythonLexer(), formatter) + else: + return "{}".format(code).replace("\n", "\n
") \ + .replace(" ", " ") + + def find_get(path): """ [Internal] - Used by the Handler class to try and find the correct handler for a GET request. @@ -19,8 +37,7 @@ def find_get(path): except Exception: tb = traceback.format_exc() print(tb, file=sys.stderr) - return 500, "\n{}\n".format(tb.replace("\n", "
\n") - .replace(" ", " ")) + return 500, format_py(tb) def find_post(path, request): @@ -34,7 +51,7 @@ def find_post(path, request): except Exception: tb = traceback.format_exc() print(tb, file=sys.stderr) - return 500, f"{tb}" + return 500, "" def get_relative_path(): @@ -59,7 +76,7 @@ def read_html(relative_file_path): def inject_external_files(html_content): """ [Internal] - Replaces {{ 'file_path' }} with the file content of that file - path. Useful for seperation of javascript and css files. + pat. Useful for seperation of javascript and css files. Uses regex to capture the pattern. Here is a link to see how it works: https://regex101.com/r/v917NK/2 """ -- cgit v1.2.1