Search code examples
pythonpyscript

Indentation issue in pyscript


i would like to implement pyscript in html code, for instance i want to generate chart output, here is my code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>my first pyscript</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
    -numpy
    -matplotlib
</py-env>
</head>
<body>
<p id="text"></p>
<div id="plot"></div>
<py-script output ="plot">
        import matplotlib.pyplot as plt
        import numpy as np
        x =np.arange(10,20,0.001)
        y =3*x+2
        fig,ax =plt.subplots()
        ax.scatter(x,y)
        fig
<!--    print("hello world")-->
<!--    x =0-->
<!--    pyscript.write("text",x+1)-->

</py-script>
</body>
</html>

but when i am runing code, i get following error :

JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 421, in eval_code CodeRunner( File "/lib/python3.10/site-packages/_pyodide/_base.py", line 237, in __init__ self.ast = next(self._gen) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 141, in _parse_and_compile_gen mod = compile(source, filename, mode, flags | ast.PyCF_ONLY_AST) File "", line 2 import numpy as np IndentationError: unexpected indent )

i did not know that pyscript in html requires indentation, but where is this indent error?


Solution

  • The alpha release of PyScript is almost 2 years old at this point - PyScript has come a long way since then! The most recent release as of April 2024 is 2024.3.2.

    In particular, many issues with indentation were fixed in the big re-write that happened with PyScript 2023.11.1, and further in PyScript 2023.12.1 and .2.

    You can see the getting started guide for an overview of getting started with contemporary PyScript. In the meantime, here's your original code adapted for the most recent style/API:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>my first pyscript</title>
        <link rel="stylesheet" href="https://pyscript.net/releases/2024.3.2/core.css" />
        <script type="module" src="https://pyscript.net/releases/2024.3.2/core.js"></script>
    <py-config>
        packages = ['numpy', 'matplotlib']
    </py-config>
    </head>
    <body>
    <p id="text"></p>
    <div id="plot"></div>
    <script type="py">
        from pyscript import display
        import matplotlib.pyplot as plt
        import numpy as np
        x =np.arange(10,20,0.001)
        y =3*x+2
        fig,ax =plt.subplots()
        ax.scatter(x,y)
        display(fig)
    </script>
    </body>
    </html>