0
我想通过在c#控制台应用程序中运行该脚本来检索python脚本的控制台输出。但我不知道我在做什么错,因为我无法读取任何输出。请帮帮我。 这是我的代码示例:试图在c#中捕获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();
}
感谢您的建议,我在尝试更改后提出建议,但它仍不会打印while循环内的内容。所以我试着调试我的程序,并且我意识到它不会进入while循环,但有针对性的Python脚本运行。因为我看到一个在我的任务管理器中运行的python线程,当我从任务管理器中结束这个任务时,我的程序在while循环之后打印了“The End”。你有什么想法,为什么它是这样的..? –
您是否尝试使用ErrorDataReceived事件? – user5195490
我更新了答案,您还需要添加这些行proc.BeginErrorReadLine(); proc.BeginOutputReadLine(); – user5195490