动态获取命令行输出

时间:2012-10-01 17:54:27

标签: c# command-line

我在c#中使用命令行运行一个程序,这个程序产生一些日志,而它运行时需要在它发生变化时显示这些日志。我写了下面的代码,但它显示了进程被杀死后的所有日志,并且在运行期间我的程序没有响应。我该如何解决?

问候

ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "C:\\server.py");
Process proc = new Process();
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
procStartInfo.UseShellExecute = false;
procStartInfo.RedirectStandardOutput = true;
//procStartInfo.CreateNoWindow = true;
proc.StartInfo = procStartInfo;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit(300);
LogstextBox.Text = output;

编辑: 好吧,我尝试使用OutputDataReceived,但它没有显示任何结果,这里是更改的代码:

{
            //processCaller.FileName = @"ping";
            //processCaller.Arguments = "4.2.2.4 -t"; this is working
            processCaller.FileName = @"cmd.exe";
            processCaller.Arguments = "/c c:\\server.py"; //this is not working
            processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
            processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
            processCaller.Completed += new EventHandler(processCompletedOrCanceled);
            processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
            this.richTextBox1.Text = "Server Started.." + Environment.NewLine;
            processCaller.Start();
    }

    private void writeStreamInfo(object sender, DataReceivedEventArgs e)
    {
        this.richTextBox1.AppendText(e.Text + Environment.NewLine);
    }

2 个答案:

答案 0 :(得分:22)

这是问题所在:

string output = proc.StandardOutput.ReadToEnd();

在进程终止之前,您将无法进入标准输出的“结束”。

您应该一次阅读一行 - 或者可能只是订阅OutputDataReceived事件(并遵循该事件记录的其他要求)。

编辑:这是适用于我的示例代码:

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    public static void Main()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c " + "type Test.cs")
        {
            WindowStyle = ProcessWindowStyle.Hidden,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        };

        Process process = Process.Start(startInfo);
        process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
        process.BeginOutputReadLine();
        process.WaitForExit();
        // We may not have received all the events yet!
        Thread.Sleep(5000);
    }
}

请注意,在您的示例代码中,您正在访问调用OutputDataReceived处理程序的任何线程上的UI - 这对我来说是个坏主意。

答案 1 :(得分:3)

您可以使用Process.BeginOutputReadLine Method。该链接在C#中显示了一个使用OutputDataReceived event的完整工作示例。该代码示例应该做你想要的。