如何将所有 Brython 输出重定向到 textarea 元素

编程入门 行业动态 更新时间:2024-10-23 22:21:57
本文介绍了如何将所有 Brython 输出重定向到 textarea 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有问题.

我需要将 所有 Brython 输出重定向到 元素.

I need to redirect all Brython output to a <textarea> element.

这是我的 HTML 文件.

Here's my HTML-file.

<!DOCTYPE html> <html> <head> <script src="cdnjs.cloudflare/ajax/libs/brython/3.8.8/brython.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/brython/3.8.8/brython_stdlib.js"></script> </head> <body onload="brython(1)"> <textarea id="console"></textarea> <script type="text/python3"> print('test') </script> </body> </html>

我知道默认情况下,Brython 中的所有输出(sys.stdout 和 sys.stderr)都会进入控制台.

I know that by default, all output (sys.stdout and sys.stderr) in Brython goes to the console.

我试过了:

<!DOCTYPE html> <html> <head> <script src="cdnjs.cloudflare/ajax/libs/brython/3.8.8/brython.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/brython/3.8.8/brython_stdlib.js"></script> </head> <body onload="brython(1)"> <textarea id="console"></textarea> <script type="text/python3"> from browser import document import sys sys.stdout = document['console'] </script> <script type="text/python3"> print('test') </script> </body> </html>

但它给了我一个 AttributeError.

But it gives me an AttributeError.

Traceback (most recent call last): module __main__2 line 1 print('test') AttributeError: 'TEXTAREA' object has no attribute 'write'

我需要使用print(),因为用户会输入code,code的结果会打印到.

I need to use print(), because the user will enter the code, and the code's result will be printed to <textarea>.

我试图搜索示例,但没有找到.

I tried to search for examples, but I did not found any.

推荐答案

原始 sys.stdout 有方法 write() 和 print()> 使用 sys.stdout.write() 将文本发送到控制台.

Original sys.stdout has method write() and print() uses sys.stdout.write() to send text to console.

您必须创建具有方法 write() 的类,并将此类分配给 sys.stdout.而你的 write() 可以将文本放入

You have to create class which also has method write() and assign this class to sys.stdout. And your write() can put text in <textarea>

最小的工作示例.

<!DOCTYPE html> <html> <head> <script src="cdnjs.cloudflare/ajax/libs/brython/3.8.8/brython.min.js"></script> <script src="cdnjs.cloudflare/ajax/libs/brython/3.8.8/brython_stdlib.js"></script> </head> <body onload="brython(1)"> <textarea id="console"></textarea> <script type="text/python3"> import sys from browser import document class MyOutput: def __init__(self): self.console = document["console"] def write(self, text): self.console.text += text sys.stdout = MyOutput() print("Hello World 1") print("Hello World 2") </script> </body> </html>

更多推荐

如何将所有 Brython 输出重定向到 textarea 元素

本文发布于:2023-07-06 07:33:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   重定向   元素   Brython   textarea

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!