handle scripts with arguments
This commit is contained in:
22
pier.py
22
pier.py
@ -25,14 +25,20 @@ from glob import glob
|
||||
from io import StringIO
|
||||
|
||||
import os
|
||||
import sys
|
||||
import http.server
|
||||
import socketserver
|
||||
|
||||
|
||||
HTML_SPACE = "%20"
|
||||
|
||||
|
||||
class ScriptServer(http.server.SimpleHTTPRequestHandler):
|
||||
|
||||
def do_GET(self):
|
||||
scr = self.path.strip("/")
|
||||
args = self.path.lstrip("/").split(HTML_SPACE)
|
||||
scr = args[0]
|
||||
|
||||
if not scr.endswith(".py"):
|
||||
scr += ".py"
|
||||
|
||||
@ -42,7 +48,7 @@ class ScriptServer(http.server.SimpleHTTPRequestHandler):
|
||||
self.send_result(f"{scr} does not exist. choose from:\n", printable_scripts)
|
||||
return
|
||||
|
||||
res = run_script(scr)
|
||||
res = run_script(scr, args)
|
||||
|
||||
msg = f"{scr} output:\n"
|
||||
msg += "_" * 80
|
||||
@ -60,11 +66,19 @@ class ScriptServer(http.server.SimpleHTTPRequestHandler):
|
||||
|
||||
|
||||
|
||||
def run_script(fn):
|
||||
def run_script(fn, args):
|
||||
sio = StringIO()
|
||||
with redirect_stdout(sio), redirect_stderr(sio):
|
||||
code = open_script(fn)
|
||||
exec(code)
|
||||
old_sys_argv, sys.argv = sys.argv, args
|
||||
try:
|
||||
exec(code)
|
||||
except BaseException as e: # need to catch SystemExit etc. as well
|
||||
print("_" * 80)
|
||||
tn = type(e).__name__
|
||||
msg = f"{tn}: {e}"
|
||||
print(msg, file=sys.stderr)
|
||||
sys.argv = old_sys_argv
|
||||
return sio.getvalue()
|
||||
|
||||
@lru_cache()
|
||||
|
Reference in New Issue
Block a user