>백엔드 개발 >파이썬 튜토리얼 >Python 코드 실행 도우미

Python 코드 실행 도우미

大家讲道理
大家讲道理원래의
2016-11-09 11:19:302238검색

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
  
r'''
learning.py
  
A Python 3 tutorial from http://www.liaoxuefeng.com
  
Usage:
  
python3 learning.py
'''
  
import sys
  
def check_version():
    v = sys.version_info
    if v.major == 3 and v.minor >= 4:
        return True
    print('Your current python is %d.%d. Please use Python 3.4.' % (v.major, v.minor))
    return False
  
if not check_version():
    exit(1)
  
import os, io, json, subprocess, tempfile
from urllib import parse
from wsgiref.simple_server import make_server
  
EXEC = sys.executable
PORT = 39093
HOST = 'local.liaoxuefeng.com:%d' % PORT
TEMP = tempfile.mkdtemp(suffix='_py', prefix='learn_python_')
INDEX = 0
  
def main():
    httpd = make_server('127.0.0.1', PORT, application)
    print('Ready for Python code on port %d...' % PORT)
    httpd.serve_forever()
  
def get_name():
    global INDEX
    INDEX = INDEX + 1
    return 'test_%d' % INDEX
  
def write_py(name, code):
    fpath = os.path.join(TEMP, '%s.py' % name)
    with open(fpath, 'w', encoding='utf-8') as f:
        f.write(code)
    print('Code wrote to: %s' % fpath)
    return fpath
  
def decode(s):
    try:
        return s.decode('utf-8')
    except UnicodeDecodeError:
        return s.decode('gbk')
  
def application(environ, start_response):
    host = environ.get('HTTP_HOST')
    method = environ.get('REQUEST_METHOD')
    path = environ.get('PATH_INFO')
    if method == 'GET' and path == '/':
        start_response('200 OK', [('Content-Type', 'text/html')])
        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()

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.