整体代码,后面开始逐步解释
简单来说整体思路是创建一个新的进程,然后我们在这个进程中调用Python解释器(python.exe)以及想要运行的Python程序(.py文件)实现Python程序的运行
string pythonPath = @"..\debug\envs\testenv\python.exe";
string scriptPath = @"..\debug\envs\AutoOffset\CalcOffsetData.py";
string scriptArguments = "arg1 arg2";
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = pythonPath,
Arguments = $"{scriptPath} {scriptArguments}",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (Process process = new Process { StartInfo = psi })
{
process.Start();
process.WaitForExit();
string standardErrorOutput = process.StandardError.ReadToEnd();
}
第一步
string pythonPath = @"..\debug\envs\testenv\python.exe";
string scriptPath = @"..\debug\envs\AutoOffset\CalcOffsetData.py";
string scriptArguments = "arg1 arg2";
确定Python解释器以及想要运行的.py文件的路径,以及需要传递的参数arg1,arg2(没有可以不加这一行),将Python解释器路径保存在pythonPath字段,.py文件的路径保存在scriptPath字段,需要传递的参数路径保存在scriptArguments字段
第二步
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = pythonPath,
Arguments = $"{scriptPath} {scriptArguments}",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
这里是为后面创建的进程做准备,相当于是配置我们的进程参数,ProcessStartInfo 是一个在 C# 中用于配置和启动新进程的类,里面包含的诸多属性就是用来配置进程的。
FileName是这是要启动的可执行文件的路径。也就是第一步中我们的python.exe。
Arguments:是要传递给启动的可执行文件的命令行参数。同样,如果没有需要传递的参数可以把scriptArguments删除
UseShellExecute: 这个属性控制是否使用操作系统的外壳来启动进程。将其设置为 false 可以在不使用外壳的情况下启动进程。
RedirectStandardOutput 和 RedirectStandardError: 这两个属性指示是否将进程的标准输出和标准错误重定向到程序中,可以捕获并处理它们的输出。
CreateNoWindow: 将此属性设置为 true 会阻止创建新的窗口来承载新的进程。
第三步
using (Process process = new Process { StartInfo = psi })
{
process.Start();
process.WaitForExit();
string standardErrorOutput = process.StandardError.ReadToEnd();
}
通过Process类创建一个新的进程,并且将我们第二步中配置好的运行参数psi放进去。使用using 语句来创建一个 Process 对象,这是为了确保在使用完之后释放资源。一旦代码块结束,Process 对象将自动被释放,这样可以避免资源泄漏。
Start 方法:这里调用 Start 方法来启动之前配置好的进程。进程将在后台开始运行。
WaitForExit 方法:这个方法会阻塞当前线程,直到启动的进程完成为止。也就是说,程序将等待进程执行完毕,然后再继续执行下面的代码。如果不等待的话,会在Pyhton程序没有结束前就结束该进程
最后一行是在程序输出中显示进程中Pyhton程序运行出现的错误
注意,注意,注意
Python版本会非常影响运行速度的快慢,如果是Python 3.6版本运行需要4分钟的话,使用Python 3.11 可能只需要8秒。所以如果进程运行非常缓慢可以尝试更换Python版本。