【问题标题】:Embedding Python 3.3 in C++ from zipped standard library on Windows XP在 Windows XP 上从压缩的标准库中将 Python 3.3 嵌入到 C++ 中
【发布时间】:2014-04-06 03:41:24
【问题描述】:

我想在我的 C++ 应用程序中嵌入 Python 3.3.4,以便:

  • Python 的标准库始终取自我应用的可执行文件旁边的 zip 存档(不应依赖于任何环境变量等);
  • 我自己的自定义 .py 模块是从另一个文件夹与可执行文件一起的 zip 存档导入的。

而且,事实上,我几乎成功地做到了。唯一仍然不起作用的是从 ZIP 存档中导入标准库:它作为一个简单的目录可以正常工作,但是每当我尝试对其进行压缩时,初始化都会失败并出现以下错误:

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

最新的 Python 甚至可以吗?我已经为此搜索了很多,并且许多消息来源声称在可执行文件附近放置正确的“python33.zip”应该可以工作。尽管如此,我的实验证明并非如此。我错过了什么?

这是我的测试代码 - 由 MS Visual Studio 2010 制作的最小控制台应用程序,在 Windows XP SP3 上运行,其中包含一些关于我尝试的内容和结果的 cmet:

#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;
}

【问题讨论】:

  • 是的,我已经尝试了所有方法,包括将 python33.zip 复制到 Windows\system32(由于某种原因,“Windows\system32\python33.zip”实际上包含在默认的 Py_GetPath() 中)。我也尝试使用 Py_SetPythonHome。结果总是一样的:只要标准库没有被压缩就可以正常工作,一旦压缩就会崩溃。
  • 无论如何,无论路径如何(正如我已经说过的,我也尝试以绝对形式指定它),它只是拒绝从 zip 加载标准库,但适用于任何“正常”目录。这是我现在看到的主要(也是唯一)问题。
  • 另外,我刚刚请人尝试在 Win7 上运行它。结果相同(崩溃)。所以它似乎也不是特定于 WinXP 的。
  • 好吧,我刚刚用你的 7z 命令行重新创建了python33.zip,结果还是一样(也尝试使用绝对路径:Py_SetPath(L"c:\\python33.zip");)。是的,它还打印ImportError: No module named 'encodings'。抱歉,我之前错过了这个。您是在使用包中包含的“库存”python .lib/.dll,还是从源代码构建它们?
  • 那么,我开始认为我的电脑或我的脑袋有问题。 :) 您能否给我发电子邮件(kirinyale[at]gmail.com)或以其他方式分享您的可执行文件和源代码,以便我检查它是否在我身边运行?

标签: python c++ windows python-3.x windows-xp


【解决方案1】:

这个问题最近被发现并记录在Python Issue 20621 中。 Python 3.3.5 中将发布对它的修复; 3.3.5 候选版本 2 现在可用于测试。 http://www.python.org/download/releases/3.3.5/

【讨论】:

    【解决方案2】:

    原来是 Python 3.3.4 的一些问题。安装 3.3.2 或 3.3.3 会立即修复所有问题。

    在 Python 的错误跟踪器上提交了此问题:

    http://bugs.python.org/issue20852

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2020-10-04
      • 2013-08-28
      相关资源
      最近更新 更多