【问题标题】:Fatal Python error: Py_Initialize: unable to load the file system codec & ModuleNotFoundError致命的 Python 错误:Py_Initialize:无法加载文件系统编解码器和 ModuleNotFoundError
【发布时间】:2019-03-30 19:58:22
【问题描述】:

意图

我想从 C++ 访问一个 python 函数,并且正在使用 C++17 和 Python 3.7.3。

我的 Visual Studio 项目设置

  • C/C++ > 常规 > 其他包含目录 > "D:\Programme\vcpkg\installed\x64-windows\include\python3.6"
  • 链接器 > 常规 > 其他库目录 > "D:\Programme\vcpkg\installed\x64-windows\lib"
  • 链接器 > 输入 > 附加依赖项 > python36.lib;...

Main.cpp

#include <Python.h>
#include <iostream>
#include "tchar.h"

int _tmain(int argc, _TCHAR* argv[])
{
    printf("Calling Python to find the sum of 2 and 2.\n");

    // Initialize the Python interpreter.
    Py_Initialize();

    // Create some Python objects that will later be assigned values.
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;

    // Convert the file name to a Python string.
    pName = PyUnicode_FromString("Sample");

    // Import the file as a Python module.
    pModule = PyImport_Import(pName);

    // Create a dictionary for the contents of the module.
    pDict = PyModule_GetDict(pModule);

    // Get the add method from the dictionary.
    pFunc = PyDict_GetItemString(pDict, "add");

    // Create a Python tuple to hold the arguments to the method.
    pArgs = PyTuple_New(2);

    // Convert 2 to a Python integer.
    pValue = PyLong_FromLong(2);

    // Set the Python int as the first and second arguments to the method.
    PyTuple_SetItem(pArgs, 0, pValue);
    PyTuple_SetItem(pArgs, 1, pValue);

    // Call the function with the arguments.
    PyObject* pResult = PyObject_CallObject(pFunc, pArgs);

    // Print a message if calling the method failed.
    if (pResult == NULL)
        printf("Calling the add method failed.\n");

    // Convert the result to a long from a Python object.
    long result = PyLong_AsLong(pResult);

    // Destroy the Python interpreter.
    Py_Finalize();

    // Print the result.
    printf("The result is %d.\n", result); std::cin.ignore(); return 0;
}

示例.py

​​>
# Returns the sum of two numbers.
def add(a, b):
    return a + b

我的目录

directory of files

release version

solution directory

错误

Calling Python to find the sum of 2 and 2.
Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00003ca0 (most recent call first):

【问题讨论】:

标签: python c++ embed


【解决方案1】:

我从这篇帖子Py_Initialize fails - unable to load the file system codec@Calvin1602(Stackoverflow 用户)那里找到了一个可行的解决方案

我刚刚遇到了完全相同的问题(相同的 Python 版本、操作系统、代码等)。

您只需将 Python 的 Lib/ 目录复制到程序的 工作目录(在 VC 上是 .vcproj 所在的目录)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2015-08-26
    • 2019-06-02
    • 2011-08-07
    • 2019-11-26
    • 2018-11-09
    • 2018-12-13
    • 2018-12-26
    相关资源
    最近更新 更多