Linux系统执行命令方法

现在我们无论是工作中还是学习中很多情况下用到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下执行,然后我这里就传入了一个/,拿到执行命令返回的数据

posted @ 2022-05-24 09:11  薛小谦  阅读(592)  评论(1编辑  收藏  举报