如何在 Windows 10 和 Python 3.8 上为 C# (VS2019) 安装 Python.NET?

How to install Python.NET for C# (VS2019) on Windows 10 and for Python 3.8?

Python.NET官网上说支持Python3.8。伟大的。 现在我有兴趣从用 C#(.NET 框架 v4.7.2)开发的应用程序调用我现有的 python 3.8 模块。

编辑:

由于 Python.NET 的作者几乎没有为来自 C# 的调用提供任何安装说明,因此我遵循了 给出的说明。 请注意,我使用的是 miniconda3 和 python 32 位(我的项目需要后者)所以我执行了以下操作:

  1. 从 VScode,我用 pip install 安装了 pythonnet 以及所有必需的 python 包(让我们使用 numpy这里为了举例)在“C:\ProgramData\Miniconda3\envs\py38_32”环境下。

  2. 在 C# 中设置环境路径(在 VS2019 中):

    string pythonPath1 = @"C:\ProgramData\Miniconda3\envs\py38_32";
    string pythonPath2 = @"C:\ProgramData\Miniconda3\envs\py38_32\Lib\site-packages";
    Environment.SetEnvironmentVariable("PATH", pythonPath1, EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath1, EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath2, EnvironmentVariableTarget.Process);
  1. 从我项目的“py38_32\Lib\site-packages”文件夹中引用了Python.Runtime.dll并添加了using Python.Runtime;

  2. 尝试导入 numpy:

    using (Py.GIL())
    {
        dynamic np = Py.Import("numpy"); //fail on this line with ImportError
    }
    

numpy 导入失败,出现“Python.Runtime.PythonException: 'ImportError”。它还说“Python 版本是:来自“\bin\Debug\MyProject.exe”的 Python3.8... 似乎它在我的调试文件夹中查找 python,而不是在上面提到的路径......也许......并且使用相同的环境从VScode导入numpy完全没问题。

有人知道这里发生了什么吗?

安装Python.NET的官方方法是通过Python包管理器pip

在 Windows,那将是 python.exe -m pip install pythonnet。这将在您的 Python 发行版中的某处创建 Python.Runtime.dll。只需从您的项目中引用它,并确保架构匹配。

一个不受支持的替代方法是使用 my unofficial build, and set Runtime.PythonDLL to the location of python38.dll of your choice (you can find one at runtime using another NuGet package: WhichPython).

如前所述 here,Anaconda(和 Miniconda)不适用于 Python.NET。我所要做的就是用我需要的所有包重新安装 Python 的新副本,并用新路径替换以下代码:

string pythonPath1 = @"C:\Python";
string pythonPath2 = @"C:\Python\Lib\site-packages";