本文介绍了使用C#进行Python脚本输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题似乎是重复的,我已经尝试了所有建议的解决方案,但是徒然,我想使用此代码重定向python脚本输出:
this question could seem as duplicate, i have tried all the suggested solution but in vain , i wanna redirect python script output using this code :
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"
,但我尝试取消缓冲输出却徒劳.
the python script contains print "hello test"
i tried unbuffering output but vainly.
请帮忙.
我正在使用VS 2010 .NET 4.0,Python 2.7,winXP sp3.
I'm using VS 2010 .NET 4.0 , Python 2.7 , winXP sp3.
推荐答案
尝试创建StreamReader实例而不是StringBuilder.这段代码对我来说很好:
Try to create a StreamReader instance instead of StringBuilder.this code works for me just fine:
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();
这篇关于使用C#进行Python脚本输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!