使用 NuGet 为 .net 设置 pythonnet

Setting up pythonnet for .net using NuGet

我正在尝试开发一个在 .net 中嵌入 python 的简单计算器程序,我想从 NuGet 引用 pythonnet 以将其包含在我的项目中

我使用 NuGet 安装了 pythonnet v2.3.0,我的系统中还安装了 python 3

如果有人给我一步一步的指导来嵌入 python net

就好了

form1.cs代码:

using System;
...
using Python.Runtime;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            PythonEngine.Initialize();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            int num1 = int.Parse(a.Text);
            int num2 = int.Parse(b.Text);
            result.Text = (num1 + num2).ToString();
            using (Py.GIL())
            {
                dynamic np = Py.Import("numpy");
            }
        }
     }
}

当我在代码中使用 using(Py.GIL()) 行时,编译器显示

System.BadImageFormatException: 'Could not load file or assembly 'Python.Runtime, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.'

此问题可能是由 Python.Runtime.dll 和您的 Python 之间的架构 (32-bit/64-bit) 不匹配引起的。

当前在 nuget.org 上发布的 pythonnet 2.3.0 NuGet 包包括两个版本的 Python.Runtime.dll 程序集:32 位 (x86) 和 64 位 (x64)。此包存在一个已知问题,无法在项目中安装正确的引用,即使项目平台设置为 64 位也是如此: https://github.com/pythonnet/pythonnet/issues/472

通常会安装 x86 参考,如果您的 Python 是 64 位,则会出现上述异常。

解决这个问题:

  • 从项目中删除现有程序集引用。
  • 从已安装的 nuget 包中手动添加对正确程序集的引用(例如 your_solution_dir\packages\pythonnet_py35_dotnet.2.3.0\lib\net40\x64\Python.Runtime.dll)

我有同样的问题。我是 运行 KerasExampleWinApp 样本 (keras.net)。错误是:

"...Python.Runtime, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' 或其依赖项之一..."

为了解决这个问题,我只是删除了 Nugget Reference 并重新安装它。

将 CPU 架构从 AnyCPU 更改为 x64 并解决了问题。