使用 pythonnet 从 .Net Core 调用 python 脚本

MrC*_*vin 5 .net c# python python.net .net-core

我正在尝试让 pythonnet 在我在 Linux 上运行的 .Net Core 应用程序中工作。

我在我的 .Net Core 项目中引用了Python.Runtime.dll(我从nuget 获得)。

我的代码是:

using System;
using Python.Runtime;
namespace pythonnet_w
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            using (**Py.GIL()**) {
            //     blabla
            }
            Console.WriteLine("End");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到此运行时错误:

 Unhandled Exception: System.MissingMethodException: Method not found:     'System.Reflection.Emit.AssemblyBuilder      
 System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.
    at Python.Runtime.CodeGenerator..ctor()
    at Python.Runtime.DelegateManager..ctor()
    at Python.Runtime.PythonEngine.Initialize(IEnumerable`1 args, Boolean setSysArgv)
    at Python.Runtime.PythonEngine.Initialize(Boolean setSysArgv)
    at Python.Runtime.PythonEngine.Initialize()
    at Python.Runtime.Py.GIL()
    at pythonnet_w.Program.Main(String[] args) in D:\Development\~.Net libraries (3.part)\phytonnet\.Net Core test (phytonnet)\c#\pythonnet_test\Program.cs:line 10
 /usr/sbin/pythonnet_w: line 5: 19487 Aborted                 dotnet "/usr/share/pythonnet_wit/pythonnet_w.dll"
Run Code Online (Sandbox Code Playgroud)

试图在这些线程中找到解决方案,但没有任何运气:

如何在 C# 中运行 py 文件?

从 .NET 调用 Python

更新:

我尝试在 Visual Studio 中打开 \pythonnet-master\src\runtime**Python.Runtime.csproj** 以查看是否可以将其编译为 .Net 或 .Core,但我只能编译为 .Net 框架。我发现这篇文章“如何从 .net 框架移植到 .net 标准”是我必须做的吗?

MP2*_*P24 6

我终于通过使用 2.4.0 版的自编译 Python.Runtime.dll 取得了成功。创建工作 DLL 有两个选项:

  • net461从相应的项目文件中删除另一个目标框架(仅保留netstandard2.0)。
  • dotnet build使用适当的选项运行

对于选项 2,以下工作(在 Windows、Mac 和 Linux 中):

  1. 克隆 pythonnet 存储库 ( https://github.com/pythonnet/pythonnet )
  2. 在 pythonnet 文件夹中, cd src\runtime
  3. dotnet build -c ReleaseWinPY3 -f netstandard2.0 Python.Runtime.15.csproj在 Windows 下运行(在 Mac/Linux 中,由于前用后用而替换ReleaseWinPY3为)ReleaseMonoPY3python37python3.7
  4. 设置DYLD_LIBRARY_PATH在Mac或LD_LIBRARY_PATHLinux中(Windows跳至):
export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.7/lib
Run Code Online (Sandbox Code Playgroud)
  1. bin\netstandard2.0\Python.Runtime.dll在您的 Visual Studio .NET Core 项目(我的目标netcoreapp2.2netcoreapp3.1也经过测试)中使用构建的 DLL作为 DLL 引用,例如结合以下代码,
export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.7/lib
Run Code Online (Sandbox Code Playgroud)