2025年1月2日木曜日

how to use py-script in WEB

 1. Project Setup

  • Create an HTML file: Start with a basic HTML structure:
HTML
<!DOCTYPE html>
<html>
<head>
    <title>My PyScript App</title>
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>

</body>
</html>

2. Include PyScript Tags

  • <py-env>: Define the Python environment (optional but recommended):
HTML
<py-env>
    - numpy
    - pandas 
</py-env> 
* This specifies the Python libraries you'll use (e.g., NumPy, Pandas).
  • <py-script>: Write your Python code within this tag:
HTML
<py-script>
    print("Hello from PyScript!") 
</py-script>

3. Display Output (Optional)

  • Use display(): To display Python output within the HTML:
HTML
<py-script>
    from js import document
    document.getElementById("my-output").innerHTML = "Output from Python" 
</py-script>

<div id="my-output"></div> 

4. Interact with HTML (Optional)

  • Use Element(): To access and manipulate HTML elements:
HTML
<py-script>
    from pyodide.ffi import create_proxy
    from js import document, window

    def button_click():
        print("Button clicked!") 

    button = Element("my-button")
    button.addEventListener("click", create_proxy(button_click)) 
</py-script>

<button id="my-button">Click Me</button>

5. Run the HTML File

  • Open the HTML file in a web browser that supports JavaScript.

Key Concepts

  • py-env: Defines the Python environment and dependencies.
  • py-script: Contains your Python code.
  • display(): Outputs Python results to the HTML.
  • Element(): Allows interaction with HTML elements.
  • js: Provides access to JavaScript objects and functions.

Example: Simple Calculation

HTML
<!DOCTYPE html>
<html>
<head>
    <title>PyScript Calculation</title>
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>

    <py-script>
        def add_numbers(a, b):
            return a + b

        result = add_numbers(5, 3)
        print(f"The sum is: {result}") 
    </py-script>

</body>
</html>

Remember:

  • PyScript is still under development, so there might be some limitations or changes in the future.
  • Refer to the official PyScript documentation for the latest information and advanced features.

I hope this helps! Let me know if you have any further questions.