Embed python interpreter to cc_binary

147 views
Skip to first unread message

Phuong Nguyen

unread,
May 18, 2023, 4:27:09 AM5/18/23
to bazel-discuss
Hi all,
Currently I have a cpp project, which needs to call API which are python scripts. I found out pybind11 which is quite user-friendly. But the issue is that I cannot integrate the python interpreter to my cc_binary which lead to the program cannot start.
Do you guys have any experience with it? The context is like I want to call python script from cpp file, so what I need to update in my BUILD file to let it know.

Thanks in advance!

Jason Schein

unread,
May 30, 2023, 5:03:56 AM5/30/23
to bazel-discuss
I don't write much C++, but I've done this in binaries in other languages. You can pass the python interpreter into a binary as a data dep and then provide the path to that binary using make variables like so:
cc_binary(
env = {
"PYTHON_PATH": "$(rootpath @python3_9_x86_64-unknown-linux-gnu//:python)",
},
data = "@python3_9_x86_64-unknown-linux-gnu//:python"
)

I have an example saved on my PC for doing this in rust that I'll share, its pretty simple and you should be able to do the same thing in your C++ program

BUILD file:
load("@rules_rust//rust:defs.bzl", "rust_binary")
rust_binary(
name = "main",
srcs = ["main.rs"],
deps = [],
rustc_env = {
"PYTHON_PATH": "$(rootpath @python3_9_x86_64-unknown-linux-gnu//:python)",
},
data = [
"@python3_9_x86_64-unknown-linux-gnu//:python",
],
)
Rust File:
use std::env;
use std::error::Error;
use std::process::Command;

fn main() -> Result<(), Box<dyn Error>> {
let python = env!("PYTHON_PATH");
println!("env python is {:?}", &python);
// Calls python interpretter
let res = Command::new(env::current_dir()?.join(&python))
.arg("-c")
// Python command being run
.arg("print('hello from python')")
.output()
.expect("failed to execute process");
println!("{:?}", std::str::from_utf8(&res.stdout)?);
Ok(())
}

Reply all
Reply to author
Forward
0 new messages