Import Error when importing complex Python libraries #3388
-
OverviewI'm trying to use pyo3 to embed a python lib to my rust project, however when I'm trying to import the lib I got Import Errors. ReproduceHere's the simplest way to reproduce: Python File Structure:
# app.py
from utils import foo
def run():
return foo() # bar.py
def bar():
return 12 # foo.py
from utils.bar import bar
def foo():
return 20 + bar() # utils/__init__.py
from utils.bar import bar
from utils.foo import foo And my rust code is: let py_foo = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python/utils/foo.py"));
let py_bar = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python/utils/bar.py"));
let py_app = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/python/app.py"));
let from_python = Python::with_gil(|py| -> PyResult<u32> {
PyModule::from_code(py, "", "utils/__init__.py", "utils")?;
PyModule::from_code(py, py_foo, "utils/foo.py", "utils")?;
PyModule::from_code(py, py_bar, "utils/bar.py", "utils")?;
let app: Py<PyAny> = PyModule::from_code(py, py_app, "app.py", "")?
.getattr("run")?
.into();
app.call0(py)?.extract(py)
});
println!("py: {}", from_python?); And then I receive such error:
How could I solve this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Or maybe I could zip my python code and unzip after distribution, then use |
Beta Was this translation helpful? Give feedback.
-
Usually with these kinds of distribution issues I recommend taking a look at PyOxidizer, which is able to zip your project and dependencies into a single executable. |
Beta Was this translation helpful? Give feedback.
I see. It's not something we've directly got a solution for at the moment. I think zipping and including in your lib as a byte stream is the way to go. If you want to avoid unzipping you might be able to add a loader to the import system which can use the
zipimport
mechanism to read directly from the bytes embedded in your lib, but that's pure speculation.