Import Modules to Pyscript
Asked Answered
P

2

7

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!

Profit answered 4/5, 2022 at 21:30 Comment(1)
it seems someone already answered this. If you see examples then you see <py-env> which defines what modules can be used. If I tried to use non-existing module then I saw it error that it can't find it on https://pypi.org (and probably it loads modules directly from this server). And as I expected some modules may not work because they may use C/C++ libraries.Billat
S
14

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>
Splice answered 4/5, 2022 at 22:18 Comment(1)
FYI it appears that a lot changed since this answer was posted. I added a new one.Tetanus
T
3

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>
Tetanus answered 25/11, 2023 at 13:35 Comment(1)
This did the trick for me tooIble

© 2022 - 2024 — McMap. All rights reserved.