How to print out the value that subprocess prints with C#?

纵然是瞬间 提交于 2019-12-23 05:15:28

问题


As is asked in this post, I can use Python's subprocess.Popen() function to print out the value from running ruby's code.

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()

How can I do the same thing with C#? How can one print the value what the subprocess prints out?


回答1:


You need to redirect stdout when spawning the child process; MSDN has a complete example: http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx

(from 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();



回答2:


ProcessStartInfo psi = new ProcessStartInfo("ruby", "/Users/smcho/Desktop/testit.rb");
psi.RedirectStandardOuput = true;W    
Process proc = new Process(psi);
proc.Start();
StreamReader stdout = proc.StandardOutput;
string line;
while ((line = stdout.ReadLine()) != null)
   Console.WriteLine(line);


来源:https://stackoverflow.com/questions/4977571/how-to-print-out-the-value-that-subprocess-prints-with-c

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