Home > Software design >  Get output of a command sent to a QProcess
Get output of a command sent to a QProcess

Time:01-09

Pretty simple question. Let's say I do this:

m_serverProcess->write("command\n");

How do I get the output of that specific command?
Is this even possible? I know that I can use readyRead signal, but that is async so the order will probably not be correct.

CodePudding user response:

You could try the methods listed in the Qt documentation of QProcess: readAllStandardOutput and readAllStandardError. You may also use the method exitCode.

CodePudding user response:

You can get the output of a command that you run using the write method by reading from the standard output (stdout) of the process. You can do this using the readAllStandardOutput method of the QProcess class, which will return a QByteArray containing the output. Here is an example of how you can use this method to get the output of a command:

m_serverProcess->write("command\n");
m_serverProcess->waitForBytesWritten(); // wait until command has been written
QByteArray output = m_serverProcess->readAllStandardOutput();

Note that you will need to wait until the command has been written to the process before attempting to read the output, as the readAllStandardOutput method will not block and will return an empty QByteArray if no output is available. You can use the waitForBytesWritten method to block execution until the command has been written.

Keep in mind that this approach will not work if the command produces its output asynchronously, as the readAllStandardOutput method will only return the output that is available at the time it is called. In this case, you may need to use the readyRead signal and read the output as it becomes available, as you mentioned.

I hope this helps!

  •  Tags:  
  • c qt
  • Related