首页 > 解决方案 > 在 c# 应用程序中使用 python 的最佳实践是什么?

问题描述

我需要在 c# 应用程序中使用 Python 分析。

准确地说:c# 应该调用 python 脚本并将输出返回到 c# 应用程序以进行进一步处理。

我已经尝试过使用 IronPython 作为许多人的推荐。

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(@"DemoPythonApplication\SentimentAnalysis.py", scope);

dynamic testFunction = scope.GetVariable("create_sentiment_analysis"); //calling a function from python script file
var result = testFunction(); //This function is returning a dynamic dictionary, which I can use in my c# code further

但 IronPython 的局限性在于,它不支持许多 python 库,如 pandas、numpy、nltk 等,这些库正在 python 脚本中使用。(因为我们有一个不同的团队在研究 python,所以我无法控制他们使用特定的库。)

我尝试的另一个选项是运行 python 进程并调用脚本

private static readonly string PythonLocation = @"Programs\Python\Python37\python.exe"; //Location of Python.exe
private static readonly string PythonScript = @"DemoPythonApplication\SentimentAnalysis.py"; //Location of Python Script

private static void ProcessInPython(int a, int b)
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = PythonLocation;
        start.Arguments = string.Format("{0} {1} {2}", PythonScript, a, b);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;

        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                var result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }

但是,使用这种方法有一些限制,我只能将控制台上打印的任何内容作为string. ,并且无法获得 python 函数返回的输出。

另外,如果我使用第二种方法,我不知道如何从 python 脚本文件中调用特定函数。

有人可以帮助在这种情况下在 c# 中使用 python 的最佳实践吗?

标签: c#pythonironpython

解决方案


推荐阅读