我有问题.
我需要将 所有 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 元素
发布评论