javascriptpythonpyscriptpyodide

Modules are not installing/importing using pyodide (v0.23.2)


I am new to Python and trying to display some diagrams on a webpage using Pyscript. However, importing modules with Pyodide isn't working. I've tried every single example found in the documentation as well as this thread: How do I import modules in a project using pyodide without errors? but it's still not working.

I've tried "loadPackage", "py-env" and "micropip.install". Am I missing something? I am completely confused. I am getting the "ModuleNotFoundError: The module 'pandas' is included in the Pyodide distribution, but it is not installed." error again and again: enter image description here

The example of the code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    <meta charset="utf-8" />
    <title>PyScript Demo</title>
</head>
<body>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/pyodide/v0.23.2/full/pyodide.js"></script>
    <script type="text/javascript">
      async function main() {
        const pyodide = await loadPyodide()
        await pyodide.loadPackage("micropip");
        const micropip = pyodide.pyimport("micropip");
        await micropip.install("pandas");
        await micropip.install("matplotlib");
        await pyodide.runPython(`
        import pandas as pd
        import matplotlib.pyplot as plt
        `);
      }
    main();
    </script>
    <py-env>
      - pandas
      - matplotlib.pyplot
    </py-env>
    <h1>Hello, Geeks</h1>
    <py-script>
        import pandas as pd
        import matplotlib.pyplot as plt

        df = pd.DataFrame([['g1', 'c1', 10], ['g1', 'c2', 12], ['g1', 'c3', 13], ['g2', 'c1', 8],
                   ['g2', 'c2', 10], ['g2', 'c3', 12]], columns=['group', 'column', 'val'])

        df.pivot(index="column", columns="group", values="val").plot(kind='bar')

        plt.show()
        plt.close()
    </py-script>
</body>
</html>

Thank you!


Solution

  • First, you should either load Pyodide or Pyscript, not both. Otherwise, since PyScript includes Pyodide, you end up with two installs of Pyodide.

    Second, your code for PyScript seems outdated, in the latest version the way to specify requirements is via,

        <py-config>
          packages = ["matplotlib", "pandas"]
        </py-config>
    

    instead of via the py-env