2 回答

TA貢獻1827條經驗 獲得超8個贊
使用brython-runner。您可以在字符串中運行 Python 代碼,并使用自定義回調函數處理標準輸出和錯誤。它使用 Web Worker 中的 Brython 實例運行代碼。
<script src="https://cdn.jsdelivr.net/gh/pythonpad/brython-runner/lib/brython-runner.bundle.js"></script>
<script>
const runner = new BrythonRunner({
? ? stdout: {
? ? ? ? write(content) {
? ? ? ? ? ? // Show output messages here.
? ? ? ? ? ? console.log('StdOut: ' + content);
? ? ? ? },
? ? ? ? flush() {},
? ? },
? ? stderr: {
? ? ? ? write(content) {
? ? ? ? ? ? // Show error messages here.
? ? ? ? ? ? console.error('StdErr: ' + content);
? ? ? ? },
? ? ? ? flush() {},
? ? },
? ? stdin: {
? ? ? ? async readline() {
? ? ? ? ? ? var userInput = prompt();
? ? ? ? ? ? console.log('Received StdIn: ' + userInput);
? ? ? ? ? ? return userInput;
? ? ? ? },
? ? }
});
runner.runCode('print("hello world")');
</script>

TA貢獻1946條經驗 獲得超4個贊
嘗試一下:
<body onload="brython()">
<script type="text/python">
from browser import document, window
import traceback
def run(event):
try:
exec(document['code'].value)
except Exception:
error_message=traceback.format_exc()
document['error_message_textarea'].value=error_message
document['run'].bind('click',run)
</script>
<input id='code' value='print(123+"OK")'></input>
<button id='run'>
RUN
</button>
<br>
<textarea id='error_message_textarea' style='color:red;width: 300px; height: 300px;'></textarea>
</body>
添加回答
舉報