如何打印出子进程使用C#打印的值?

pro*_*eek 0 c# subprocess interprocess

正如问到这个职位,我可以使用Python subprocess.Popen()函数来运行Ruby的代码打印出来的值.

import subprocess
import sys

cmd = ["ruby", "/Users/smcho/Desktop/testit.rb"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
    print line, 
    sys.stdout.flush() 
p.wait()
Run Code Online (Sandbox Code Playgroud)

我怎么能用C#做同样的事情?如何打印子进程打印出来的值?

Mar*_*ell 6

在生成子进程时需要重定向stdout; MSDN有一个完整的例子:http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx

(来自MSDN):

 // Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();
Run Code Online (Sandbox Code Playgroud)