搜尋此網誌

2009年11月6日 星期五

如何執行外部程式,並取得其標準輸出資料

在Qt中,要執行外部程式最容易的方法就是使用 QProcess, 並連結 readyReadStandardOutput 這個signal來取得其標準輸出.

例如,我們要在程式內部執行 ls 這個命令,並取得其結果,我們可以這麼做

// header file ----------

QProcess pls;

// cpp ------------------

connect(&pls, SIGNAL(readyReadStandardOutput()), this, SLOT(sl_readPlsOutput()));

pls.start("ls", QStringList() << "-al");

if (!pls.waitForStarted())
printf("wait for pls\n");
if (!pls.waitForFinished())
printf("wait for pls\n");

// slot -------------------
sl_readPlsOutput()
{
QByteArray tmpArray;
tmpArray = pls.readAllStandardOutput();
}