form1using Microsoft.VisualBasic.ApplicationServices; // VB应用程序服务本程序实际上没有使用可以删除 using System; // C#基础类 using System.Diagnostics; // Process进程类 using System.Windows.Forms; // WinForms界面 using System.Xml.Linq; // XML操作本程序没有使用可以删除 namespace YOLOTrainTool { public partial class Form1 : Form { // 保存启动的Python进程 Process process; // 窗体构造函数 public Form1() { // 初始化窗体控件 InitializeComponent(); } /// summary /// 点击开始训练 /// /summary private void btnStart_Click(object sender, EventArgs e) { // Python解释器路径 string pythonExe \\Python38\\python.exe; // train.py路径 string script txtScript.Text; // data.yaml路径 string data txtData.Text; // 训练轮数 string epochs txtEpochs.Text; // 组合命令参数 // 最终效果 // python train.py --data xxx.yaml --epochs 100 string args $\{script}\ --data \{data}\ --epochs {epochs}; // 创建启动信息对象 ProcessStartInfo psi new ProcessStartInfo(); // 要启动的程序 psi.FileName pythonExe; // 传递给python的参数 psi.Arguments args; // 不使用Windows Shell启动 psi.UseShellExecute false; // 重定向标准输出 psi.RedirectStandardOutput true; // 重定向错误输出 psi.RedirectStandardError true; // 不弹CMD窗口 psi.CreateNoWindow true; // 创建进程对象 process new Process(); // 设置启动参数 process.StartInfo psi; // Python正常输出事件 process.OutputDataReceived (s, ev) { // 判断是否有输出 if (ev.Data ! null) // 因为不是UI线程所以需要Invoke更新界面 Invoke(new Action(() txtLog.AppendText(ev.Data \r\n))); }; // Python错误输出事件 process.ErrorDataReceived (s, ev) { if (ev.Data ! null) // 红色输出可以自己改RichTextBox实现 Invoke(new Action(() txtLog.AppendText([ERR] ev.Data \r\n))); }; // 启动Python process.Start(); // 开始异步读取标准输出 process.BeginOutputReadLine(); // 开始异步读取错误输出 process.BeginErrorReadLine(); // 日志提示 txtLog.AppendText(训练启动...\r\n); } /// summary /// 点击停止训练 /// /summary private void btnStop_Click(object sender, EventArgs e) { // 判断进程是否存在并且还没退出 if (process ! null !process.HasExited) { // 强制结束Python process.Kill(); // 输出提示 txtLog.AppendText(训练停止\r\n); } } /// summary /// 选择train.py /// /summary private void btnSelectScript_Click(object sender, EventArgs e) { // 文件选择框 OpenFileDialog dlg new OpenFileDialog(); // 过滤Python文件 dlg.Filter Python Files|*.py; // 点击确定 if (dlg.ShowDialog() DialogResult.OK) // 保存路径 txtScript.Text dlg.FileName; } /// summary /// 选择data.yaml /// /summary private void btnSelectData_Click(object sender, EventArgs e) { // 文件选择框 OpenFileDialog dlg new OpenFileDialog(); // 过滤yaml dlg.Filter YAML Files|*.yaml; // 点击确定 if (dlg.ShowDialog() DialogResult.OK) // 保存路径 txtData.Text dlg.FileName; } /// summary /// 选择Python解释器 /// /summary private void btnSelectPython_Click(object sender, EventArgs e) { // 文件选择框 OpenFileDialog dlg new OpenFileDialog(); // 只显示python.exe dlg.Filter Python|python.exe; // 点击确定 if (dlg.ShowDialog() DialogResult.OK) // 保存Python路径 txtPython.Text dlg.FileName; } } }