欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#执行外部命令示例分享

程序员文章站 2024-02-18 22:35:52
复制代码 代码如下:string command = @"python test.py";string output = execute.run(command);cons...

复制代码 代码如下:

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;
        }
    }
}