0

Skulpt给出的示例在包含 python 程序的整个字符串上运行解释器:

https://github.com/skulpt/skulpt/blob/master/example/calling_from_js.html

是否有可能逐行运行解释器,例如为了突出显示当前执行的 Python 行?

先感谢您。

4

1 回答 1

1
var program = "print('something')\nprint('something else')";

var programs = program.split("\n");

for(var i = 0; i<programs.length; i++){
    //skulpt on `programs[i]` and highlight that line
}

本质上你只想做这样的事情:

  1. 将整个程序拆分为一系列行
  2. 通过 Skulpt 单独运行每一行(根据需要突出显示此行)

从您的第二个链接略微修改的代码:

<script src="../dist/skulpt.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function outf(text)
    {
        var output = document.getElementById("output");
        text = text.replace(/</g, '&lt;');
        output.innerHTML = output.innerHTML + text;
    }
    function runit(prog)
    {
        //changed this so the function accepts an argument
        var output = document.getElementById("output");
        output.innerHTML = '';
        Sk.configure({output:outf});
        try {
            var module = Sk.importMainWithBody("<stdin>", false, prog);
            var obj = module.tp$getattr('a');
            var runMethod = obj.tp$getattr('run');
            var ret = Sk.misceval.callsim(runMethod, 10);
            alert(ret.v);
        } catch (e) {
            alert(e);
        }
    }
</script>
<form>
<textarea id="code" rows="24" cols="80">
class Test:
     def run(self, b):
         self.a = 10 + b
         return self.a

print "Hello World"
a = Test()
</textarea><br>
<button onclick="runit()" type="button">Run</button>
</form>

<pre id="output"></pre>

然后只需将此代码插入您想要的任何位置

var programs = document.getElementById("code").value;

for(var i = 0; i<programs.length; i++){
    // Whatever code you want to use to highlight the line goes here
    runit(programs[i]);
}
于 2015-07-09T13:42:04.070 回答