如何自定义Py-Script <py-repl>交互环境的输出展示,仅保留最新运行会话的全部输出
Got it, let's tackle this issue where your <py-repl> keeps retaining all historical output instead of just the latest run's results. The problem with your CSS approach makes total sense—when you run code with multiple print statements, each one generates a new <div> in your output container, and :nth-last-child() only grabs the very last of those, not all from the current session.
Here's a reliable solution that clears old output before each new run, so you only see results from the latest session:
Step-by-Step Solution
We'll use a bit of JavaScript to hook into the REPL's "run" action and clear the output container right before code executes.
- Add this script to your page (either in a
<script>tag at the end of your<body>or an external JS file):
document.addEventListener('DOMContentLoaded', () => { // Grab references to your REPL and output container const myRepl = document.getElementById('my-repl'); const outputDiv = document.getElementById('output'); // Locate the auto-generated "Start" button in the REPL const runButton = myRepl.querySelector('.py-repl__run-button'); // Attach a click handler to clear output before running code runButton.addEventListener('click', () => { outputDiv.innerHTML = ''; }); });
How This Works
- When the page loads, we find your REPL element and its associated output container.
- We target the built-in "Start" button that Py-Script generates for the REPL.
- Every time you click "Start" to run code, the script first wipes out all existing content in the output container. Then, when your code executes, all new
printoutputs are added to a fresh, empty container—so you'll see all results from the current run, and none from previous ones.
Why This Beats the CSS Approach
Unlike the CSS method which only hides all but the last single output element, this solution fully clears old output before each run. That means if your code has 5 print statements, all 5 will appear in the output, and they'll replace whatever was there from the last time you ran code.
内容的提问来源于stack exchange,提问作者chillingfox

