pybind11 python嵌入Windows 10,致命Python错误:initfsencoding:无法加载文件系统编解码器#1930

时间:2019-09-24 08:14:54

标签: python embed pybind11

当我使用PyBind11嵌入Python interpereter时,我遇到了错误:     initfsencoding:无法加载文件系统编解码器。

详细信息:

OS: Windows 10 1903 18362.356
Python 3.7.4 & Packages: Miniconda installed at C:\Users\My\Miniconda3\envs\sci_dev
MSVS: 2019 community 16.2.5
PyBind11: compiled with VS 2019 from git source with Boost, Eigen and 
    Catch. Installed to C:\Users\My\Miniconda3\envs\sci_dev with only 
    include and share

CMakeLists.txt

cmake_minimum_required( VERSION 3.15 )

project( "PyBind11_Test" )
enable_language(C)
enable_language(CXX)

find_package(pybind11 CONFIG REQUIRED PATHS 
    "C:/Users/My/Miniconda3/envs/sci_dev/share/cmake")`
include_directories( "C:/Users/My/Miniconda3/envs/sci_dev/include/pybind11" )
MESSAGE( [Main] " pybind11_INCLUDE_DIRS = ${pybind11_INCLUDE_DIRS}" )
MESSAGE( [Main] " pybind11_LIBRARIES = ${pybind11_LIBRARIES}" )



add_executable(PyBind11_Test main.cpp)

target_include_directories( PyBind11_Test PRIVATE "C:/Users/My/Miniconda3/envs/sci_dev/include   
        /pybind11" )                                                                    

target_link_libraries(PyBind11_Test PRIVATE pybind11::embed)

和main.cpp

#include <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
int main() {
    py::scoped_interpreter guard{};
    /*
    import sys
    print sys.path
    print "Hello,World!"
    */
    auto sys = py::module::import("sys");
    // sys.attr("path").attr("insert")(1, "C:/Users/My/Miniconda3/envs/sci_dev/Lib/site-packages");
    py::print(sys.attr("path"));
    py::print("Hello, World!"); // use the Python API

    //auto math = py::module::import("math");
    //double root_two = math.attr("sqrt")(2.0).cast<double>();

    //std::cout << "The square root of 2 is: " << root_two << "\n";

当VS configure为X64版本时,在cmd中运行生成exe文件时,它将报告错误:

Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00001628 (most recent call first):

1 个答案:

答案 0 :(得分:0)

根据 Py_Initialize fails - unable to load the file system codec

通过添加指向Python安装位置的环境变量“ PYTHONPATH”和“ PATHONHOME”解决了致命错误。
PATHONPATH="C:\Users\My\Miniconda3\envs\sci_dev\DLLs;C:\Users\My\Miniconda3\envs\sci_dev\Lib;C:\Users\My\Miniconda3\envs\sci_dev\Lib\site-packages"

PATHONHOME="C:\Users\CRRCHZ\Miniconda3\envs\sci_dev"

最后.exe输出预期结果!