繁体   English   中英

在QProcess输出中保留ANSI转义序列

[英]Keep ANSI Escape Sequences in QProcess Output

我正在创建一个程序,在其中启用了C ++ 11的Ubuntu 16.04 Qt 5.5.1上使用QProcess框架在Qt中运行进程。 我将流程输出流定向到QTextEdit。

我想将此输出着色为使用与本机终端通过嵌入的ANSI转义颜色序列解释的相同的颜色。 但是,我无法解析转义序列,因为QProcess输出中似乎缺少这些转义序列。 我本来以为QString会剥离它们,但是经过一些测试后,我认为情况并非如此。

如果可以将转义序列保留在QProcess输出中,则我发现了一些信息,可将我指向ANSI转义颜色解释方向。

这是我在Qt代码中所做的示例项目。

源文件...

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QProcess>
#include <QStringList>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStringList input = {"gcc will_not_build.c"};
    QProcess * proc = new QProcess();

    proc->setReadChannel(QProcess::StandardOutput);
    proc->setProcessChannelMode(QProcess::MergedChannels);
    proc->setWorkingDirectory("/path/to/test/c/file/");

    //Start bash
    proc->start("bash");
    proc->waitForStarted();

    // Write as many commands to this process as needed
    foreach(QString str, input){
        proc->write(str.toUtf8() + "\n");
        proc->waitForBytesWritten(-1);
    }

    // Let bash close gracefully
    proc->write("exit $?\n");
    proc->waitForBytesWritten(-1);

    proc->closeWriteChannel();
    proc->waitForFinished();
    proc->waitForReadyRead();

    QByteArray read_data = proc->readAll();

    // The use of tr(read_data) also works here.
    QString output = tr(read_data);//QString::fromStdString (read_data.toStdString ());

    proc->closeReadChannel(QProcess::StandardOutput);

    proc->close();
    delete proc;

    // Add the output to the text box
    ui->textEdit->append (output);
}

MainWindow::~MainWindow()
{
    delete ui;
}

头文件...

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H 

表单文件...

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QTextEdit" name="textEdit">
    <property name="geometry">
     <rect>
      <x>33</x>
      <y>19</y>
      <width>331</width>
      <height>211</height>
     </rect>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>19</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

C源文件...

int main(){
    // Intentionally will not build
    I will not build :)
}

我的输出如下所示:

QProcess gcc输出

本机Linux终端的输出如下所示:

Linux终端gcc输出颜色

有谁知道如何在QProcess输出中保留ANSI转义颜色序列,以便我可以模拟Linux终端颜色?

附带说明一下,我在Qt Creator源代码中进行了挖掘,并且有一个类可以将ANSI转义颜色转换为Rich Text颜色,因此我知道有人在这方面。 同样,在构建项目时,由于某种原因,Qt Creator不会在其自己的终端中为构建输出着色。

多亏了对我的问题的深刻见解,我才能够找到解决问题的方法。 我会分享...

QProcess也不是错误,也不是QString。 问题出在程序执行的环境中。 由于这些程序(gcc等)的输出未连接到TTY设备,因此将剥离所有ANSI转义序列。 有一种方法可以欺骗输出,使其看起来好像已连接到TTY设备

只需在命令前添加unbuffer即可。

由于我实际上是在创建Qt Creator插件,因此我已经链接了许多Qt Creator源代码。 碰巧的是,已经存在一个名为AnsiEscapeCodeHandler的方便的类,用于将ANSI转义序列转换为QTextCharFormat和相应的ANSI转义序列剥离的字符串。

为了说明如何使用该类,但现在在我的示例中,我将从可下载的Qt Creator源代码中将ansieescapecodehandler.hansiescapecodehandler.cpp复制到测试项目中。 我不得不从AnsiEscapeCodeHandler源文件中删除几行内容,以在其余Qt Creator源代码的上下文之外进行编译,仅此而已。

新的源文件...

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QProcess>
#include <QStringList>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStringList input = {"unbuffer gcc will_not_build.c"};
    QProcess * proc = new QProcess();

    proc->setReadChannel(QProcess::StandardOutput);
    proc->setProcessChannelMode(QProcess::MergedChannels);
    proc->setWorkingDirectory("/path/to/test/c/file/");

    //Start bash
    proc->start("bash");
    proc->waitForStarted();

    // Write as many commands to this process as needed
    foreach(QString str, input){
        proc->write(str.toUtf8() + "\n");
        proc->waitForBytesWritten(-1);
    }

    // Let bash close gracefully
    proc->write("exit $?\n");
    proc->waitForBytesWritten(-1);

    proc->closeWriteChannel();
    proc->waitForFinished();
    proc->waitForReadyRead();

    QByteArray read_data = proc->readAll();

    // The use of tr(read_data) also works here.
    QString output = tr(read_data);//QString::fromStdString (read_data.toStdString ());

    proc->closeReadChannel(QProcess::StandardOutput);

    proc->close();
    delete proc;

    // Strip default character set escape sequences, since those seem to be left
    // See https://stackoverflow.com/questions/36279015/what-does-x1bb-do
    output.remove("\x1b(B", Qt::CaseInsensitive);

    // Since it is just one single text stream define here instead of globally
    Utils::AnsiEscapeCodeHandler ansi_handler;

    FormattedTextList result = ansi_handler.parseText (Utils::FormattedText(output, ui->textEdit->currentCharFormat ()));

    // Loop through the text/format results
    foreach(Utils::FormattedText ft, result){
        ui->textEdit->setCurrentCharFormat (ft.format);
        ui->textEdit->insertPlainText (ft.text);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

新的头文件...

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

// This exists in the qtcreator-src code and handles ansi escape code color parsing
#include "ansiescapecodehandler.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

    typedef QList<Utils::FormattedText> FormattedTextList;
};

#endif // MAINWINDOW_H

新的彩色输出... QProcess gcc输出

QProcess不会干扰进程的输出,它只是gcc (与其他许多发出彩色输出的程序一样),默认情况下,仅当它检测到正在TTY设备上进行写入时,才会发出颜色转义序列。

如果要禁用此启发式方法并要求始终产生彩色输出,则必须在编译器命令行中添加-fdiagnostics-color=always选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM