python代码运行助手可以让你在线输入python代码,然后通过本机运行的一个python脚本来执行代码。原理如下:
在网页输入代码:
点击run按钮,代码被发送到本机正在运行的python代码运行助手;
python代码运行助手将代码保存为临时文件,然后调用python解释器执行代码;
网页显示代码执行结果:
下载
点击右键,目标另存为:learning.py
备用下载地址:learning.py
完整代码:
#!/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’learning python
run
‘]
if method == ‘get’ and path == ‘/env’:
start_response(‘200 ok’, [(‘content-type’, ‘text/html’)])
l = [b’env’]
for k, v in environ.items():
p = ‘
%s = %s’ % (k, str(v))
l.append(p.encode(‘utf-8’))
l.append(b”)
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’, [(‘content-type’, ‘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’, [(‘content-type’, ‘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’, [(‘content-type’, ‘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()
运行
在存放learning.py的目录下运行命令:
代码如下:
c:\users\michael\downloads> python learning.py
如果看到ready for python code on port 39093…表示运行成功,不要关闭命令行窗口,最小化放到后台运行即可:
试试效果
需要支持html5的浏览器:
ie >= 9
firefox
chrome
sarafi