Skulpt给出的示例在包含python程序的整个字符串上运行解释器:
https://github.com/skulpt/skulpt/blob/master/example/calling_from_js.html
是否有可能逐行运行解释器,例如为了突出显示当前执行的Python行?
先感谢您。
最佳答案
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
}
本质上,您只想执行以下操作:
将完整程序分为一系列行
通过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, '<');
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]);
}