gpt4 book ai didi

javascript - 如何使用 Skulpt 逐行评估 Python

转载 作者:行者123 更新时间:2023-12-03 09:36:33 27 4
gpt4 key购买 nike

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
}

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

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

关于javascript - 如何使用 Skulpt 逐行评估 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com