我正在尝试在我的 C++ dll 库中使用嵌入式 python。该库是使用 GCC 编译器、CMake 和 Ninja 在 MSYS2 中构建和编译的。 Python 3.10 也使用 pacman 安装在 MSYS2 上。 Windows 10 env 在路径中包含
C:\msys64\mingw64\bin
(python 也位于此处)。 Python 未安装在 Windows 上,仅安装在 MSYS2 上。
这就是
CMakeLists.txt
包含的内容:
cmake_minimum_required(VERSION 3.26)
project(python_test)
set(CMAKE_CXX_STANDARD 17)
find_package(Python REQUIRED Development)
add_executable(python_test main.cpp)
target_link_libraries(python_test PRIVATE Python::Python)
简单测试代码:
int main() {
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"import numpy as np\n"
"print('Today is', ctime(time()))\n");
if (Py_FinalizeEx() < 0)
exit(120);
return 0;
}
当我运行此代码时,出现此错误:
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'python3'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'C:\\Users\\someUsername\\CLionProjects\\python_test\\cmake-build-debug\\python_test.exe'
sys.base_prefix = 'D:\\a\\msys64\\mingw64'
sys.base_exec_prefix = 'D:\\a\\msys64\\mingw64'
sys.platlibdir = 'lib'
sys.executable = 'C:\\Users\\someUsername\\CLionProjects\\python_test\\cmake-build-debug\\python_test.exe'
sys.prefix = 'D:\\a\\msys64\\mingw64'
sys.exec_prefix = 'D:\\a\\msys64\\mingw64'
sys.path = [
'D:\\a\\msys64\\mingw64\\lib\\python310.zip',
'D:\\a\\msys64\\mingw64\\lib\\python3.10',
'D:\\a\\msys64\\mingw64\\lib\\lib-dynload',
'',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00004564 (most recent call first):
<no Python frame>
但是
python
命令在 MSYS2/MinGW 控制台和 Windows cmd 中都可以工作。当我在 Windows 10 环境中将 PYTHONHOME 指定为 C:\msys64\mingw64\bin
时,我在 Clion 中再次遇到相同的错误,现在在 Windows 命令行中也是如此。如何解决这个问题?
我设置了
PYTHONHOME=C:\msys64\mingw64\bin
,更重要的是PYTHONPATH=C:\msys64\mingw64\lib\python3.10;C:\msys64\mingw64\lib\python3.10\site-packages;C:\msys64\mingw64\lib\lib-dynload
,它解决了我的问题