Last active
          May 20, 2022 14:39 
        
      - 
      
- 
        Save taikedz/f9893d3a580577db630ce603037ca901 to your computer and use it in GitHub Desktop. 
    Example of using python directly in a HTML page with DOM access
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <!DOCTYPE html> | |
| <html><head> | |
| <style> | |
| python { display: none; } | |
| </style> | |
| <script src="https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js"></script> | |
| <script> | |
| // https://pyodide.org/en/stable/usage/quickstart.html | |
| pyscripts = document.getElementsByTagName("python"); | |
| let pyodide = null | |
| async function main() { | |
| pyodide = await loadPyodide(); | |
| for(i=0; i < pyscripts.length; i++) { | |
| let python_script = pyscripts[i].innerHTML | |
| console.log(pyodide.runPython(python_script)) | |
| } | |
| }; | |
| main(); | |
| </script> | |
| <python> | |
| import js | |
| import time | |
| def add_text(content): | |
| new_elem = js.document.createElement("p") | |
| new_elem.innerText = content | |
| js.document.getElementById("content").appendChild(new_elem) | |
| def count_print(name): | |
| for i in range(20): | |
| add_text(f"{name} {i}") | |
| time.sleep(0.5) | |
| </python> | |
| <python> | |
| # all executions happen with the same context | |
| count_print("First") | |
| </python> | |
| </head> | |
| <body> | |
| <div id="content"></div> | |
| </body> | |
| </html> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Note that this was justa little expriment. A more useful and usable item is pyscript:
https://pyscript.net
See also https://github.com/pyscript/pyscript/blob/main/docs/tutorials/getting-started.md