c#执行外部命令示例分享
时间:2023-10-18 15:30:20
String Command = @"python test.py";
String Output = Execute.run(Command);
Console.WriteLine(Output);
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//using before change the namespace
namespace test.utility
{
class Execute
{
public static String run(String Command)
{
String Output = null;
if (Command != null && !Command.Equals(""))
{
Process process = new Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = "cmd.exe";
//no create the cmd windows
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;
process.StartInfo = processStartInfo;
try
{
process.Start();
process.StandardInput.WriteLine(Command);
process.StandardInput.WriteLine("exit");
process.WaitForExit(30 * 1000);
Output = process.StandardOutput.ReadToEnd();
}
catch (Exception e)
{
process.Close();
return e.ToString();
}
finally
{
process.Close();
}
}
return ContextFilter(Output);
}
public static String ContextFilter(String Output)
{
Regex regex_end = new Regex("^[^^]*#end");
Match match = regex_end.Match(Output);
Regex regex_begin = new Regex("^[^^]*?#begin\r\n");
String result = regex_begin.Replace(match.Value, "");
Regex regex_tar = new Regex("\r\n#end$");
result = regex_tar.Replace(result,"");
return result;
}
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
微信跳一跳辅助Java代码实现
Kotlin入门教程之开发环境搭建
![](https://img.aspxhome.com/file/2023/6/125346_0s.png)
C#实现给图片添加日期信息的示例详解
![](https://img.aspxhome.com/file/2023/2/84462_0s.png)
WPF实现自带触控键盘的文本框
![](https://img.aspxhome.com/file/2023/2/113792_0s.png)
Spring学习教程之AOP模块的概述
![](https://img.aspxhome.com/file/2023/7/91747_0s.jpg)
java自定义异常打印内容详解
![](https://img.aspxhome.com/file/2023/2/77082_0s.jpg)
Java接口DAO模式代码原理及应用详解
![](https://img.aspxhome.com/file/2023/0/72570_0s.png)
c语言动态数组示例
C# 遍历枚举类型的所有元素
Java中对象的深复制(深克隆)和浅复制(浅克隆)介绍
使用spring框架中的组件发送邮件功能说明
![](https://img.aspxhome.com/file/2023/1/63341_0s.png)
使用logback实现按自己的需求打印日志到自定义的文件里
C++中的auto_ptr智能指针的作用及使用方法详解
Java ArrayList中存放引用数据类型的方式
![](https://img.aspxhome.com/file/2023/6/60556_0s.png)
Java实现简单学生管理系统
![](https://img.aspxhome.com/file/2023/1/69901_0s.png)
C++异步操作future和aysnc与function和bind
![](https://img.aspxhome.com/file/2023/3/124013_0s.webp)
C#实现保存文件时重名自动生成新文件的方法
SpringTask实现定时任务方法讲解
![](https://img.aspxhome.com/file/2023/1/62681_0s.png)
C++ 线程(串行 并行 同步 异步)详解
![](https://img.aspxhome.com/file/2023/4/124014_0s.png)
谈谈变量命名规范的重要性
![](https://img.aspxhome.com/file/2023/9/81259_0s.png)