codemirror与实现c++/c在线编译器

codemirror

下载
codemirror js版

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})

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值