亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Brython 創建簡單的 python 代碼運行器

如何使用 Brython 創建簡單的 python 代碼運行器

蝴蝶刀刀 2023-09-12 17:23:18
我正在創建簡單的代碼編輯器,它可以運行 python 代碼并顯示輸出和錯誤消息。目前我可以運行 python 代碼,但問題是輸出顯示在開發人員工具的控制臺中。我想將輸出和錯誤消息獲取到 DOM 元素或作為字符串傳遞到 JS 腳本<script type="text/python">from browser import document, window import tb as tracebackdef run(event):         try:         exec(document['code'].value)     except Exception:        print(traceback.format_exc()) document['run'].bind('click',run)</script>這是我的代碼。'code' 是用于輸入代碼的文本框的 ID。'run' 是運行按鈕的 id。我想將輸出獲取到另一個文本框或作為字符串獲取到我的 js 腳本,而不是顯示在開發人員工具的控制臺中
查看完整描述

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>


查看完整回答
反對 回復 2023-09-12
?
絕地無雙

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>


查看完整回答
反對 回復 2023-09-12
  • 2 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號