c++ - 是否可以在运行时修改 PYTHONPATH?

标签 c++ python boost-python python-c-api python-embedding

我有一个动态链接到 Python 解释器的 C++ 应用程序。我希望能够从特定目录导入 python 模块。我想为我的进程修改 PYTHONPATH,以便 sys.path 将包含我添加到 PYTHONPATH 的路径。根据本文档,这似乎是它的工作方式:

http://docs.python.org/c-api/intro.html#embedding-python

但是,当我从 Python 领域打印 sys.path 时,它具有 PYTHONPATH 的原始内容,而不是我设置的内容。这是我正在做的事情的一个例子(使用 Boost.Python):

int main(int argc, char* argv[])
{
  _putenv_s("PYTHONPATH", "C:\\source\\\\modules");
  Py_Initialize();
  object main = import("__main__");
  object global = (main.attr("__dict__"));
  exec("import sys\nprint sys.path"), global, global);
}

PS - 我知道还有其他方法可以实现我的目标,但这不是我要问的。我想知道为什么 Py_Initialize() 在设置 sys.path 时不使用 PYTHONPATH 的当前值。或许我误解了它的工作原理?

最佳答案

我找到了跨平台解决方案。在调用任何其他 python 代码之前,只需执行以下 python 行:

import sys
sys.path.append("C:\\source\\\\modules")

关于c++ - 是否可以在运行时修改 PYTHONPATH?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5318441/

相关文章:

c++ - boost/ python : How can I use/convert extracted objects?

python - Boost Python找不到dll文件

c++ - std::partial_sum 和 std::inclusive_scan 有什么区别?

c++ - 了解 bool 运算符==(参数1,参数2)

c++ - 初始化列表和 std::forward

python - 循环 python 3 中的错误

python - 左旋转数组

python - 如何在 Python 中将字符串日期时间转换为时间戳?

c++ - 最小化时 DirectX 崩溃

c++ - 编译Boost::Python时出现问题