2

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 ?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Peter Estiven
  • 414
  • 1
  • 7
  • 16

2 Answers2

3

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 !")
marqueemoon
  • 376
  • 2
  • 5
  • It works, thanks. But, if I want to display everything in the HTML document whatever the code, is there a way to do it ? – Peter Estiven Oct 08 '17 at 04:12
  • If the question is how to display with the `print()` function, like in standard Python, you can redirect `sys.stdout` to an object with a `write` method, eg `document` in module __browser__ – marqueemoon Oct 08 '17 at 11:59
3

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.

Juha Tuomala
  • 111
  • 11