You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在Skulpt中用textarea替代alert box实现Python input()输入?

解决Skulpt中用textarea替代alert作为input()输入载体的问题

我之前也踩过这个坑!旧示例失效大概率是因为Skulpt的API更新了,现在得用异步Promise的方式重写input函数才行。下面是我亲测有效的完整实现方案:

第一步:准备HTML结构

先在页面里放好代码编辑区、输入用的textarea和输出展示区域:

<!-- Python代码编辑区 -->
<textarea id="codeArea" rows="10" placeholder="输入你的Python代码...">
# 测试代码
name = input("请输入你的名字: ")
print(f"你好, {name}!")
age = input("请输入你的年龄: ")
print(f"明年你就{int(age)+1}岁啦!")
</textarea>

<!-- 用户输入区域 -->
<textarea id="inputArea" rows="2" placeholder="在这里输入内容,按回车提交"></textarea>

<!-- 输出展示区域 -->
<div id="output" style="margin-top:10px; padding:10px; border:1px solid #ccc;"></div>

<!-- 运行按钮 -->
<button onclick="runPython()" style="margin-top:10px;">运行代码</button>

第二步:重写Skulpt的input逻辑

关键是用Promise处理异步输入,让Skulpt等待用户完成输入后再继续执行。直接看JavaScript代码:

function runPython() {
  const code = document.getElementById("codeArea").value;
  const outputElem = document.getElementById("output");
  const inputElem = document.getElementById("inputArea");

  // 清空之前的输出内容
  outputElem.innerHTML = '';

  // 配置Skulpt核心参数
  Sk.configure({
    // 处理Python的print输出,追加到展示区
    output: function(text) {
      outputElem.innerHTML += text + '<br>';
    },
    // 重写input函数,替换默认alert弹窗
    input: function(promptText) {
      // 把输入提示打印到输出区,提示用户输入
      outputElem.innerHTML += promptText;
      
      // 返回Promise,让Skulpt暂停执行直到用户提交输入
      return new Promise((resolve) => {
        // 监听回车事件提交输入
        function handleSubmit(e) {
          if (e.key === 'Enter') {
            e.preventDefault(); // 阻止textarea默认换行
            const inputValue = inputElem.value.trim();
            inputElem.value = ''; // 清空输入框
            inputElem.removeEventListener('keydown', handleSubmit);
            resolve(inputValue); // 把输入值传递给Skulpt继续执行
          }
        }

        inputElem.addEventListener('keydown', handleSubmit);
        inputElem.focus(); // 自动聚焦到输入框,提升用户体验
      });
    },
    // 处理文件读取(默认实现即可)
    read: function(file) {
      if (file === 'stdin') return '';
      return Sk.read(file);
    }
  });

  // 异步执行Python代码,处理可能的错误
  Sk.misceval.asyncToPromise(() => {
    return Sk.importMainWithBody("<stdin>", false, code, true);
  }).catch((error) => {
    outputElem.innerHTML += `<span style="color:red;">错误: ${error.toString()}</span>`;
  });
}

关键注意点

  • Skulpt版本要求:确保你使用的是v0.11.0及以上的版本,旧版本不支持Promise-based的input处理,这也是旧示例失效的核心原因。
  • 多次input调用支持:上面的代码可以处理连续多次input()调用,每次输入后会自动解绑事件,下次调用input时重新绑定。
  • 用户体验优化:可以根据需求给inputArea添加样式,或者在输入时增加视觉提示,让用户更清晰地知道何时需要输入内容。

内容的提问来源于stack exchange,提问作者Stacked Flowrider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:07:41