How can I copy the stdout of a process (copy, not redirect)?

安稳与你 提交于 2019-12-20 03:26:30

问题


there are a lot of examples that show how to redirect the stdout of another application. However I would like to let the application keep its stdout and only retrieve a copy of the stdout in my parent process. Is this possible?

My scenario: I have some tests (using Visual Studio Test Runner) which start an external process (server) to do their testing. The server outputs a lot of useful debug information in its stdout which I would like to include in my test results.

I can capture the process output and output it via Trace.WriteLine to let it show up in the test details later. However it would be nice to see the server window with its output while the test is running to see the current progress (test can be running a long time).

So I'm looking for ways to copy this information instead of simply redirecting it.

Any ideas?


回答1:


What about writing a small program that forwards STDIN to STDOUT, while at the same time doing something else with it as well?

You could then replace the command that starts the server process with one that starts it and pipes its output to the above utility. That way you 'll have both programmatic access to the output and see it in real time in the output window.




回答2:


Would this work for you?

        var outputText = new StringBuilder();
        var errorText = new StringBuilder();

        using (var process = Process.Start(new ProcessStartInfo(
            @"YourProgram.exe",
            "arguments go here")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false
            }))
        {
            process.OutputDataReceived += (sendingProcess, outLine) =>
            {
                outputText.AppendLine(outLine.Data); // capture the output
                Console.Out.WriteLine(outLine.Data); // echo the output
            }

            process.ErrorDataReceived += (sendingProcess, errorLine) =>
            {
                errorText.AppendLine(errorLine.Data); // capture the error
                Console.Error.WriteLine(errorLine.Data); // echo the error
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            // At this point, errorText and outputText StringBuilders
            // have the captured text.  The event handlers already echoed the
            // output back to the console.
        }


来源:https://stackoverflow.com/questions/7850352/how-can-i-copy-the-stdout-of-a-process-copy-not-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!