Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read QProcess output to string

Tags:

I have a code that uses QProcess like this.

int main(int argc, char *argv[]) {     int status=0;     QProcess pingProcess;     QString ba;     QString exec = "snmpget";     QStringList params;      params << "-v" << "2c" << "-c" << "public" << "10.18.32.52" <<    ".1.3.6.1.4.1.30966.1.2.1.1.1.5.10";     status=pingProcess.execute(exec, params);     pingProcess.close(); } 

This outputs the following.

SNMPv2-SMI::enterprises.30966.1.2.1.1.1.5.10 = STRING: "0.1" 

I want to take(read) this output as string. I searched for this and I cant find the solution. Thanks in advance.

like image 522
sersem1 Avatar asked Jun 27 '13 13:06

sersem1


Video Answer


2 Answers

Did you try QByteArray QProcess::readAllStandardOutput() docs - here

QString can be instantiated from QByteArray:

QString output(pingProcess.readAllStandardOutput()); 

As others mentioned, and I join to them, you should not use execute method and replace it with:

pingProcess.start(exec, params); pingProcess.waitForFinished(); // sets current thread to sleep and waits for pingProcess end QString output(pingProcess.readAllStandardOutput()); 
like image 113
Shf Avatar answered Oct 04 '22 01:10

Shf


@Shf is right in that you should be using readAllStandardOutput. However, you're using the function execute() which is a static method. You should be calling start( ) from an instance of a QProcess.

It may also be a good idea to then either wait for the data with waitForReadyRead, or just wait for the process to finish with waitForFinished( ).

Also, there's an overloaded start function, which allows you to pass the whole command in, which may make your code easier to read: -

QProcess pingProcess; QString exe = "snmpget -v 2c -c public 10.18.32.52 .1.3.6.1.4.1.30966.1.2.1.1.1.5.10"; pingProcess.start(exe); pingProcess.waitForFinished(); QString output(pingProcess.readAllOutput()); 

Note that calling waitForFinished will hang the current process, so if you're going to do something that will take a while, you would then want to dynamically create the QProcess and connect to the finished() signal in order for a connected slot to then read the data.

like image 36
TheDarkKnight Avatar answered Oct 04 '22 00:10

TheDarkKnight