BOB/Command/CommandApplication.cs
2025-11-17 13:12:15 +08:00

269 lines
8.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Common.Attributes;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Command
{
[BOBCommand]
public static class CommandApplication
{
/// <summary>
/// 打开外部应用程序
/// </summary>
/// <param name="route">程序路径</param>
/// <param name="waitShutdown">是否等待关闭</param>
/// <param name="AdminRun">是否请求管理员运行</param>
public static void OpenApplication(string route, bool waitShutdown, bool AdminRun)
{
// 创建一个新的进程实例
Process process = new Process();
try
{
// 指定要启动的程序路径
process.StartInfo.FileName = route;
// 指定是否等待程序关闭
process.StartInfo.UseShellExecute = !waitShutdown;
if (AdminRun) process.StartInfo.Verb = "runas";
// 启动程序
process.Start();
// 如果需要等待程序关闭,则等待程序退出
if (waitShutdown)
{
process.WaitForExit();
}
}
catch (Exception ex)
{
Console.WriteLine("错误!: " + ex.Message);
}
finally
{
// 确保进程对象被释放
process.Dispose();
}
}
/// <summary>
/// 使用默认方式打开一个文件
/// </summary>
/// <param name="route">文件路径</param>
public static void OpenFile(string route)
{
// 创建一个新的进程实例
Process process = new Process();
try
{
// 指定要启动的程序路径
process.StartInfo.FileName = route;
process.StartInfo.UseShellExecute = true;
// 启动程序
process.Start();
}
catch (Exception ex)
{
Console.WriteLine("错误!: " + ex.Message);
}
finally
{
// 确保进程对象被释放
process.Dispose();
}
}
// Python引擎相关字段
private static Process _pythonProcess;
private static string _pythonPath = string.Empty;
private static bool _isPythonEngineInitialized = false;
/// <summary>
/// 初始化python引擎
/// </summary>
/// <param name="py路径">Python解释器路径</param>
public static void Initialization_Python(string py路径)
{
try
{
// 验证Python路径是否存在
if (string.IsNullOrEmpty(py路径) || !File.Exists(py路径))
{
throw new FileNotFoundException($"Python解释器路径不存在: {py路径}");
}
// 验证是否为Python可执行文件
var fileInfo = new FileInfo(py路径);
if (!fileInfo.Name.ToLower().Contains("python"))
{
Console.WriteLine("警告: 指定的文件可能不是Python解释器");
}
// 测试Python是否能正常运行
var testProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = py路径,
Arguments = "--version",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
testProcess.Start();
testProcess.WaitForExit(5000); // 5秒超时
if (testProcess.ExitCode != 0)
{
throw new InvalidOperationException($"Python解释器验证失败退出码: {testProcess.ExitCode}");
}
_pythonPath = py路径;
_isPythonEngineInitialized = true;
Console.WriteLine($"Python引擎初始化成功版本: {testProcess.StandardOutput.ReadToEnd().Trim()}");
}
catch (Exception ex)
{
_isPythonEngineInitialized = false;
_pythonPath = string.Empty;
Console.WriteLine($"初始化Python引擎失败: {ex.Message}");
throw;
}
}
/// <summary>
/// 运行python脚本
/// </summary>
/// <param name="路径">Python脚本路径</param>
/// <returns>脚本执行结果</returns>
public static string Run_Python_Script(string )
{
if (!_isPythonEngineInitialized)
{
throw new InvalidOperationException("Python引擎未初始化请先调用初始化python引擎");
}
if (string.IsNullOrEmpty() || !File.Exists())
{
throw new FileNotFoundException($"Python脚本路径不存在: {路径}");
}
Process process = null;
try
{
process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = _pythonPath,
Arguments = $"\"{}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
var output = new StringBuilder();
var error = new StringBuilder();
// 设置输出和错误处理
process.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
output.AppendLine(e.Data);
};
process.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
error.AppendLine(e.Data);
};
process.Start();
// 异步读取输出
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
var outputResult = output.ToString().Trim();
var errorResult = error.ToString().Trim();
if (process.ExitCode != 0)
{
throw new InvalidOperationException($"Python脚本执行失败退出码: {process.ExitCode}, 错误: {errorResult}");
}
return string.IsNullOrEmpty(outputResult) ? "执行成功" : outputResult;
}
catch (Exception ex)
{
Console.WriteLine($"运行Python脚本失败: {ex.Message}");
throw;
}
finally
{
process?.Dispose();
}
}
/// <summary>
/// 释放python引擎
/// </summary>
/// <param name="py">Python解释器路径可选用于验证</param>
public static void Release_Python(string py = "")
{
try
{
if (!string.IsNullOrEmpty(py) && py != _pythonPath)
{
Console.WriteLine($"警告: 释放的Python路径与当前初始化路径不匹配");
}
// 如果有正在运行的Python进程尝试终止它
if (_pythonProcess != null && !_pythonProcess.HasExited)
{
try
{
_pythonProcess.Kill();
_pythonProcess.WaitForExit(1000);
}
catch (Exception ex)
{
Console.WriteLine($"终止Python进程时出错: {ex.Message}");
}
}
_pythonPath = string.Empty;
_isPythonEngineInitialized = false;
_pythonProcess = null;
Console.WriteLine("Python引擎已释放");
}
catch (Exception ex)
{
Console.WriteLine($"释放Python引擎失败: {ex.Message}");
throw;
}
}
}
}