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

如何在PyScript的py-terminal中清除终端内容?

清除PyScript嵌入的Python REPL输出内容

PyScript的网页REPL/终端基于浏览器DOM实现,并非系统原生终端,所以os.system("clear")、print("\033c")这类系统终端命令自然无效。可以通过Python调用JavaScript操作DOM的方式直接清空输出区域,具体方法如下:

针对py-repl组件

from js import document

def clear_repl():
    # 获取py-repl的Shadow DOM内的输出容器
    repl_output = document.querySelector("py-repl").shadowRoot.querySelector(".output")
    # 清空输出内容
    repl_output.innerHTML = ""

# 调用函数执行清除
clear_repl()

针对py-terminal组件

from js import document

def clear_terminal():
    # 获取py-terminal的Shadow DOM内的输出容器
    terminal_output = document.querySelector("py-terminal").shadowRoot.querySelector(".terminal-output")
    terminal_output.innerHTML = ""
    # 可选:清空当前输入框内容
    terminal_input = document.querySelector("py-terminal").shadowRoot.querySelector(".terminal-input")
    terminal_input.value = ""

# 调用函数执行清除
clear_terminal()

注意事项

  • PyScript组件使用Shadow DOM封装,必须通过shadowRoot才能访问内部的输出元素
  • 如果组件类名因版本变更失效,可以通过浏览器开发者工具(F12)查看元素结构,调整选择器内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:40:15