Linux系統執行命令方法
阿新 • • 發佈:2022-05-24
現在我們無論是工作中還是學習中很多情況下用到Linux系統,當我們需要在C#程式碼中呼叫類似與cmd視窗執行命令時候,就需要用到此方法
public static Process CommitCommand(string commandStr, string workingDir, Action<DataReceivedEventArgs> action) { var logger = LogManager.GetCurrentClassLogger(); try { logger.Debug("Get into CommitCommand"); Process process = new Process(); process.StartInfo.FileName = commandStr.Substring(0, commandStr.IndexOf(" ")).Trim(); var pathDir = Environment.GetEnvironmentVariable("PATH").Split(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? ":" : ";", StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault(s => File.Exists(Path.Combine(s, process.StartInfo.FileName)) || File.Exists(Path.Combine(s, process.StartInfo.FileName + ".exe"))); if (string.IsNullOrEmpty(pathDir)) { process.StartInfo.FileName= Path.GetFullPath(process.StartInfo.FileName, workingDir); } process.StartInfo.Arguments = commandStr.Substring(commandStr.IndexOf(" ")).Trim(); process.StartInfo.WorkingDirectory = string.IsNullOrWhiteSpace(workingDir) ? process.StartInfo.WorkingDirectory : workingDir; process.StartInfo.CreateNoWindow = true; process.StartInfo.ErrorDialog = false; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.ErrorDataReceived += (sender, args) => { action(args); logger.Error($"ErrorDataReceived:commandStr:{commandStr}. workingDir:{workingDir}. Error:{args.Data}"); }; process.EnableRaisingEvents = true; process.OutputDataReceived += (sender, args) => { action(args); //logger.Debug($"OutputDataReceived:{args.Data}"); }; process.Exited += (sender, args) => { logger.Debug("程式退出!"); logger.Error($"Exited:commandStr:{commandStr}. workingDir:{workingDir}"); }; process.Start(); process.StandardInput.AutoFlush = true;//process.StandardInput.WriteLine("") process.BeginErrorReadLine(); process.BeginOutputReadLine(); logger.Debug("Sign out CommitCommand"); return process; } catch (Exception e) { logger.Error(e, "process can not start."); logger.Debug(e.Message); return null; } }
呼叫也非常簡單,引數1:執行得命令 引數2:路徑 比如說我們需要執行mysql,就需要在對應資料夾內執行對應命令,這個時候第二個引數就可以傳入路徑
然後我再給出一個呼叫得例子
Process pc = new Process(); pc = ToolClass.CommitCommand("nvidia-smi", "/", args => { if (!string.IsNullOrEmpty(args.Data)) { useGpuNumber.Add(args.Data); } }); pc.WaitForExit(); pc.Dispose();
我這裡時檢視顯示卡也就是GPU得資訊的命令,可以再root下執行,然後我這裡就傳入了一個/,拿到執行命令返回的資料