c# - 在 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 的最佳实践吗?
解决方案
推荐阅读
- ajax - Laravel ajax URL 在本地完美地返回 404 错误
- spring-security - @PreAuthorize hasRole 使用属性注入的值
- angular - 错误 TS2339:“AppComponent”类型上不存在属性“fileReset”
- node.js - nodejs require 语句中的 const 与 var
- spring-boot - Spring boot DelegatingSecurityContextAsyncTaskExecutor 导致潜在的内存泄漏
- python - 如何访问正在运行的程序 API
- c# - 当 showdialogwindow 阻止我尝试访问的窗口时,是否有事件或我可以使用的东西
- batch-file - 临时变量增量
- c# - Unity:如何在运行时更改 UI 元素布局(即更改 RectTransform)?
- c# - smtpclient windows server 2008,此邮件服务器在尝试通过此 SMTP(提交)端口发送时需要身份验证 (1)