I make heavy use of virtualenv to isolate my development environments from the system-wide Python installation. Typical work-flow for using a virtualenv involves running
source /path/to/virtualenv/bin/activateto set the environment variables that Python requires to execute an isolated runtime. Making sure my Python executables use the current active virtualenv is as simple as setting the shebang to
#!/usr/bin/env python
Lately, though, I've been writing some C code that embeds the Python runtime. What I can't seem to figure out is how to get the embedded runtime to use the current active virtualenv. Anybody got a good example to share?
Inspecting path and setting Py_SetProgramName worked for me:
std::vector<std::string> paths;
std::string pathEnv = getenv("PATH");
boost::split(paths, pathEnv, boost::is_any_of(";:"));
for (std::string path : paths)
{
boost::filesystem::path pythonPath = boost::filesystem::path(path) / "python";
std::cout << pythonPath << std::endl;
if (boost::filesystem::exists(pythonPath))
{
pythonProgramName_ = pythonPath.string(); // remember path, because Py_SetProgramName doesn't save it anywhere
Py_SetProgramName(&pythonProgramName_[0]);
break;
}
}
Py_Initialize();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With