加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python代码运行助手

发布时间:2020-12-17 17:29:26 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #!/usr/bin/env python3# -*- coding: utf-8 -*- r'''learning.py A Python 3 tutorial from http://www.liaoxuefeng.com Usage: python3 learning.py

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#!/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'<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>']
    if method == 'GET' and path == '/env':
        start_response('200 OK','text/html')])
        L = [b'<html><head><title>ENV</title></head><body>']
        for k,v in environ.items():
            p = '<p>%s = %s' % (k,str(v))
            L.append(p.encode('utf-8'))
        L.append(b'</html>')
        return L
    if host != HOST or method != 'POST' or path != '/run' or not environ.get('CONTENT_TYPE','').lower().startswith('application/x-www-form-urlencoded'):
        start_response('400 Bad Request','application/json')])
        return [b'{"error":"bad_request"}']
    s = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
    qs = parse.parse_qs(s.decode('utf-8'))
    if not 'code' in qs:
        start_response('400 Bad Request','application/json')])
        return [b'{"error":"invalid_params"}']
    name = qs['name'][0] if 'name' in qs else get_name()
    code = qs['code'][0]
    headers = [('Content-Type','application/json')]
    origin = environ.get('HTTP_ORIGIN','')
    if origin.find('.liaoxuefeng.com') == -1:
        start_response('400 Bad Request','application/json')])
        return [b'{"error":"invalid_origin"}']
    headers.append(('Access-Control-Allow-Origin',origin))
    start_response('200 OK',headers)
    r = dict()
    try:
        fpath = write_py(name,code)
        print('Execute: %s %s' % (EXEC,fpath))
        r['output'] = decode(subprocess.check_output([EXEC,fpath],stderr=subprocess.STDOUT,timeout=5))
    except subprocess.CalledProcessError as e:
        r = dict(error='Exception',output=decode(e.output))
    except subprocess.TimeoutExpired as e:
        r = dict(error='Timeout',output='执行超时')
    except subprocess.CalledProcessError as e:
        r = dict(error='Error',output='执行错误')
    print('Execute done.')
    return [json.dumps(r).encode('utf-8')]
 
if __name__ == '__main__':
    main()

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读