Search code examples
pythonhtmltextareastdoutbrython

How can I redirect all Brython output to a textarea element


I have a problem.

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

Here's my HTML-file.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/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>

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

I tried this:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/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>

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'

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.


Solution

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

    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>


    Minimal working example.

    <!DOCTYPE html>
    <html>
        <head>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.8.8/brython.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/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>