Execute Python Script in C#: Step-by-Step
You can use Python’s standard library Process to call a Python script in C#. Here is a simple example code:
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
string pythonExe = @"C:\Python\Python38\python.exe"; // Python解释器的路径
string script = @"C:\path\to\your\script.py"; // Python脚本的路径
Process process = new Process();
process.StartInfo.FileName = pythonExe; // 指定Python解释器的路径
process.StartInfo.Arguments = script; // 指定要执行的Python脚本的路径
process.StartInfo.UseShellExecute = false; // 不使用Shell执行
process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
process.StartInfo.CreateNoWindow = true; // 不创建新窗口
process.Start(); // 启动进程
string output = process.StandardOutput.ReadToEnd(); // 读取标准输出
process.WaitForExit(); // 等待进程执行完毕
int exitCode = process.ExitCode; // 获取进程的退出码
Console.WriteLine("Output:");
Console.WriteLine(output);
Console.WriteLine("Exit Code: {0}", exitCode);
Console.ReadLine();
}
}
In the code above, you need to replace pythonExe with the path of the Python interpreter and script with the path of the Python script to be executed. Then, use Process to start a Python process and redirect the standard output to be retrieved in C#.
Before using Process to call a Python script, make sure you have installed the Python interpreter and added it to the system’s environment variables.