Iron Python System.TypeLoadException:无法从程序集System.Core加载类型“System.Runtime.CompilerServices.Closure”

2024-09-29 23:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在使用Iron Python在C#中运行基于Python的dll

我的C代码中有一行:

public void Runpython(string name, string id)
{
   var engine = Python.CreateEngine();    
   
   //Get Dll
   var path = Environment.CurrentDirectory;
   var fullPath = @$"{path}\PythonService.dll";
   engine.Runtime.LoadAssembly(Assembly.LoadFile(fullPath));
   
   //Get pythonservice.py file         
   var scope = engine.Runtime.ImportModule("pythonservice");

   //Get PythonService class
   var pythonService = scope.GetVariable("PythonService");

   //Run function
   var pyService = engine.Operations.CreateInstance(pythonService);
   var result = pyService.save(name, id);
            
   Console.WriteLine(result);
}

异常发生在这一行:var scope = engine.Runtime.ImportModule("pythonservice"); 当它试图获取我包装在dll中的pythonservice.py文件时

我能知道是什么原因造成的吗

我使用的是Iron Python 2.7.11,我的C#类库和控制台应用程序都是.NET Core 3.1

多谢各位


Tags: pathnamepyidgetstringvarservice
1条回答
网友
1楼 · 发布于 2024-09-29 23:30:53

你可以不用IronPython做同样的工作

在“C:\Program Files\Python39\python.exe”或任何python环境中安装库

试试这个:

public string Run(string scriptFilePatch, string args)
{
    var psi = new ProcessStartInfo();
    psi.FileName = @"C:\Program Files\Python39\python.exe"; // or any python environment

    psi.Arguments = $"\"{scriptFilePatch}\" {args}";

    psi.UseShellExecute = false;
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.StandardOutputEncoding = Encoding.UTF8;

    string errors = "", result = "";

    using (var process = Process.Start(psi))
    {
        result = process.StandardOutput.ReadToEnd();
        errors = process.StandardError.ReadToEnd();

    }
    StringWriter writer = new StringWriter();
    HttpUtility.HtmlDecode(result, writer);
    string decodedString = writer.ToString();

    return decodedString;
}

用法:

 Run("c:/code/download.py", "\"imageUrl\" \"fileName}"");

并阅读python中的参数

Python代码:

    import sys
    url = sys.argv[1] #arg {imageUrl} recived from c# code
    fileName = sys.argv[2] #arg {fileName} recived from c# code

要将数据返回到c#代码,您应该使用以下命令:

b = any_object;
sys.stdout.buffer.write(bytearray(b,"utf-8"))

相关问题 更多 >

    热门问题