How can I see output from a Brython script on the page? Why doesn't `print` work?
Question:
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 ?
Answers:
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 !")
Add an id=’fish’ whatever for tag and then overwrite it in python:
<body id='fish' onload='brython()'>
and then:
d = document['fish']
d.clear()
d <= "Result: %s" % str(x)
Note that you need to call element .clear() first, <= is the same as Javascript .appendChild(), see the documentation: https://brython.info/static_doc/en/cookbook/content_in_div.html
If you want to see it in proper XHTML page, don’t replace the whole body but just one div-element/tag for example. Or overwrite the whole body with all needed XHTML tags.
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 ?
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 !")
Add an id=’fish’ whatever for tag and then overwrite it in python:
<body id='fish' onload='brython()'>
and then:
d = document['fish']
d.clear()
d <= "Result: %s" % str(x)
Note that you need to call element .clear() first, <= is the same as Javascript .appendChild(), see the documentation: https://brython.info/static_doc/en/cookbook/content_in_div.html
If you want to see it in proper XHTML page, don’t replace the whole body but just one div-element/tag for example. Or overwrite the whole body with all needed XHTML tags.