如何使用 Brython 创建简单的 python 代码运行器

我正在创建简单的代码编辑器,它可以运行 python 代码并显示输出和错误消息。目前我可以运行 python 代码,但问题是输出显示在开发人员工具的控制台中。我想将输出和错误消息获取到 DOM 元素或作为字符串传递到 JS 脚本


<script type="text/python">

from browser import document, window 

import tb as traceback


def run(event): 

    

    try: 

        exec(document['code'].value) 

    except Exception:

        print(traceback.format_exc()) 


document['run'].bind('click',run)


</script>

这是我的代码。'code' 是用于输入代码的文本框的 ID。'run' 是运行按钮的 id。我想将输出获取到另一个文本框或作为字符串获取到我的 js 脚本,而不是显示在开发人员工具的控制台中


蝴蝶刀刀
浏览 105回答 2
2回答

斯蒂芬大帝

使用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>

绝地无双

尝试一下:<body onload="brython()"><script type="text/python">from browser import document, window&nbsp;import tracebackdef run(event):&nbsp;&nbsp; &nbsp; try:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; exec(document['code'].value)&nbsp;&nbsp; &nbsp; except Exception:&nbsp; &nbsp; &nbsp; &nbsp; error_message=traceback.format_exc()&nbsp; &nbsp; &nbsp; &nbsp; document['error_message_textarea'].value=error_messagedocument['run'].bind('click',run)</script><input id='code' value='print(123+"OK")'></input><button id='run'>&nbsp; &nbsp; RUN</button><br><textarea id='error_message_textarea' style='color:red;width: 300px; height: 300px;'></textarea></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python