在Windows XP上从压缩标准库中嵌入Python 3.3到C++

5 投票
2 回答
1599 浏览
提问于 2025-04-17 20:47

我想把Python 3.3.4嵌入到我的C++应用程序中,具体要求是:

  • Python的标准库总是从一个和我的应用程序可执行文件放在一起的zip压缩包中获取(不应该依赖任何环境变量等);
  • 我自己写的自定义.py模块要从一个不同的文件夹或者和可执行文件放在一起的zip压缩包中导入。

实际上,我几乎已经做到这一点了。唯一还不工作的就是从ZIP压缩包中导入标准库:作为一个简单的文件夹是可以正常工作的,但每当我尝试把它压缩成zip时,初始化就会失败,并出现以下错误:

Fatal Python error: Py_Initialize: unable to load the file system codec

最新的Python真的可以这样做吗?我在网上查了很多资料,很多来源都说把正确的"python33.zip"放在可执行文件旁边应该可以工作。不过,我的实验结果却不一样。我到底漏掉了什么呢?

这是我的测试代码——一个用MS Visual Studio 2010制作的最简单的控制台应用程序,运行在Windows XP SP3上,里面有一些我尝试过的内容和结果的注释:

#include "stdafx.h"
#include "python.h"

int _tmain(int argc, _TCHAR* argv[])
{
    // calling or not calling Py_SetProgramName doesn't seem to change anything
    //Py_SetProgramName(argv[0]);

    // python_lib is a directory with contents of python33/Lib
    // python_lib.zip is an equivalent ZIP archive with contents of python33/Lib (without any top-level subdirs)
    // _scripts.dat is a ZIP archive containing a custom script (hello.py)

    //Py_SetPath(L"python_lib;_scripts.dat"); // works fine! (non-zipped standard library, zipped custom script)

    Py_SetPath(L"python_lib.zip;_scripts.dat"); // both std library and scripts are zipped - fails with error "unable to load the file system codec" during Py_Initialize()

    Py_Initialize();

    PyRun_SimpleString("from time import time,ctime\n"
                        "print('Today is',ctime(time()))\n");

    PyRun_SimpleString("import hello"); // runs hello.py from inside _scripts.dat (works fine if Py_Initialize succeeds)

    Py_Finalize();

    return 0;
}

2 个回答

1

原来是Python 3.3.4出了点问题。换成3.3.2或3.3.3就能立刻解决所有问题。

我在Python的错误追踪系统上提交了这个问题:

http://bugs.python.org/issue20852

2

这个问题最近被发现并记录在 Python问题20621 中。它的修复将在Python 3.3.5版本中发布;现在可以测试3.3.5的第二个候选版本。你可以在这里找到下载链接:http://www.python.org/download/releases/3.3.5/

撰写回答