在C#中调用Python代码主要有以下四种方式,根据需求选择合适的方法:
一、通过命令行调用(System.Diagnostics.Process)
适用于Python脚本不依赖第三方模块的情况,通过启动子进程执行脚本。
示例代码:
using System.Diagnostics;
public void RunPythonScript(string scriptPath, string arguments)
{
ProcessStartInfo start = new ProcessStartInfo
{
FileName = "python", // 或 python.exe 完整路径
Arguments = $"{scriptPath} {arguments}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
using (Process process = Process.Start(start))
{
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (!string.IsNullOrEmpty(error))
Console.WriteLine($"Error: {error}");
else
Console.WriteLine(output);
}
}
二、使用IronPython(嵌入式解释器)
适用于Python脚本依赖.NET库或需要与C#深度集成的场景,需额外安装IronPython库。
示例代码:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
namespace CSharpCallPython
{
class Program
{
static void Main(string[] args)
{
ScriptEngine pyEngine = Python.CreateEngine();
dynamic py = pyEngine.ExecuteFile(@"test.py");
// 调用Python函数
int[] array = new int[] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string result = py.main(array);
Console.WriteLine(result);
}
}
}
三、使用Python.NET(双向互操作)
支持C#与Python双向调用,适用于需要复杂交互的场景,需安装Python.NET包。
示例代码:
using Python.Runtime;
using System;
namespace ClassLibraryPython
{
public static class PythonInterpreter
{
private static bool _isInitialized = false;
public static void Initialize()
{
if (!_isInitialized)
{
Python.CreateEngine();
_isInitialized = true;
}
}
public static object CallPythonFunction(string functionName, params object[] args)
{
using (Python.GIL())
{
dynamic py = Python.CreateEngine().ExecuteFile("test.py");
return py[functionName](args);
}
}
}
}
四、网络通信(HTTP/Socket)
适用于远程调用Python服务,通过HTTP请求或WebSocket实现跨平台交互。
示例代码: