Import Modules to Pyscript

16.8k Views Asked by At

When we are coding python code, we typically use packages and modules that we import. For example, when we are coding we may write:

import numpy
import requests
from bs4 import BeautifulSoup

When we are trying to integrate python with html with Pyscript (https://pyscript.net/), it just says that it doesn’t have the package installed. However, when this happens in normal python we use PiP and import it from there. However, what should we do when we need a package in Pyscript?

Thank you!

2

There are 2 best solutions below

1
On BEST ANSWER

At this time, bs4 is not supported. You will receive an error

ValueError: Couldn't find a pure Python 3 wheel for 'bs4'

You will also have problems using the requests package in pyscript. Usepyfetch instead of requests.get.

To import numpy and requests, use <py-env> before <py-script>. Example:

<body>
  <py-env>
  - numpy
  </py-env>

  <py-script>

import numpy as np

print(np.random.randn(10, 4))

</py-script>
</body>

Pyscript also supports package versions:

  <py-env>
    - numpy==1.22.3
  </py-env>
1
On

It looks like py-env has been deprecated (I couldn't get it to work at all). Fortunately, py-config did the trick:

  <py-config type="toml">
    packages = ["numpy", "beautifulsoup4", "requests"]
  </py-config>

  <py-script>
        import numpy as np
        import requests
        import bs4
        from bs4 import BeautifulSoup

        print(bs4.__version__)
        print(requests.__version__)

        a = np.array([1, 2, 3])
        print("Array:", a)
        print("Hello from Python in the browser!")
  </py-script>