Process.start : 출력을 얻는 방법? .NET 앱에서 외부 명령 줄 프로그램을 실행하고

Mono / .NET 앱에서 외부 명령 줄 프로그램을 실행하고 싶습니다. 예를 들어 mencoder 를 실행하고 싶습니다 . 가능합니까?

  1. 명령 행 쉘 출력을 가져 와서 텍스트 상자에 쓰려면?
  2. 시간이 경과하면서 진행률 표시 줄을 표시하는 숫자 값을 얻으려면?


답변

Process객체 세트를 StartInfo적절하게 만들 때 :

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

그런 다음 프로세스를 시작하고 읽습니다.

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

int.Parse()또는 int.TryParse()문자열을 사용하여 숫자 값으로 변환 할 수 있습니다 . 읽은 문자열에 유효하지 않은 숫자가 있으면 먼저 문자열을 조작해야 할 수도 있습니다.


답변

출력을 동기식 또는 비동기식으로 처리 할 수 ​​있습니다 .

1. 동기 예

static void runCommand()
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    //* Read the output (or the error)
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    string err = process.StandardError.ReadToEnd();
    Console.WriteLine(err);
    process.WaitForExit();
}

참고 이 모두 처리하는 것이 좋습니다 것을 출력오류 : 그들은 개별적으로 처리해야합니다.

(*) 일부 명령 (여기서는 StartInfo.Arguments)에 /c 지시문을 추가해야합니다. 그렇지 않으면 프로세스가에서 정지됩니다 WaitForExit().

2. 비동기 예

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

출력과 복잡한 작업을 수행 할 필요가없는 경우 처리기를 직접 인라인으로 추가하기 만하면 OutputHandler 메서드를 무시할 수 있습니다.

//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);

답변

자, 오류와 출력을 모두 읽고 싶지만 다른 답변 (예 : 나와 같은)에서 제공되는 솔루션 중 하나를 사용하여 교착 상태 를 얻는 사람 은 여기 MSDN StandardOutput속성 설명을 읽은 후에 작성한 솔루션입니다 .

답변은 T30의 코드를 기반으로합니다.

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set ONLY ONE handler here.
    process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHandler);
    //* Start process
    process.Start();
    //* Read one element asynchronously
    process.BeginErrorReadLine();
    //* Read the other one synchronously
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    process.WaitForExit();
}

static void ErrorOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

답변

이를 수행하는 표준 .NET 방법은 프로세스의 StandardOutput 스트림 에서 읽는 것 입니다. 연결된 MSDN 문서에 예가 있습니다. 마찬가지로, 당신은 읽을 수 StandardError 및 쓰기 StandardInput .


답변

  1. 여기에 설명 된대로 프로세스의 명령 행 쉘 출력을 얻을 수 있습니다. http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx

  2. 이것은 mencoder에 따라 다릅니다. 명령 행에서이 상태를 출력하면 yes 🙂


답변

두 프로세스가 공유 메모리를 사용하여 통신하고 체크 아웃 할 수 있습니다. MemoryMappedFile

주로 mmf“using”문을 사용하여 부모 프로세스에서 메모리 매핑 된 파일 을 만든 다음 종료 될 때까지 두 번째 프로세스를 만들고 mmfusing에 결과를 쓴 BinaryWriter다음 mmf부모 프로세스를 사용하여 결과를 읽습니다. 통과mmf 명령 행 인수를 사용 이름을 전달하거나 하드 코딩하십시오.

상위 프로세스에서 맵핑 된 파일을 사용할 때 맵핑 된 파일이 상위 프로세스에서 릴리스되기 전에 하위 프로세스가 맵핑 된 파일에 결과를 쓰도록하십시오.

예 : 부모 프로세스

    private static void Main(string[] args)
    {
        using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("memfile", 128))
        {
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(512);
            }

            Console.WriteLine("Starting the child process");
            // Command line args are separated by a space
            Process p = Process.Start("ChildProcess.exe", "memfile");

            Console.WriteLine("Waiting child to die");

            p.WaitForExit();
            Console.WriteLine("Child died");

            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("Result:" + reader.ReadInt32());
            }
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

아동 과정

    private static void Main(string[] args)
    {
        Console.WriteLine("Child process started");
        string mmfName = args[0];

        using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mmfName))
        {
            int readValue;
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("child reading: " + (readValue = reader.ReadInt32()));
            }
            using (MemoryMappedViewStream input = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(input);
                writer.Write(readValue * 2);
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

이 샘플을 사용하려면 내부에 2 개의 프로젝트가있는 솔루션을 작성한 다음 % childDir % / bin / debug에서 하위 프로세스의 빌드 결과를 가져 와서 % parentDirectory % / bin / debug에 복사 한 다음 부모 프로젝트

childDir그리고 parentDirectoryPC 행운에 프로젝트의 폴더 이름입니다 🙂


답변

프로세스 (bat 파일, perl 스크립트, 콘솔 프로그램 등)를 시작하고 표준 출력을 Windows 형식으로 표시하는 방법 :

processCaller = new ProcessCaller(this);
//processCaller.FileName = @"..\..\hello.bat";
processCaller.FileName = @"commandline.exe";
processCaller.Arguments = "";
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
// processCaller.Failed += no event handler for this one, yet.

this.richTextBox1.Text = "Started function.  Please stand by.." + Environment.NewLine;

// the following function starts a process and returns immediately,
// thus allowing the form to stay responsive.
processCaller.Start();    

ProcessCaller이 링크에서 찾을 수 있습니다 : 프로세스 시작 및 표준 출력 표시