Skip to content

Commit

Permalink
Add the path of Matplotlib to the link search (for Anaconda)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris00 committed Mar 2, 2024
1 parent ffbd993 commit 7f39f64
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ jobs:
- name: Install Matplotlib (Anaconda)
if: startsWith(matrix.build, 'Anaconda')
run: $CONDA/bin/conda install conda-forge::matplotlib
- name: Test Matplotlib
run: |
$CONDA/bin/conda info --base
$CONDA/bin/conda info --envs
python3 -c "import matplotlib; print(matplotlib.__file__)"
- name: Install Rust (rustup)
run: rustup update ${{ matrix.rust }} --no-self-update && rustup default ${{ matrix.rust }}
shell: bash
Expand Down
21 changes: 21 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use std::{
path::Path,
process::Command,
};

fn main() {
let matplotlib = "import matplotlib; print(matplotlib.__file__)";
let plt_init = Command::new("python3").args(["-c", matplotlib]).output()
.map(|o| o.stdout)
.or_else(|_| {
Command::new("python").args(["-c", matplotlib]).output()
.map(|o| o.stdout)
})
.expect("Pyhon or package matplotlib not found");
let plt_path = String::from_utf8_lossy(&plt_init);
let plt_path = Path::new(plt_path.as_ref());
if let Some(d) = plt_path.parent() {
let d = d.to_str().unwrap();
println!("cargo:rustc-env=MATPLOTLIB_DIR={d}");
}
}
24 changes: 21 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use pyo3::{
prelude::*,
intern,
exceptions::{PyFileNotFoundError, PyPermissionError},
types::{PyDict, PyList},
types::{PyDict, PyList, PyString},
};
use numpy::{
PyArray1,
Expand Down Expand Up @@ -102,10 +102,28 @@ If you use Anaconda, see https://github.com/PyO3/pyo3/issues/1554"),

impl std::error::Error for Error {}

/// Import the module `name`. Try to update the Python search path if
/// it fails.
fn pyimport<N>(py: Python<'_>, name: N) -> Result<Py<PyModule>, PyErr>
where N: IntoPy<Py<PyString>> + Clone {
println!("---------------------{:?}", option_env!("MATPLOTLIB_DIR"));
match PyModule::import(py, name.clone()) {
Ok(m) => Ok(m.into()),
Err(e) => {
if let Some(d) = option_env!("MATPLOTLIB_DIR") {
py.import("sys")?.getattr("path")?
.call_method1("append", (d,)).unwrap();
PyModule::import(py, name).map(|m| m.into())
} else {
Err(e)
}
}
}
}

/// Import and return a handle to the module `$m`.
macro_rules! pyimport { ($m: literal) => {
Python::with_gil(|py|
PyModule::import(py, intern!(py, $m)).map(|m| m.into()))
Python::with_gil(|py| pyimport(py, intern!(py, $m)))
}}

lazy_static! {
Expand Down

0 comments on commit 7f39f64

Please sign in to comment.