Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an embedded Python runtime to use the current active virtualenv

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/activate
to 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?

like image 288
BrianTheLion Avatar asked Sep 20 '11 23:09

BrianTheLion


1 Answers

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();
like image 177
DikobrAz Avatar answered Sep 23 '22 06:09

DikobrAz