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

Linux系统执行命令方法的更多相关文章

  1. Android 开发进入Linux系统执行命令 2018-5-25 Fri.

    /** * 进入linux cmd执行命令 * * @param command * @return */ private boolean runRootCommand(String command) ...

  2. 修改linux系统时间的方法(date命令)

    修改linux系统时间的方法(date命令) 来源:互联网 作者:佚名 时间:11-18 23:22:27 [大 中 小] date命令不仅可以显示系统当前时间,还可以用它来修改系统时间,下面简单的介 ...

  3. [转帖]Linux后端执行命令的方法

    Linux 后台执行命令的方法 http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=4241330&fromuid=212883 ...

  4. php 执行计划任务方式之 linux crontab 执行命令

    一.crond简介 crond 是linux下用来周期性的执行某种任务或等待处理某些事件的一个守护进程,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务 工具,并且会自动启动c ...

  5. 查看linux系统版本命令 (转)

    查看linux系统版本命令 分类: Linux 知识小结2011-10-10 15:26 240162人阅读 评论(9) 收藏 举报 linuxredhatdebianx86susesun 一.查看内 ...

  6. Linux系统——awk命令

    awk命令不仅仅是Linux系统的命令,也是一种编程语言,用来处理数据和生成报告(Exel),处理的数据可以是一个或多个文件(标准输入和管道获取标准输入).可在命令行上编辑操作,也可以写成awk程序运 ...

  7. Linux系统ifconfig命令找不到,centos ifconfig Command not found

    centos ifconfig Command not found,Linux系统ifconfig命令找不到 >>>>>>>>>>>& ...

  8. Linux系统基础命令

    这是看itercast的学习笔记 Linux系统基础命令 日期时间 命令date用以查看.设置当前系统时间:格式化显示时间: +%Y--%m--%d 命令hwclock(clock)用以显示硬件时钟时 ...

  9. Linux系统-解压缩命令集合

    Linux系统-解压缩命令集合 linux zip命令 zip -r myfile.zip ./* 将当前目录下的所有文件和文件夹全部压缩成myfile.zip文件,-r表示递归压缩子目录下所有文件. ...

随机推荐

  1. javascript 理解和使用回调函数

    在javascript中,function是内置的类对象,也就是说它是一种类型的对象,可以和其他String.Array.Number.Objec类的对象一样用于内置对象的管理.因为function实 ...

  2. js中的bool值转换及"&&" 、"||"、 "!!"详解

    bool值转换 数据类型 bool值转化 undefined undefined 转化为 false Object null 转化为false,其他为 true Boolean false 转化为 f ...

  3. [computer vision] Bag of Visual Word (BOW)

    Bag of Visual Word (BoW, BoF, 词袋) 简介 BoW 是传统的计算机视觉方法,用一些特征(一些向量)来表示一个图像.BoW的核心思想是利用一组较为通用的特征,将图像用这些特 ...

  4. 【Android开发】APP桌面角标问题

    Demo:https://github.com/baitutang1221/BadgeNumberManager 参考:https://juejin.im/post/59f2e59751882578c ...

  5. 百度图像识别SDK实验

    软件构造实验作业 实验名称:百度图像识别SDK实验 班级:信1905-1      学号:20194171      姓名:常金悦          一. 实验要求 每个步骤必须截图并说明 二.实验步 ...

  6. LC-349

    Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the ...

  7. linux权限与系统信息

    权限 1.权限分为3个部分 可读(r) 可写(w) 可执行(x) 没有对应权限(-) 2.权限位 权限位主要分为三个部分,分别是属主.属组以及其他人 rwx : 属主 r-x : 属组 r-x : 其 ...

  8. Lumia一键刷稳定版 Win10 arm 及其报错处理

    前言 之前我发了一篇Lumia1520 刷Win10 arm双系统的文章,不过后来发现那个方法对小白来说太不友好,且系统也不稳定,所以我找到了更好的方法 刷机 我们可以利用刷机迷进行刷机,支持一键刷机 ...

  9. JVM虚拟机类加载机制(一)

    类从被加载到虚拟机内存中开始,到卸载出内存截止,整个生命周期包括:加载.验证.准备.解析,初始化.使用.卸载七个阶段.其中验证.准备.解析三个部分统称为连接. 类初始化情况: 遇到new.getsta ...

  10. 腾讯云OCR服务二次开发

    本文记录了对腾讯云OCR服务二次开发的代码和开发过程中遇到的问题.