1

Im using this code in Qt to get output of a cmd commend

     QProcess c_output;
     c_output.start("some-exe", QStringList() << "param1" << "param2" << "param3...");
     if (!c_output.waitForStarted())
         std::cout << false;

     c_output.write("...");
     c_output.closeWriteChannel();

     if (!c_output.waitForFinished())
         std::cout << false;

its work just good.
with this code i can access output with c_output.readAll(), but problem is this code wait until cmd finish exec ... and then give all output in c_output.readAll(), i want to get output in realtime and show them in gui of my program
my mean is my commend print multiply lines after exec, i want to show all of them one by one in my program and not wait for it to finish.

zgyarmati
  • 1,135
  • 8
  • 15
sanab3343
  • 154
  • 1
  • 11

1 Answers1

2

You can use waitForReadyRead instead of the waitForFinished , see at https://doc.qt.io/qt-5/qprocess.html#waitForReadyRead

Here is a simple example with the usage:

#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{

    QCoreApplication app(argc, argv);
    QProcess c_output;
    c_output.setProcessChannelMode(QProcess::MergedChannels);
     c_output.start("dmesg", QStringList() << "-w");
     if (!c_output.waitForStarted()){
         qDebug() << "Failed to start";
        return -1;
     }

     c_output.write("...");
     c_output.closeWriteChannel();

     while (c_output.state() != QProcess::NotRunning)
     {
        qDebug() << ".";
        if (c_output.waitForReadyRead())
         qDebug() << "c_output" << c_output.readAllStandardOutput();
     }


    return app.exec();
}
zgyarmati
  • 1,135
  • 8
  • 15
  • after that how can i use c_output.readAll() to read the output? – sanab3343 Sep 16 '20 at 17:53
  • thanks for good example, can you please show example for showing in gui? i mean append output in exiting text – sanab3343 Sep 16 '20 at 18:33
  • 1
    I think this is out of scope for this question. See for example this SO answer: https://stackoverflow.com/questions/13559990/how-to-append-text-to-qplaintextedit-without-adding-newline-and-keep-scroll-at or state a separated question with your exact issue. – zgyarmati Sep 16 '20 at 18:35
  • a problem i found in your code is it show \r\n and its also some time merge line – sanab3343 Sep 16 '20 at 18:38
  • i think its because im in the window and i think its use \r\n for going to next line – sanab3343 Sep 16 '20 at 18:44
  • 1
    This also depends on the format of the output of the executable, so i can't guide you with a specific example, but you can try to use the combination of `canReadLine() ` and `readLine()` methods as well to get separated lines. – zgyarmati Sep 16 '20 at 18:48