从C#调用Python可以通过多种方式实现,以下是几种常见的方法及其基础概念、优势、类型、应用场景以及可能遇到的问题和解决方法。
subprocess
模块和C#的System.Diagnostics.Process
类。using System.Diagnostics;
public void RunPythonScript(string scriptPath, string arguments)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python"; // 或者是python.exe的完整路径
start.Arguments = $"{scriptPath} {arguments}";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.WriteLine(result);
}
using (StreamReader reader = process.StandardError)
{
string error = reader.ReadToEnd();
if (!string.IsNullOrEmpty(error))
{
Console.Error.WriteLine(error);
}
}
}
}
首先,安装Python.NET库:
pip install pythonnet
然后在C#中使用:
using Python.Runtime;
public void CallPythonFunction()
{
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
double[] data = { 1.0, 2.0, 3.0 };
dynamic result = np.array(data);
Console.WriteLine(result);
}
}
通过上述方法,可以在C#应用中有效地集成和调用Python脚本或函数,实现更复杂的功能和应用场景。
领取专属 10元无门槛券
手把手带您无忧上云