Python脚本输出使用C#redirect

这个问题可能看起来像重复,我已经尝试了所有build议的解决scheme,但徒劳无功,我想使用此代码redirectpython脚本输出:

System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "python.exe"; proc.StartInfo.Arguments = Application.StartupPath.Replace("\\bin\\Debug", "") + "\\scripts\\test.py"; proc.OutputDataReceived += OutputDataReceived; proc.ErrorDataReceived += ErrorDataReceived; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.Start(); //proc.WaitForExit(); StringBuilder q = new StringBuilder(); while (!proc.HasExited) { q.Append(proc.StandardOutput.ReadToEnd()); } string r = q.ToString(); r = proc.StandardOutput.ReadToEnd(); MessageBox.Show(r); } private void OutputDataReceived(object sender, DataReceivedEventArgs args) { //textOutput.Text += args.Data; MessageBox.Show(args.Data); } 

python脚本包含print "hello test"我试图unbuffering输出,但徒然。

请任何帮助。

我正在使用VS 2010 .NET 4.0,Python 2.7,winXP sp3。

Solutions Collecting From Web of "Python脚本输出使用C#redirect"

尝试创建一个StreamReader实例,而不是StringBuilder。 这段代码对我来说很好:

  System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "ping.exe"; proc.StartInfo.Arguments = "8.8.8.8"; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.Start(); StreamReader q = proc.StandardOutput; while (!proc.HasExited) Console.WriteLine(q.ReadLine()); Console.ReadKey();