python在线编译器的简单原理及简单实现代码
作者:superboycxx 时间:2022-01-06 18:40:49
我们先来看一下效果(简单的写了一个):
原理:将post请求的代码数据写入了服务器的一个文件,然后用服务器的python编译器执行返回结果
实现代码:
#flaskrun.py
# -*- coding: utf-8 -*-
# __author__="ZJL"
from flask import Flask
from flask import request
from flask import Response
import json
import zxby
app = Flask(__name__)
def Response_headers(content):
resp = Response(content)
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
@app.route('/')
def hello_world():
return Response_headers('hello world!!!')
@app.route('/run', methods=['POST'])
def run():
if request.method == 'POST' and request.form['code']:
code = request.form['code']
print(code)
jsondata = zxby.main(code)
return Response_headers(str(jsondata))
@app.errorhandler(403)
def page_not_found(error):
content = json.dumps({"error_code": "403"})
resp = Response_headers(content)
return resp
@app.errorhandler(404)
def page_not_found(error):
content = json.dumps({"error_code": "404"})
resp = Response_headers(content)
return resp
@app.errorhandler(400)
def page_not_found(error):
content = json.dumps({"error_code": "400"})
resp = Response_headers(content)
return resp
@app.errorhandler(405)
def page_not_found(error):
content = json.dumps({"error_code": "405"})
resp = Response_headers(content)
return resp
@app.errorhandler(410)
def page_not_found(error):
content = json.dumps({"error_code": "410"})
resp = Response_headers(content)
return resp
@app.errorhandler(500)
def page_not_found(error):
content = json.dumps({"error_code": "500"})
resp = Response_headers(content)
return resp
if __name__ == '__main__':
app.run(debug=True)
#zxby.py
# -*- coding: utf-8 -*-
# __author__="ZJL"
import os, sys, subprocess, tempfile, time
# 创建临时文件夹,返回临时文件夹路径
TempFile = tempfile.mkdtemp(suffix='_test', prefix='python_')
# 文件名
FileNum = int(time.time() * 1000)
# python编译器位置
EXEC = sys.executable
# 获取python版本
def get_version():
v = sys.version_info
version = "python %s.%s" % (v.major, v.minor)
return version
# 获得py文件名
def get_pyname():
global FileNum
return 'test_%d' % FileNum
# 接收代码写入文件
def write_file(pyname, code):
fpath = os.path.join(TempFile, '%s.py' % pyname)
with open(fpath, 'w', encoding='utf-8') as f:
f.write(code)
print('file path: %s' % fpath)
return fpath
# 编码
def decode(s):
try:
return s.decode('utf-8')
except UnicodeDecodeError:
return s.decode('gbk')
# 主执行函数
def main(code):
r = dict()
r["version"] = get_version()
pyname = get_pyname()
fpath = write_file(pyname, code)
try:
# subprocess.check_output 是 父进程等待子进程完成,返回子进程向标准输出的输出结果
# stderr是标准输出的类型
outdata = decode(subprocess.check_output([EXEC, fpath], stderr=subprocess.STDOUT, timeout=5))
except subprocess.CalledProcessError as e:
# e.output是错误信息标准输出
# 错误返回的数据
r["code"] = 'Error'
r["output"] = decode(e.output)
return r
else:
# 成功返回的数据
r['output'] = outdata
r["code"] = "Success"
return r
finally:
# 删除文件(其实不用删除临时文件会自动删除)
try:
os.remove(fpath)
except Exception as e:
exit(1)
if __name__ == '__main__':
code = "print(11);print(22)"
print(main(code))
运行app.run()方法,通过post提交代码,就ok了。我们可以对输出结过做进一步的处理,我这只是为了解一下原理,就没继续了。
来源:http://blog.csdn.net/m0_37499059/article/details/79221990
标签:python,在线编译器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用SQL Server 2000索引视图提高性能
2009-01-13 13:47:00
![](https://img.aspxhome.com/file/UploadPic/20091/200911419338684.gif)
python使用Apriori算法进行关联性解析
2022-08-15 13:02:10
DreamWeaver操作超级技巧大全
2008-10-03 20:50:00
python 教程之blinker 信号库
2023-11-23 10:15:51
Symfony2框架创建项目与模板设置实例详解
2023-11-20 23:36:39
![](https://img.aspxhome.com/file/2023/9/92809_0s.jpg)
Python Web框架Flask信号机制(signals)介绍
2022-12-01 13:52:23
Web标准在中国
2008-11-26 11:27:00
python实现在pandas.DataFrame添加一行
2022-04-14 01:53:23
详解Golang语言HTTP客户端实践
2023-09-17 13:52:07
python多线程之事件Event的使用详解
2022-12-21 11:46:10
php实现比较全的数据库操作类
2023-11-22 02:15:10
python操作mongodb根据_id查询数据的实现方法
2023-04-04 23:12:28
平面设计中的文字设计
2009-01-15 12:09:00
从数据行入手保护SQL Server数据安全
2009-04-13 10:28:00
![](https://img.aspxhome.com/file/UploadPic/20094/2009413132414109.jpg)
python实现网站用户名密码自动登录功能
2021-07-05 09:48:13
关于window.opener的用法
2008-02-23 11:03:00
Python标准库sched模块使用指南
2022-09-20 12:19:06
Go语言的Channel遍历方法详解
2023-09-24 07:50:08
![](https://img.aspxhome.com/file/2023/4/101054_0s.png)
图文详解如何利用PyTorch实现图像识别
2023-02-04 00:54:13
![](https://img.aspxhome.com/file/2023/1/83661_0s.png)
傲游对开发人员的影响越来越大了
2009-10-14 13:16:00