我正在尝试让 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");
}
}
}
我收到这个运行时错误:
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"
试图在这些线程中找到解决方案但没有任何运气:
更新:
我试过在Visual Studio中打开\pythonnet-master\src\runtime**Python.Runtime.csproj**看能不能编译成.Net或者.Core,但是只能编译成.Net framework . 我找到这篇文章“How to port from .net framework to .net standard” 这是我必须做的吗?
最佳答案
我终于通过使用 2.4.0 版的自编译 Python.Runtime.dll 获得了成功。创建工作 DLL 有两种选择:
- 从相应的项目文件中删除其他目标框架
net461
(仅保留netstandard2.0
)。 - 使用适当的选项运行
dotnet build
对于选项 2,以下有效(在 Windows、Mac 和 Linux 中):
- 克隆 pythonnet 存储库 ( https://github.com/pythonnet/pythonnet )
- 在pythonnet文件夹下,
cd src\runtime
- 在 Windows 中运行
dotnet build -c ReleaseWinPY3 -f netstandard2.0 Python.Runtime.15.csproj
(在 Mac/Linux 中,将ReleaseWinPY3
替换为ReleaseMonoPY3
因为前者使用python37
后者使用python3.7
) - 在 Mac 中设置
DYLD_LIBRARY_PATH
或在 linux 中设置LD_LIBRARY_PATH
(Windows 跳过):
export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.7/lib
- 使用构建的 DLL
bin\netstandard2.0\Python.Runtime.dll
作为 Visual Studio .NET Core 项目中的 DLL 引用(我的目标是netcoreapp2.2
,netcoreapp3.1
也测试正常),例如结合以下代码,
using System;
using Python.Runtime;
namespace Python_CSharp
{
class Program
{
static void Main(string[] args)
{
using (Py.GIL())
{
dynamic os = Py.Import("os");
dynamic dir = os.listdir();
Console.WriteLine(dir);
foreach (var d in dir)
{
Console.WriteLine(d);
}
}
}
}
}
关于c# - 使用 pythonnet 从 .Net Core 调用 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628176/