如何使用Skulpt逐行评估Python

时间:2015-07-09 13:09:13

标签: javascript python interpreter skulpt

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

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

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

提前谢谢。

1 个答案:

答案 0 :(得分: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运行每一行(根据需要突出显示此行)
  3. 第二个链接中稍微修改过的代码:

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