2012-05-22 71 views
17
ifconfig | grep 'inet' 

通過終端執行時正在工作。但不是通過QProcess中命令在終端工作,但不通過QProcess

我的示例代碼

QProcess p1; 
p1.start("ifconfig | grep 'inet'"); 
p1.waitForFinished(); 
QString output(p1.readAllStandardOutput()); 
textEdit->setText(output); 

上的TextEdit是越來越顯示任何內容。

但是當我在qprocess的開始只使用ifconfig時,輸出顯示在textedit上。我有沒有錯過任何構建命令ifconfig | grep 'inet'的技巧,如使用\''\||?爲特殊字符?但我想,以及:(

+0

您需要指定ifconifg的完整路徑。你的應用程序有不同的PATH變量,那麼你的終端 –

+0

@KamilKlimek由於這可能是單個命令的問題,在這種情況下,命令的管道(QProcess不支持)是真正的問題。 – leemes

+0

對!總是忘了那一個 –

回答

34

QProcess中執行一個單一的過程。 。你所要做的是執行shell命令,不是一個過程命令的管道是你的shell的一個特點

有三種可能的解決方案:

把comman d。您想作爲參數傳遞給sh-c執行(「命令」):

QProcess sh; 
sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet"); 

sh.waitForFinished(); 
QByteArray output = sh.readAll(); 
sh.close(); 

或者你可以在命令作爲標準輸入寫sh

QProcess sh; 
sh.start("sh"); 

sh.write("ifconfig | grep inet"); 
sh.closeWriteChannel(); 

sh.waitForFinished(); 
QByteArray output = sh.readAll(); 
sh.close(); 

避免了另一種方法sh,就是推出兩個QProcesses做管道在你的代碼:

QProcess ifconfig; 
QProcess grep; 

ifconfig.setStandardOutputProcess(&grep); // "simulates" ifconfig | grep 

ifconfig.start("ifconfig"); 
grep.start("grep", QStringList() << "inet"); // pass arguments using QStringList 

grep.waitForFinished(); // grep finishes after ifconfig does 
QByteArray output = grep.readAll(); // now the output is found in the 2nd process 
ifconfig.close(); 
grep.close(); 
+0

它是如何完成的? – ScarCode

+5

我爲一些可能的解決方案添加了代碼示例。 – leemes

+2

Grep工作。但我想將ifconfig的輸出傳遞給awk'/inet/{gsub(/.*:/,"",$1);print$1}'。它在終端上成功地打印了一些o/p,而不是通過Qprocess。我用你的解決方案的第2步 – ScarCode

6

QProcess對象不會自動給你完全成熟的shell語法:你不能用管道使用shell此:

p1.start("/bin/sh -c \"ifconfig | grep inet\""); 
+1

我也試過這個。但仍然不工作! – ScarCode

+1

啊是的,它應該是雙引號,而不是引號。 – kmkaplan

+3

替代方案(更安全,因爲您不必注意參數內部的轉義,如果它更復雜):使用QStringList作爲參數,如下所示:'p1.start(「/ bin/sh」,QStringList <「-c」<<「ifconfig | grep inet」);' – leemes

相關問題