C# 如何打印出子流程用C打印的值?
正如本文所要求的,我可以使用Python的subprocess.Popen函数打印出运行ruby代码的值C# 如何打印出子流程用C打印的值?,c#,subprocess,interprocess,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.st
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()
我如何用C做同样的事情?如何打印子进程打印出的值?生成子进程时需要重定向标准输出;MSDN有一个完整的例子: 从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();
您需要研究从进程对象重定向标准输出。接受的答案显示了如何异步执行。
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);