프로그래밍/Rust
[macOS] PyO3를 사용하여 rust에서 python 코드를 실행하기
cellaxon
2025. 2. 25. 10:30
1. 새로운 프로젝트 생성
cargo new test_pyo3
2. Cargo.toml 파일에 아래의 내용 추가
[dependencies.pyo3]
version = "0.23.4"
features = ["auto-initialize"]
3. main.rs 수정
use pyo3::ffi::c_str;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
fn main() -> PyResult<()> {
Python::with_gil(|py| {
let sys = py.import("sys")?;
let version: String = sys.getattr("version")?.extract()?;
let locals = [("os", py.import("os")?)].into_py_dict(py)?;
let code = c_str!("os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'");
let user: String = py.eval(code, None, Some(&locals))?.extract()?;
println!("Hello {}, I'm Python {}", user, version);
Ok(())
})
}
4. export를 사용하여 파이썬 경로와 관련된 환경 변수 설정
python 라이브러리 경로 확인 스크립트를 실행하여 설치 경로 확인
import sysconfig
print(sysconfig.get_config_var("LIBDIR"))
실행 결과
python ./scripts/check_python_path.py
/Users/a1/.local/share/mise/installs/python/3.12.8/lib
위의 실행 결과를 아래에 반영하여 터미널에서 실행(영구적으로 사용할 경우 ~/.zshrc 에 추가)
export PYTHONHOME=/Users/a1/.local/share/mise/installs/python/3.12.8
export PYTHONPATH=/Users/a1/.local/share/mise/installs/python/3.12.8/lib/python3.12
export DYLD_LIBRARY_PATH=/Users/a1/.local/share/mise/installs/python/3.12.8/lib:$DYLD_LIBRARY_PATH
5. 프로젝트 실행
cargo run
실행 결과
cargo run --release
Compiling test_pyo3 v0.1.0 (/Users/a1/project/fitogether_video_new/test_pyo3)
Finished `release` profile [optimized] target(s) in 0.33s
Running `target/release/test_pyo3`
Hello a1, I'm Python 3.12.8 (main, Jan 14 2025, 23:36:58) [Clang 19.1.6 ]
https://pyo3.rs/v0.23.4/python-from-rust.html#calling-python-in-rust-code
Calling Python from Rust - PyO3 user guide
This chapter of the guide documents some ways to interact with Python code from Rust. Below is an introduction to the 'py lifetime and some general remarks about how PyO3's API reasons about Python code. The subchapters also cover the following topics: Pyt
pyo3.rs
사업자 정보 표시펼치기/접기
주식회사 셀엑손 (CELLAXON Inc. | 이상효 | 경기도 화성시 동탄감배산로 143, 202동 2409호 | 사업자 등록번호 : 304-81-34245 | TEL : 031-8043-3215 | Mail : ryan@cellaxon.com | 통신판매신고번호 : 2022-화성동탄-0844호 | 사이버몰의 이용약관 바로가기