pyo3: Can not link to virtual environment on OS X

๐Ÿ› Bug Reports

I can not link to the correct virtual environment in OS X. Instead, the system Python is always used.

๐ŸŒ Environment

  • Your operating system and version: OS X Big Sur 11.5
  • Your python version: 3.8.11
  • How did you install python (e.g. apt or pyenv)? Did you use a virtualenv?: Python was installed with homebrew via brew install python@3.8 A virtual environment was created with python3 -m venv redvox and is located at /Users/anthony/venvs/redvox
  • Your Rust version (rustc --version): rustc 1.56.0-nightly (9c25eb7aa 2021-07-25)
  • Your PyO3 version: 14.1
  • Have you tried using latest PyO3 main (replace version = "0.x.y" with git = "https://github.com/PyO3/pyo3")?:

No

๐Ÿ’ฅ Reproducing

  1. Activate the virtual environment source /Users/anthony/venvs/redvox/bin/activate
  2. Ensure matplotlib is installed pip install matplotlib
  3. Run the rust code cargo run
use pyo3::prelude::*;
use std::io::Result;

fn main() -> Result<()> {
    let src = r#"
import sys
print(sys.executable, sys.path)
import matplotlib
            "#;

    Python::with_gil(|py| {
        py.run(src, None, None).unwrap();
    });

    Ok(())
}

The following shows how I activate the virtual environment and attempt to call the rust code. The error message I receive is also included.

anthony@REDVOX-00-MACBOOK-PRO rust-sandbox % source ~/venvs/redvox/bin/activate
(redvox) anthony@REDVOX-00-MACBOOK-PRO rust-sandbox % python3
Python 3.8.11 (default, Jun 29 2021, 03:08:07) 
[Clang 12.0.5 (clang-1205.0.22.9)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> exit()
(redvox) anthony@REDVOX-00-MACBOOK-PRO rust-sandbox % cargo run 
   Compiling pyo3 v0.14.1
   Compiling rust-sandbox v0.1.0 (/Users/anthony/Development/rust-sandbox)
    Finished dev [unoptimized + debuginfo] target(s) in 4.63s
     Running `target/debug/rust-sandbox`
/Users/anthony/Development/rust-sandbox/target/debug/rust-sandbox ['/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages']
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: PyErr { type: <class 'ModuleNotFoundError'>, value: ModuleNotFoundError("No module named 'matplotlib'"), traceback: Some(<traceback object at 0x100ddbbc0>) }', src/main.rs:12:33
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Iโ€™ve tried setting PYTHONHOME and PYTHONPATH. Neither of these have worked for me. The system Python is always used no matter what I try. How can I get pyo3 to work with my virtual environment on OS X?

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 5
  • Comments: 17 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Something like this could work?

diff --git a/src/gil.rs b/src/gil.rs
index 37e0ed2495..397f9560b0 100644
--- a/src/gil.rs
+++ b/src/gil.rs
@@ -71,6 +71,28 @@ pub fn prepare_freethreaded_python() {
         if ffi::Py_IsInitialized() == 0 {
             ffi::Py_InitializeEx(0);

+            #[cfg(target_os = "macos")]
+            if let Ok(venv) = std::env::var("VIRTUAL_ENV") {
+                // Safety: the GIL is already held because of the Py_IntializeEx call.
+                let pool = GILPool::new();
+                let py = pool.python();
+
+                let version_info = py.version_info();
+                let sys = py.import("sys").unwrap();
+                let sys_path = sys.getattr("path").unwrap();
+                sys_path
+                    .call_method1(
+                        "append",
+                        (format!(
+                            "{}/lib/python{}.{}/site-packages",
+                            venv, version_info.major, version_info.minor
+                        ),),
+                    )
+                    .unwrap();
+
+                drop(pool);
+            }
+
             // Release the GIL.
             ffi::PyEval_SaveThread();
         }

Perhaps, yes. Probably want to detect Conda environments in a similar way. (like we do in pyo3_build_config)

Thereโ€™s also ffi calls we could run before Py_Initiailize e.g. Py_SetPath

I fear that whatever logic we introduce may not work for everyone. I wonder if we can have prepare_freethreaded_python to do a sensible default and then have a builder pattern to be able to enable/disable various bits like this environment detection or pass in specific values.

Hiya, Iโ€™m experiencing the same issue using poetry. The โ€œsolutionโ€ is to append to the PYTHONPATH the site-packagefolder` from the virtualenv lib, e.g.:

export PYTHONPATH=${PYTHONPATH}:/Users/naamanhirschfeld/Library/Caches/pypoetry/virtualenvs/starlite-s4i-xLL2-py3.10/lib/python3.10/site-packages/

This is of course very ugly and quite brittle. Can I suggest that as a safeguard, the user will be able to specify the env or virtual env (depending if running in system or virtual env of course) as a parameter passed to prepare_freethreaded_python?

The solution proposed by @messense works great, but does not work if you have editable installed packages (aka packages installed with -e). I still cant find a solution for this. Is there anything that can be done to help deal with this issue?

I spent yesterday fighting this and wanted to raise another difficulty I found. I was able to include my virtualenvโ€™s site-packages by setting PYTHONPATH to $VIRTUAL_ENV/lib/python3.$MINOR_VERSION/site-packages. However, the system site-packages was still included, so my sys.path ended up looking like

'/Users/jacksonnewhouse/code/influxdb/.venv/lib/python3.13/site-packages',
 '/Users/jacksonnewhouse/.pyenv/versions/3.13.0/lib/python313.zip',
 '/Users/jacksonnewhouse/.pyenv/versions/3.13.0/lib/python3.13',
 '/Users/jacksonnewhouse/.pyenv/versions/3.13.0/lib/python3.13/lib-dynload',
 '/Users/jacksonnewhouse/.pyenv/versions/3.13.0/lib/python3.13/site-packages'

This leads to unexpected behavior like successfully importing a package that only exists in the main python installation but not in the virtualenv.

Next step was to use the env var PYTHONPATH to set the paths to search (as an alternative to finding them via the venv). This seems to completely replace the sys.path rather than prepending it.

So as a follow on step I set the all the relevant paths using the PYTHONPATH env var.

This seems to work and I have bene able to load my python modules. But I do not believe it is the right way to use PYTHONPATH. I believe PYTHONPATH is supposed to be used to extend the search path of python modules not to define the complete search path.

I base this on how python is working:

(venv) bengreene@Euclid rusty-snakeskin % export PYTHONPATH=/Users/bengreene/Development/rusty-snakeskin/venv/lib/python3.9/site-packagesafdfsdf
(venv) bengreene@Euclid rusty-snakeskin % python -c "import sys; print('\n'.join(sys.path))"                                                    

/Users/bengreene/Development/rusty-snakeskin/venv/lib/python3.9/site-packagesafdfsdf
/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python39.zip
/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9
/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload
/Users/bengreene/Development/rusty-snakeskin/venv/lib/python3.9/site-packages
/Users/bengreene/Development/rusty-snakeskin/mypy

So it points me to the sys.path is not being initialised correctly. I was not able to easily locate where in the code this was set. But if you can point me in the right direction I am happy to take a look.