Question
I came across pyscript hoping to use it to document python code with mkdocs. I have looked into importing my own module. Individual files work. How do I import my own module using pyscript instead?
- Requirements for running the example:
- python package
numpy
($ pip install numpy
) - python package
matplotlib
($ pip install matplotlib
) - local webserver for live preview on localhost (eq.
$ npm install -g live-server
)
- python package
Below is an example that works with the 'just import a python file' approach, see line
from example import myplot
.When I change the line to
from package.example import myplot
it is not working and I get the following error in firefox/chromium:JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 1, in ModuleNotFoundError: No module named 'package' )
Any help is appreciated. I found this discussion on github, but I am lost when trying to follow.
Example
Folder structure
├── index.html
└── pycode/
├── example.py
└── package/
├── example.py
└── __init__.py
index.html
<!doctype html>
<html>
<head>
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css"/>
<py-env>
- numpy
- matplotlib
- paths:
- ./pycode/example.py
- ./pycode/package
</py-env>
</head>
<body>
<div id="lineplot"></div>
<py-script>
from example import myplot
import matplotlib.pyplot as plt
theta,r = myplot(4)
fig, ax = plt.subplots(
subplot_kw = {'projection': 'polar'}
)
ax.plot(theta, r)
ax.set_rticks([0.5, 1, 1.5, 2])
ax.grid(True)
pyscript.write('lineplot',fig)
</py-script>
</body>
</html>
example.py
import numpy as np
def myplot(val:int):
r = np.arange(0, 2, 0.01)
theta = val * np.pi * r
return theta,r
__init__.py
__all__ = [ 'example.py' ]
Intended result in the webbrowser