问题描述
我正在尝试运行 example from the Python docs - 粘贴在这里是为了完整:
这看起来像一个完整的可执行程序,文档读起来像是一个完整的可执行 C 程序,但是运行它给我这个错误:
//Simple.cpp
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int
main(int argc,char *argv[])
{
wchar_t *program = Py_DecodeLocale(argv[0],NULL);
if (program == NULL) {
fprintf(stderr,"Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is',ctime(time()))\n");
if (Py_FinalizeEx() < 0) {
exit(120);
}
PyMem_RawFree(program);
return 0;
}
我唯一能想到的可能是它不喜欢我构建这个程序的方式,即使用以下 cmake 脚本:
Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'D:\UsingPythonFromC\cmake-build-release\src\Simple.exe'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'D:\\UsingPythonFromC\\cmake-build-release\\src\\Simple.exe'
sys.base_prefix = 'C:\\Miniconda3'
sys.base_exec_prefix = 'C:\\Miniconda3'
sys.executable = 'D:\\UsingPythonFromC\\cmake-build-release\\src\\Simple.exe'
sys.prefix = 'C:\\Miniconda3'
sys.exec_prefix = 'C:\\Miniconda3'
sys.path = [
'C:\\Miniconda3\\python38.zip','.\\DLLs','.\\lib','D:\\UsingPythonFromC\\cmake-build-release\\src',]
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 0x00005148 (most recent call first):
<no Python frame>
# CMakeLists.txt
cmake_minimum_required(VERSION 3.19)
project(UsingPythonFromC)
set(CMAKE_CXX_STANDARD 14)
find_package(Python COMPONENTS Interpreter Development NumPy required)
set(target Simple)
add_executable(${target} Simple.cpp)
target_link_libraries(${target} PUBLIC ${Python_LIBRARIES})
target_include_directories(${target} PUBLIC ${Python_INCLUDE_Dirs} ${CMAKE_CURRENT_SOURCE_DIR} )
install(TARGETS ${target})
有人有什么建议吗?谢谢。
编辑
我尝试在调用 #powershell (or whatever)
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=../install-msvc-REL -DPython_ROOT_DIR=C:\Miniconda3 ..
cmake --build --target install --config Release
之前和之后使用 Py_SetPath
添加 site-packages
目录
Py_Initialize
正如评论中所建议的,我用 C:\Miniconda\Lib 尝试了 Py_SetPath,但没有运气。然后我看到 this 答案似乎表明,由于 Py_SetPath(reinterpret_cast<const wchar_t *>(R"(C:\Miniconda3\Lib\site-packages)"));
清除了路径,我们实际上需要为其提供“所有”路径。因为我不确定“全部”是什么意思,所以我尝试添加我的 Py_SetPath
中已经存在的那些。在 PATH
正上方添加此行也不起作用:
Py_Initialize
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)