0%

代码在线运行工具

使用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
});
//自动换行,设置为off关闭
editor.setOption("wrap", "free");
//首次运行
$(document).ready(function () {
//获取cookie
var cookieCode = getCookie("code");
runCode(editor.getValue(), lan);
//将光标移至末尾
editor.navigateFileEnd();
//监听Ctrl+S命令
editor.commands.addCommand({
name: 'save',
bindKey: { win: 'Ctrl-S', mac: 'Command-S' },
exec: function (editor) {
download('phponline.php', editor.getValue());
},
readOnly: false // 如果不需要使用只读模式,这里设置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)