获取命令行输出动态(Getting command line output dynamically)

2019-08-01 01:46发布

我正在使用命令行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);
    }

Answer 1:

这就是问题:

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);
    }
}

请注意,在你的示例代码,你所访问的任何线程的UI OutputDataReceived处理程序被调用-看起来像一个坏主意给我。



Answer 2:

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



文章来源: Getting command line output dynamically