Files
pier/pier.py
2022-05-10 10:48:41 +02:00

81 lines
1.7 KiB
Python
Executable File

#!/usr/bin/env python3
from contextlib import redirect_stdout, redirect_stderr
from functools import lru_cache
from glob import glob
from io import StringIO
import http.server
import socketserver
HOST = "localhost"
PORT = 9090
class ScriptServer(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
scr = self.path.strip("/")
if not scr.endswith(".py"):
scr += ".py"
scripts = sorted(glob("*.py"))
if scr not in scripts:
printable_scripts = "\n".join(scripts)
self.send_result(f"{scr} does not exist. choose from:\n", printable_scripts)
return
res = run_script(scr)
msg = f"{scr} output:\n"
msg += "_" * 80
msg += f"\n{res}"
self.send_result(msg)
def send_result(self, *msg):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
msg = encode_html(*msg)
self.wfile.write(msg)
print(msg)
def run_script(fn):
sio = StringIO()
with redirect_stdout(sio), redirect_stderr(sio):
code = open_script(fn)
exec(code)
return sio.getvalue()
@lru_cache()
def open_script(fn):
print("reading", fn)
print("_" * 80)
with open(fn) as f:
src = f.read()
code = compile(src, fn, "exec")
return code
def encode_html(*msg):
msg = (str(i) for i in msg)
msg = " ".join(msg)
msg = msg.split("\n")
msg = "<br>".join(msg)
msg = msg.encode()
return msg
if __name__ == "__main__":
socketserver.TCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer((HOST, PORT), ScriptServer) as httpd:
print(f"serving at {HOST}:{PORT}")
httpd.serve_forever()