簡體   English   中英

動態獲取命令行輸出

[英]Getting command line output dynamically

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

這就是問題:

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 - 這對我來說是個壞主意。

您可以使用Process.BeginOutputReadLine方法 該鏈接顯示了C#中使用OutputDataReceived event的完整工作示例。 該代碼示例應該做你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM