【问题标题】:How to install Python.NET for C# (VS2019) on Windows 10 and for Python 3.8?如何在 Windows 10 和 Python 3.8 上为 C# (VS2019) 安装 Python.NET?
【发布时间】:2020-12-14 15:07:30
【问题描述】:

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

编辑:

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

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

  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 c# python.net


    【解决方案1】:

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

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

    一种不受支持的替代方法是使用my unofficial build,并将Runtime.PythonDLL 设置为您选择的python38.dll 的位置(您可以在运行时使用另一个NuGet 包找到一个:WhichPython)。

    【讨论】:

    • 是的,问题中已经提到了 pip 安装。但是感谢您宣传不受支持的替代品...
    • 不支持的版本已经合并到Python.NET官方:nuget.org/packages/pythonnet
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 2020-02-29
      • 2020-11-25
      • 2020-05-27
      • 1970-01-01
      • 2020-07-03
      • 2020-04-08
      • 2020-09-03
      相关资源
      最近更新 更多