codemirror
demo:
所需文件
//需要codemirror.css , anbiance.css (这里的和下载后的文件位置不一样)
<link href="../../../css/plugins/codemirror/codemirror.css" rel="stylesheet">
<link href="../../../css/plugins/codemirror/ambiance.css" rel="stylesheet">
//
<script src="../../../js/plugins/codemirror/mode/javascript.js"></script>
// 实现c++所需的js文件 clike.js
<script src="../../../js/plugins/codemirror/mode/clike.js"></script>
初始化代码框
<textarea id="code1" style="display: none;"></textarea>
更多设置看:
语言(c++/python…)的设置:
https://codemirror.net/5/mode/
config的设置:
https://codemirror.net/5/doc/manual.html#config
//设置config
var editor_one;
$(document).ready(function () {
editor_one = CodeMirror.fromTextArea(document.getElementById("code1"), {
lineNumbers: true, //行号
matchBrackets: true,
styleActiveLine: true,
theme: "ambiance",
mode: "text/x-c++src"
});
editor_one.setValue()
});
简单样式如下:
c编译的实现
需要gcc/g++环境变量:
mingw64下载:离线包下载解压即可添加到环境变量https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/
提交函数
async function submit(e){
var code = editor_one.getValue();
const response = await fetch('/run', {
method: 'POST',
body: code
});
const result = await response.json();
if (result.code === 200) {
console.log(result.data.res)
}else{
alert("网络错误");
}
}
服务器:
@router.post("/run",tags=["程序运行"])
async def run_code(request:Request,code:Optional[str] = Body(...)):
content = code
with open("./test.cpp", 'w', encoding='utf-8') as f:
f.write(content)
cmd_order = 'g++ test.cpp -o test.out && test.out'
# 注意环境变量env(gcc的环境变量/路径)根据自己的添加。
cmd_p = subprocess.Popen(cmd_order, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env={"Path": "D:\\devc++64位\\MinGW64\\bin"})
# 向输入添加数据
cmd_p.stdin.write(b'1 2\n')
cmd_p.stdin.close()
cmd_result = ""
# 读取输出
cmd_result += cmd_p.stdout.read().decode()
# 读取错误信息
cmd_result += cmd_p.stderr.read().decode()
print(cmd_result)
return success(msg="😄",data={"res":cmd_result})