使用ace js和flask 搭建在线代码运行平台,目前需要服务端 有对应开发语言的环境
代码运行工具
ACE 是一个实现了语法着色功能的基于 Web 的代码编辑器,支持的语言包括: PHP JAVA PYTHON GO 等多种语言
ace使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <xmp id="editor"><?php $str = 'World'; echo "Hello $str\n"; echo date('Y-m-d H:i:s').PHP_EOL; echo "PHP版本:".phpversion(); ?></xmp> <textarea class="result" id="result" disabled></textarea> <script src="src/ace.js" type="text/javascript"></script> <script src="src/ext-language_tools.js" type="text/javascript"></script>
<script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.session.setMode("ace/mode/php"); editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true }); editor.setOption("wrap", "free"); $(document).ready(function () { var cookieCode = getCookie("code"); runCode(editor.getValue(), lan); editor.navigateFileEnd(); editor.commands.addCommand({ name: 'save', bindKey: { win: 'Ctrl-S', mac: 'Command-S' }, exec: function (editor) { download('phponline.php', editor.getValue()); }, readOnly: false }); }); </script>
|
后端利用python flask框架作为服务端, 接受前端传的代码和语言 执行后返回前端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| from flask import Flask; from flask import request import subprocess
app=Flask(__name__) @app.route('/api/exec', methods=['GET','POST']) def api_exec(): lan = request.args.get("lan") code = request.form.get("code") if lan == "python": filename = "exec.py" else: filename = "exec.%s" %(lan) write_file(filename, code) if lan == "go": filename = "run %s" %(filename) p = subprocess.Popen("%s %s" %(lan, filename), shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8") results = p.communicate()[0] if not results: results = p.communicate()[1] return results
def write_file(filename, code): fo = open(filename, "w") fo.write(code) fo.close()
if __name__ == '__main__': app.run(debug=True,host='127.0.0.1',port=82)
|