Search code examples
pythonbrython

How can I see output from a Brython script on the page? Why doesn't `print` work?


I try to use Brython. I have a Python script (test.py) and I would like to display the result of this script in the browser.

I have tried :

<html>
<head>
<script src="brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python" src="test.py"></script>
</body>
</html>

and my script is :

x = int(input("Value: "))
x = pow(x,2)
print("Result: " + str(x))

Unfortunately, I cannot display the result in the browser. Is there something missing ?


Solution

  • In Brython, print displays in the browser console.

    If you want to write the result in the HTML document:

    from browser import document
    
    x = int(input("Value: "))
    x = pow(x, 2)
    
    document <= "Result: " + str(x)
    

    [edit] Another option is to set sys.stdout to an object with a write() method, for instance document in module browser :

    from browser import document
    import sys
    
    sys.stdout = document
    print("Hello", "world !")