<p>我和Pybind11开发人员在这篇BUG文章中合作,以实现最终的解决方案,我将在下面进行总结。一路上出现的另一个错误是:</p>
<pre><code>Fatal Python Error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named ‘encodings’
</code></pre>
<p>尝试从命令提示符运行可执行文件时</p>
<p><a href="https://github.com/pybind/pybind11/issues/2855#issuecomment-777648383" rel="nofollow noreferrer">https://github.com/pybind/pybind11/issues/2855#issuecomment-777648383</a></p>
<hr/>
<p>在Windows 10上(不使用linux的Windows子系统):</p>
<ul>
<li>安装Anaconda或miniconda</li>
<li>使用命令构建conda环境</li>
</ul>
<pre><code>conda create -n embedtest -c conda-forge python==3.7.9 pybind11==2.6.2 cmake=3.19.4
conda activate embedtest
</code></pre>
<p>注意:3.15之后的任何版本的cmake似乎都可以工作。我没有指定pybind11或cmake的哪个版本,而是成功地使用了cmake 3.19.4。(Pybind11版本2.6.2是当前默认值)。此外,避免使用python版本的3.8或3.9,因为已知这些版本不起作用(请参阅pybind11文档)</p>
<ul>
<li>接下来,将下面的文本复制到一个CMakeLists.txt文件中,该文件与pybind11网站(<a href="https://pybind11.readthedocs.io/en/stable/advanced/embedding.html" rel="nofollow noreferrer">https://pybind11.readthedocs.io/en/stable/advanced/embedding.html</a>)中的main.cpp文件位于同一目录中</李>
</ul>
<p>CMakeLists.txt内容:</p>
<pre><code>cmake_minimum_required(VERSION 3.15)
project(main)
find_package(Python COMPONENTS Interpreter Development)
find_package(pybind11 REQUIRED)
add_executable(main main.cpp)
target_link_libraries(main pybind11::embed)
</code></pre>
<ul>
<li>接下来,在激活conda环境的windows命令提示符下运行以下命令,您已移动到main.cpp和CMakeLists.txt文件所在的目录。注意,-B命令在名为build的子目录中生成输出</李>
</ul>
<pre><code>cmake -B build -A x64
cmake build build
set PYTHONHOME=C:\Users\test\Miniconda3\venvs\embedtest
build\Debug\main.exe
</code></pre>
<p>注意:必须从终端设置PYTHONHOME变量,因为使用cmake设置此变量不会使新定义在构建时或执行时可用,从而导致错误。这里给出的目录示例是python可执行文件在conda环境中的位置,在使用find_package(python组件…)找到python包后,可以通过向CMakeLists.txt代码添加以下行轻松获得该位置</p>
<pre><code>message(STATUS ${Python_EXECUTABLE})
</code></pre>
<p>如果您的目标是在没有虚拟环境的情况下使用pybind11,则不需要set(仅限Python_VIRTUALENV)行,但调用的Python版本将是默认安装的版本</p>
<hr/>
<p>如果希望通过WSL在Windows 10上使用pybind11,则说明几乎相同。CMakeLists.txt和main.cpp文件相同,但终端命令略有不同:</p>
<pre><code>cmake -B build
cmake build build
cd build
chmod +x main
./main
</code></pre>