c#執(zhí)行外部命令示例分享
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;
}
}
}
相關(guān)文章
C#結(jié)合JS解決Word添加無效位圖導(dǎo)致進(jìn)程停滯的問題
這篇文章主要為大家詳細(xì)介紹了C#如何結(jié)合JS解決Word添加無效位圖導(dǎo)致進(jìn)程停滯的問題,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
C#設(shè)置軟件開機(jī)自動運(yùn)行的方法(修改注冊表)
這篇文章主要介紹了C#設(shè)置軟件開機(jī)自動運(yùn)行的方法,通過簡單修改注冊表開機(jī)啟動項實(shí)現(xiàn)軟件的開機(jī)啟動功能,非常簡單實(shí)用,需要的朋友可以參考下2016-06-06
C#實(shí)現(xiàn)自動識別URL網(wǎng)址的方法
這篇文章主要介紹了C#實(shí)現(xiàn)自動識別URL網(wǎng)址的方法,涉及C#操作URL地址的相關(guān)技巧,需要的朋友可以參考下2015-05-05

