简体   繁体   English

如何使用Skulpt逐行评估Python

[英]How to use Skulpt to eval Python line by line

The example given by Skulpt runs the interpreter on the whole string containing the python program: Skulpt给出的示例在包含python程序的整个字符串上运行解释器:

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

Is there a possibility to run the interpreter line by line, for example in order to highlight the Python line which is currently executed? 是否有可能逐行运行解释器,例如为了突出显示当前执行的Python行?

Thank you in advance. 先感谢您。

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
}

Essentially you just want to do something like this: 本质上,您只想执行以下操作:

  1. Split the full program into a series of lines 将完整程序分为一系列行
  2. Run each line through Skulpt individually (highlight this line as needed) 通过Skulpt单独运行每一行(根据需要突出显示此行)

Slightly modified code from your second link: 在第二个链接中稍作修改的代码:

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

Then just insert this code wherever you want 然后只要在任何地方插入此代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM