网站推广.NET

网站推广.NET

Python代码运行助手

来源:互联网

#!/usr/bin/env python3# -*- coding: utf-8 -*-  r&#39;&#39;&#39;learning.py  A Python 3 tutorial from http://www.liaoxuefeng.com  Usage:  python3 learning.py&#39;&#39;&#39;  import sys  def check_version():    v = sys.version_info    if v.major == 3 and v.minor >= 4:        return True    print(&#39;Your current python is %d.%d. Please use Python 3.4.&#39; % (v.major, v.minor))    return False  if not check_version():    exit(1)  import os, io, json, subprocess, tempfilefrom urllib import parsefrom wsgiref.simple_server import make_server  exec = sys.executablePORT = 39093HOST = &#39;local.liaoxuefeng.com:%d&#39; % PORTTEMP = tempfile.mkdtemp(suffix=&#39;_py&#39;, prefix=&#39;learn_python_&#39;)INDEX = 0  def main():    httpd = make_server(&#39;127.0.0.1&#39;, PORT, application)    print(&#39;Ready for Python code on port %d...&#39; % PORT)    httpd.serve_forever()  def get_name():    global INDEX    INDEX = INDEX + 1    return &#39;test_%d&#39; % INDEX  def write_py(name, code):    fpath = os.path.join(TEMP, &#39;%s.py&#39; % name)    with open(fpath, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:        f.write(code)    print(&#39;Code wrote to: %s&#39; % fpath)    return fpath  def decode(s):    try:        return s.decode(&#39;utf-8&#39;)    except UnicodeDecodeError:        return s.decode(&#39;gbk&#39;)  def application(environ, start_response):    host = environ.get(&#39;HTTP_HOST&#39;)    method = environ.get(&#39;REQUEST_METHOD&#39;)    path = environ.get(&#39;PATH_INFO&#39;)    if method == &#39;GET&#39; and path == &#39;/&#39;:        start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/html&#39;)])        return [b&#39;<html><head><title>Learning Python</title></head><body><form method="post" action="/run"><textarea name="code" style="width:90%;height: 600px"></textarea><p><button type="submit">run</button></p></form></body></html>&#39;]    if method == &#39;GET&#39; and path == &#39;/env&#39;:        start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/html&#39;)])        L = [b&#39;<html><head><title>ENV</title></head><body>&#39;]        for k, v in environ.items():            p = &#39;<p>%s = %s&#39; % (k, str(v))            L.append(p.encode(&#39;utf-8&#39;))        L.append(b&#39;</html>&#39;)        return L    if host != HOST or method != &#39;POST&#39; or path != &#39;/run&#39; or not environ.get(&#39;CONTENT_TYPE&#39;, &#39;&#39;).lower().startswith(&#39;application/x-www-form-urlencoded&#39;):        start_response(&#39;400 Bad Request&#39;, [(&#39;Content-Type&#39;, &#39;application/json&#39;)])        return [b&#39;{"error":"bad_request"}&#39;]    s = environ[&#39;wsgi.input&#39;].read(int(environ[&#39;CONTENT_LENGTH&#39;]))    qs = parse.parse_qs(s.decode(&#39;utf-8&#39;))    if not &#39;code&#39; in qs:        start_response(&#39;400 Bad Request&#39;, [(&#39;Content-Type&#39;, &#39;application/json&#39;)])        return [b&#39;{"error":"invalid_params"}&#39;]    name = qs[&#39;name&#39;][0] if &#39;name&#39; in qs else get_name()    code = qs[&#39;code&#39;][0]    headers = [(&#39;Content-Type&#39;, &#39;application/json&#39;)]    origin = environ.get(&#39;HTTP_ORIGIN&#39;, &#39;&#39;)    if origin.find(&#39;.liaoxuefeng.com&#39;) == -1:        start_response(&#39;400 Bad Request&#39;, [(&#39;Content-Type&#39;, &#39;application/json&#39;)])        return [b&#39;{"error":"invalid_origin"}&#39;]    headers.append((&#39;Access-Control-Allow-Origin&#39;, origin))    start_response(&#39;200 OK&#39;, headers)    r = dict()    try:        fpath = write_py(name, code)        print(&#39;Execute: %s %s&#39; % (exec, fpath))        r[&#39;output&#39;] = decode(subprocess.check_output([exec, fpath], stderr=subprocess.STDOUT, timeout=5))    except subprocess.CalledProcessError as e:        r = dict(error=&#39;Exception&#39;, output=decode(e.output))    except subprocess.TimeoutExpired as e:        r = dict(error=&#39;Timeout&#39;, output=&#39;执行超时&#39;)    except subprocess.CalledProcessError as e:        r = dict(error=&#39;Error&#39;, output=&#39;执行错误&#39;)    print(&#39;Execute done.&#39;)    return [json.dumps(r).encode(&#39;utf-8&#39;)]  if __name__ == &#39;__main__&#39;:    main()

python代码运行助手