使用CodeMirror實現Python3線上編輯器

weixin_34253539發表於2019-01-13

一、編寫頁面

主要是引入相關的css檔案和js檔案,這裡採用簡單插入link和script標籤的形式。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="codemirror/lib/codemirror.css">
    <link rel="stylesheet" href="codemirror/addon/fold/foldgutter.css">
    <link rel="stylesheet" href="codemirror/addon/hint/show-hint.css">
    <link rel="stylesheet" href="codemirror/addon/lint/lint.css">
    <link rel="stylesheet" href="leetcode.css">  
</head>
<body>
    <form action="">
        <textarea id="editor" class="editor"></textarea>
    </form>   
    <button id="test">click</button>
</body>
</html>
<script src="codemirror/lib/codemirror.js"></script>

<script src="codemirror/addon/comment/comment.js"></script>

<script src="codemirror/addon/selection/active-line.js"></script>

<script src="codemirror/keymap/sublime.js"></script>

<script src="codemirror/addon/hint/show-hint.js"></script>
<script src="codemirror/mode/python/python.js"></script> 

<script src="codemirror/addon/fold/foldcode.js"></script>
<script src="codemirror/addon/fold/foldgutter.js"></script>
<script src="codemirror/addon/fold/brace-fold.js"></script>
<script src="codemirror/addon/fold/indent-fold.js"></script>
<script src="codemirror/addon/fold/comment-fold.js"></script>

<script src="codemirror/addon/edit/closebrackets.js"></script>
<script src="codemirror/addon/edit/matchbrackets.js"></script>

<script src="axios.js"></script>

<script src="index.js"></script>

二、配置CodeMirror

在index.js中配置CodeMirror

window.onload = function () {
    var el = document.getElementById("editor");
    var version = "# version: Python3\n\n";
    var codeAreaTip = "# please edit your code here:\n";
    var codeStart = "# code start\n\n";
    var codeEnd = "# code end\n\n";
    var codeTip = "'''\nThis function is the entry of this program and\nit must be return your answer of current question.\n'''\n";
    var code = "def solution():\n\tpass";
    var initValue = version + codeAreaTip + codeStart + codeEnd + codeTip + code;
    var myCodeMirror = CodeMirror.fromTextArea(el, {
        mode: "python", // 語言模式
        theme: "leetcode", // 主題
        keyMap: "sublime", // 快鍵鍵風格
        lineNumbers: true, // 顯示行號
        smartIndent: true, // 智慧縮排
        indentUnit: 4, // 智慧縮排單位為4個空格長度
        indentWithTabs: true, // 使用製表符進行智慧縮排
        lineWrapping: true, // 
        // 在行槽中新增行號顯示器、摺疊器、語法檢測器
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"], 
        foldGutter: true, // 啟用行槽中的程式碼摺疊
        autofocus: true, // 自動聚焦
        matchBrackets: true, // 匹配結束符號,比如"]、}"
        autoCloseBrackets: true, // 自動閉合符號
        styleActiveLine: true, // 顯示選中行的樣式
    });
    // 設定初始文字,這個選項也可以在fromTextArea中配置
    myCodeMirror.setOption("value", initValue);
    // 編輯器按鍵監聽
    myCodeMirror.on("keypress", function() {
        // 顯示智慧提示
        myCodeMirror.showHint(); // 注意,註釋了CodeMirror庫中show-hint.js第131行的程式碼(阻止了程式碼補全,同時提供智慧提示)
    });
    var test = document.getElementById("test");
    test.onclick = function() {
        var value = myCodeMirror.getValue();
        axios.post("http://localhost/api/runcode", {
            code: value
        }).then(function(res) {
            console.log(res);
        });
    };
};

三、後臺呼叫python shell

過程如下:

  1. 在接收的程式碼字串後面新增print(solution())用於列印結果
  2. 將第一步處理後的字串寫入一個檔案中這裡是code/code.py
  3. 使用child_process模組的exec方法呼叫shell執行python code/code.py命令,獲取列印結果
const express = require("express");
const { exec } = require("child_process");
const router = express.Router();
router.post("/api/runcode", (req, res) => {
    let code = req.body.code;
    fs.writeFile("code/code.py", code+"\nprint(solution())", (err) => {
        let command = "python code/code.py";
        exec(command, (err, stdout, stdin) => {
            if(err){
                let reg  = /[\d\D]*(line\s\d)[\d\D]*?(\w*(?:Error|Exception).*)/im;
                let matchArr = reg.exec(err.message);
                matchArr.shift();
                res.send(matchArr.join(", "));
            }
            else
                res.send(stdout);
        });
    });
});

效果:
圖片描述

相關文章