我试图通过在c#console应用程序中运行该脚本来检索python脚本的控制台输出。但我不知道自己做错了什么,因为我无法阅读任何输出。请帮我。 这是我的代码示例:
Process proc = new Process();
try
{
proc.StartInfo.FileName = "C:\\Program Files\\Python36\\python.exe";
proc.StartInfo.Arguments = "\"E:/Database/Python Scripts/TestFile.py\" \"E:/Database/Testing.db\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.EnableRaisingEvents = true;
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
Console.WriteLine("line:" + line);
}
Console.WriteLine("The End");
Console.ReadLine();
}
catch(Exception ex)
{
Console.WriteLine("Error:{0}, Detail: {1}", ex.Message, ex.StackTrace);
Console.ReadLine();
}
finally
{
//Console.ReadLine();
proc.Close();
proc.Dispose();
}
答案 0 :(得分:0)
首先你需要设置proc.StartInfo.RedirectStandardOutput = false;为真 那么你需要监听输出事件
proc.StartInfo.FileName = "C:\\Program Files\\Python36\\python.exe";
proc.StartInfo.Arguments = "\"E:/Database/Python Scripts/TestFile.py\" \"E:/Database/Testing.db\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.EnableRaisingEvents = true;
proc.OutputDataReceived+= ProcessOutputHandler;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
private void ProcessOutputHandler(object sender, DataReceivedEventArgs e)
{
//get the data using e.Data
}
您可以为ErrorOutput执行相同的操作,因为它们是您可以获得的单独流。要监听错误,只需为proc.ErrorDataReceived+= ProcessErrorOutputHandler;