1

I am using Brython.js I am able to print a loop in HTML browser but as you can see this is adding the output to entire DOM.

How can I append the print result into an specific DOM element? For example if I want to print the output into #map, how can I do it?

    <ul id="maps"></ul>
    <script type="text/python">
        from browser import document
        import sys
        sys.stdout = document
        maps= ["world", "asia", "africa"]
        for x in maps:
         print(x)
     </script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125
  • Just a quick reminder about the level of pleading in your questions, Behseini. I noted it recently [here](https://stackoverflow.com/questions/66397084/how-to-add-item-to-class-list-of-objects-populated-in-an-ienumerable), [here](https://stackoverflow.com/questions/66404171/property-returns-null-using-c-sharp-expression-bodied-in-construction) and [here](https://stackoverflow.com/questions/66293794/how-to-navigate-to-cpt-archive-from-listed-taxonomy-term). – halfer Mar 19 '21 at 19:43
  • It's worth noting that readers who feel they are being exalted, put on a pedestal, or showered with ingratiation may just decide to skip the question. Most people would rather be spoken to as if they were a colleague - perhaps because begging can be interpreted as a form of emotional manipulation. – halfer Mar 19 '21 at 19:50

1 Answers1

1

You can assign an instance of a custom class to sys.stdout. You just have to override the write method. For example:

from browser import document
import sys

class CustomStdout:
    def write(self, txt):
        document['maps'].html += f'<li>{txt}</li>'


sys.stdout = CustomStdout()

maps = ["world", "asia", "africa"]

for x in maps:
    print(x)

But the following would be simpler:

from browser import document
from browser.html import LI

maps_ul = document['maps']
maps = ["world", "asia", "africa"]

for x in maps:
    maps_ul <= LI(x)

The <= operator, being the operands of type DOMElement, acts like appendChild in brython.

tecnobillo
  • 161
  • 2
  • 6