本文介绍了如何处理使用控制字符的控制台应用程序的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个可执行文件(在我的例子中,这是PNGOUT.exe),并抓住它的输出从stdout。但事实证明是棘手的 - 应用程序使用某种控制字符替换以前打印的输出(显示进度),C#类愉快地记录它们,当我想分析输出字符串,我会严重头痛。 (我甚至需要一段时间来弄清楚我的字符串发生了什么)

I want to call an executable (in my case, this is PNGOUT.exe) and grab its output from stdout. But it turned out to be tricky - the application uses some sort of control characters to replace previously printed output (display of progress), and C# classes happily record them and when I want to analyze the output string, I get serious headache. (It even took a while for me to figure out what's happening with my string)

我使用以下方法调用可执行文件:

I'm calling executable with following method:

public static string RunPNGOut(string pngOutPath, string target) {
   var process = new Process {
      StartInfo = {
         UseShellExecute = false,
         RedirectStandardOutput = true,
         CreateNoWindow = true,
         FileName = pngOutPath,
         Arguments = '"' + target + '"'
      }
   };
   process.Start();

   var result = process.StandardOutput.ReadToEnd();

   process.WaitForExit();

   return result;
}



我需要使用不同的方法捕获控制台中的最终文本状态,或者以某种方式摆脱 result 中的控制字符(不是简单地删除它们,而是应用它们到字符串以实现最终的外观)。

I need either use different method that captures only final state of text in console, or somehow get rid of control characters in result(not simply delete them, but "apply" them to string to achieve the final look). How can it be done?

推荐答案

最有可能的是,输出包含\r,它只是将游标返回到当前行。如果这是真的,那么您可以通过擦除当前行相应地调整字符串。这不简单,但是 - 你还必须覆盖上一行。我将处理一些代码,看看是否可以得到一个解决方案。

Most likely, the output contains \r, which simply returns the cursor to the beginning of the current line. If that's true, then you can adjust the string accordingly by erasing the current line. It's not simple, though - you have to also overwrite the previous line. I'll work on some code and see if I can arrive at a solution.

EDIT:这里是我想出的解决方案 - 轻轻测试。输出将在变量中,您可以单独分析或连接在一起分析为一行。

Here's the solution I came up with - it's lightly tested. The output will be in the lines variable, which you can either analyze individually or join together to analyze as a single line.

string rawOut = "Results:\r\n___ % done\r 10\r 20\r 30\r\nError!";
string[] lines = Regex.Split(rawOut, Environment.NewLine);
for(int j=0; j<lines.Length; j++)
{
    string line = lines[j];
    if (line.Contains('\r'))
    {
        string[] subLines = line.Split('\r');
        char[] mainLine = subLines[0].ToCharArray();
        for(int i=1; i<subLines.Length; i++)
        {
            string subLine = Regex.Replace(subLines[i], ".\x0008(.)", "$1");
            if (subLine.Length > mainLine.Length) mainLine = subLine.ToCharArray();
            else subLine.CopyTo(0, mainLine, 0, subLine.Length);
        }
        lines[j] = new String(mainLine);
    }
}

这篇关于如何处理使用控制字符的控制台应用程序的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:36