From 4f72c0799305243ec0734afb41bdaf7a89f1469e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A7=E7=9F=B3=E5=A4=B4?= Date: Fri, 19 Jul 2024 16:46:05 +0800 Subject: [PATCH] =?UTF-8?q?[feat]=E6=96=B0=E5=A2=9EStringHelper.Execute?= =?UTF-8?q?=EF=BC=8C=E6=89=A7=E8=A1=8C=E5=91=BD=E4=BB=A4=E5=B9=B6=E7=AD=89?= =?UTF-8?q?=E5=BE=85=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NewLife.Core/Common/MachineInfo.cs | 39 +++-------------------- NewLife.Core/Extension/StringHelper.cs | 43 ++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 37 deletions(-) diff --git a/NewLife.Core/Common/MachineInfo.cs b/NewLife.Core/Common/MachineInfo.cs index 9c915ab57..c17125dce 100644 --- a/NewLife.Core/Common/MachineInfo.cs +++ b/NewLife.Core/Common/MachineInfo.cs @@ -316,7 +316,7 @@ private void LoadWindowsInfo() } } #else - str = Execute("reg", @"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid"); + str = "reg".Execute(@"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid", 0, false); if (!str.IsNullOrEmpty() && str.Contains("REG_SZ")) Guid = str.Substring("REG_SZ", null).Trim(); var csproduct = ReadWmic("csproduct", "Name", "UUID", "Vendor"); @@ -825,7 +825,7 @@ public void RefreshSpeed() var sr = "/etc/os-release"; if (TryRead(sr, out value)) return value?.SplitAsDictionary("=", "\n", true)["PRETTY_NAME"].Trim(); - var uname = Execute("uname", "-sr")?.Trim(); + var uname = "uname".Execute("-sr", 0, false)?.Trim(); if (!uname.IsNullOrEmpty()) { // 支持Android系统名 @@ -906,40 +906,9 @@ private static Boolean TryRead(String fileName, [NotNullWhen(true)] out String? return dic; } - private static String? Execute(String cmd, String? arguments = null) - { - try - { -#if DEBUG - if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Execute({0} {1})", cmd, arguments); -#endif - - var psi = new ProcessStartInfo(cmd, arguments ?? String.Empty) - { - // UseShellExecute 必须 false,以便于后续重定向输出流 - UseShellExecute = false, - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - RedirectStandardOutput = true, - //RedirectStandardError = true, - }; - var process = Process.Start(psi); - if (process == null) return null; - - if (!process.WaitForExit(3_000)) - { - process.Kill(); - return null; - } - - return process.StandardOutput.ReadToEnd(); - } - catch { return null; } - } - private static IDictionary? ReadCommand(String cmd, String? arguments = null) { - var str = Execute(cmd, arguments); + var str = cmd.Execute(arguments, 0, false); if (str.IsNullOrEmpty()) return null; return str.SplitAsDictionary(":", "\n", true); @@ -955,7 +924,7 @@ public static IDictionary ReadWmic(String type, params String[] var dic2 = new Dictionary(StringComparer.OrdinalIgnoreCase); var args = $"{type} get {keys.Join(",")} /format:list"; - var str = Execute("wmic", args)?.Trim(); + var str = "wmic".Execute(args, 0, false)?.Trim(); if (str.IsNullOrEmpty()) return dic2; var ss = str.Split("\r\n"); diff --git a/NewLife.Core/Extension/StringHelper.cs b/NewLife.Core/Extension/StringHelper.cs index 0f308a1ba..a86384da6 100644 --- a/NewLife.Core/Extension/StringHelper.cs +++ b/NewLife.Core/Extension/StringHelper.cs @@ -980,7 +980,7 @@ public static String SpeakAsyncCancelAll(this String value) /// 进程退出代码 public static Int32 Run(this String cmd, String? arguments = null, Int32 msWait = 0, Action? output = null, Action? onExit = null, String? working = null) { - if (XTrace.Debug) XTrace.WriteLine("Run {0} {1} {2}", cmd, arguments, msWait); + if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Run {0} {1} {2}", cmd, arguments, msWait); // 修正文件路径 var fileName = cmd; @@ -1039,7 +1039,7 @@ public static Int32 Run(this String cmd, String? arguments = null, Int32 msWait /// public static Process ShellExecute(this String fileName, String? arguments = null, String? workingDirectory = null) { - if (XTrace.Debug) XTrace.WriteLine("ShellExecute {0} {1} {2}", fileName, arguments, workingDirectory); + if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("ShellExecute {0} {1} {2}", fileName, arguments, workingDirectory); //// 修正文件路径 //if (!Path.IsPathRooted(fileName) && !workingDirectory.IsNullOrEmpty()) fileName = workingDirectory.CombinePath(fileName); @@ -1055,5 +1055,44 @@ public static Process ShellExecute(this String fileName, String? arguments = nul return p; } + + /// 执行命令并等待返回 + /// 命令 + /// 命令参数 + /// 等待退出的时间。默认0毫秒不等待 + /// 没有标准输出时,是否返回错误内容。默认false + /// + public static String? Execute(this String cmd, String? arguments = null, Int32 msWait = 0, Boolean returnError = false) + { + try + { + if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Execute {0} {1}", cmd, arguments); + + var psi = new ProcessStartInfo(cmd, arguments ?? String.Empty) + { + // UseShellExecute 必须 false,以便于后续重定向输出流 + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + RedirectStandardOutput = true, + //RedirectStandardError = true, + StandardOutputEncoding = Encoding.UTF8, + }; + var process = Process.Start(psi); + if (process == null) return null; + + if (msWait > 0 && !process.WaitForExit(msWait)) + { + process.Kill(); + return null; + } + + var rs = process.StandardOutput.ReadToEnd(); + if (rs.IsNullOrEmpty() && returnError) rs = process.StandardError.ReadToEnd(); + + return rs; + } + catch { return null; } + } #endregion } \ No newline at end of file