如何获取使用 QProcess 调用的程序的返回标准输出?
How to get the returned stdout of a program called with QProcess?
我正在用 Qt 编写程序,目前使用 popen 到 运行 一个 linux 命令并将输出读入字符串:
QString Test::popenCmd(const QString command) {
FILE *filePointer;
int status;
int maxLength = 1024;
char resultStringBuffer[maxLength];
QString resultString = "";
filePointer = popen(command.toStdString().c_str(), "r");
if (filePointer == NULL) {
return 0;
}
while (fgets(resultStringBuffer, maxLength, filePointer) != NULL) {
resultString += resultStringBuffer;
}
status = pclose(filePointer);
if (status == 0) {
return resultString;
} else {
return 0;
}
}
所以我想放弃上面的代码,因为如果可能的话我更愿意使用 Qt 提供的更高级别的工具。有没有人有关于如何使用 QProcess 执行此操作的示例,或者至少大致了解如何执行此操作?
无论如何,这将是 Linux 上的 运行。
谢谢
这样做:
void Process::runCommand(const QString &p_Command) {
QProcess *console = new QProcess();
console->connect(console, SIGNAL(readyRead()), this, SLOT(out()));
console->connect(console, SIGNAL(finished(int)), this, SLOT(processFinished(int)));
console->start(p_Command);
}
void Process::out() {
QProcess *console = qobject_cast<QProcess*>(QObject::sender());
QByteArray processOutput = console->readAll();
}
void Process::processFinished(int p_Code) {
QProcess *console = qobject_cast<QProcess*>(QObject::sender());
QByteArray processOutput = console->readAll() + QString("Finished with code %1").arg(p_Code).toLatin1();
}
信号QProcess::finished()
可用于获取进程的退出代码。
我正在用 Qt 编写程序,目前使用 popen 到 运行 一个 linux 命令并将输出读入字符串:
QString Test::popenCmd(const QString command) {
FILE *filePointer;
int status;
int maxLength = 1024;
char resultStringBuffer[maxLength];
QString resultString = "";
filePointer = popen(command.toStdString().c_str(), "r");
if (filePointer == NULL) {
return 0;
}
while (fgets(resultStringBuffer, maxLength, filePointer) != NULL) {
resultString += resultStringBuffer;
}
status = pclose(filePointer);
if (status == 0) {
return resultString;
} else {
return 0;
}
}
所以我想放弃上面的代码,因为如果可能的话我更愿意使用 Qt 提供的更高级别的工具。有没有人有关于如何使用 QProcess 执行此操作的示例,或者至少大致了解如何执行此操作?
无论如何,这将是 Linux 上的 运行。
谢谢
这样做:
void Process::runCommand(const QString &p_Command) {
QProcess *console = new QProcess();
console->connect(console, SIGNAL(readyRead()), this, SLOT(out()));
console->connect(console, SIGNAL(finished(int)), this, SLOT(processFinished(int)));
console->start(p_Command);
}
void Process::out() {
QProcess *console = qobject_cast<QProcess*>(QObject::sender());
QByteArray processOutput = console->readAll();
}
void Process::processFinished(int p_Code) {
QProcess *console = qobject_cast<QProcess*>(QObject::sender());
QByteArray processOutput = console->readAll() + QString("Finished with code %1").arg(p_Code).toLatin1();
}
信号QProcess::finished()
可用于获取进程的退出代码。