2014-03-27 95 views
1

使用QProcess::startDetached,我需要將來自另一個進程的動態參數列表傳遞給啓動進程。傳遞包含空格和引號的參數字符串

const QString & prog, const QStringList & args, const QString & workingDirectory ...)

注意,包含空格的參數不傳遞到過程 作爲獨立參數。

...

的Windows:包含空格的參數被包裝在引號。啓動的進程將作爲常規的獨立進程運行。

我有一個包含以下文本的字符串,它來自一個外部程序,而不在其上的任何控制:

-c "resume" -c "print 'Hi!'" -c "print 'Hello World'" 

我需要上面的字符串傳遞給QProcess::startDetached使得啓動程序捕獲它作爲與上面的字符串相同。

我必須解析字符串並建立一個字符串列表嗎?或者任何人有更好的解決方案?

回答

2

您不必在所有使用一個QStringList中的參數,因爲有這個重載函數: -

bool QProcess::startDetached(const QString & program) 

其中,作爲文檔狀態: -

啓動程序程序在一個新的過程中。程序是包含程序名稱及其參數的單個字符串文本。參數由一個或多個空格分隔。

程序字符串也可以包含引號,以確保包含空格的參數被正確提供給新進程。

您可能需要 「與\」 來代替,但你可以做到這一點從QString的

 

您可以使用parseCombinedArgString(從Qt的源代碼)解析:

QStringList parseCombinedArgString(const QString &program) 
{ 
    QStringList args; 
    QString tmp; 
    int quoteCount = 0; 
    bool inQuote = false; 
    // handle quoting. tokens can be surrounded by double quotes 
    // "hello world". three consecutive double quotes represent 
    // the quote character itself. 
    for (int i = 0; i < program.size(); ++i) 
    { 
     if (program.at(i) == QLatin1Char('"')) 
     { 
      ++quoteCount; 
      if (quoteCount == 3) 
      { 
       // third consecutive quote 
       quoteCount = 0; 
       tmp += program.at(i); 
      } 
      continue; 
     } 
     if (quoteCount) 
     { 
      if (quoteCount == 1) 
       inQuote = !inQuote; 
      quoteCount = 0; 
     } 
     if (!inQuote && program.at(i).isSpace()) 
     { 
      if (!tmp.isEmpty()) 
      { 
       args += tmp; 
       tmp.clear(); 
      } 
     } 
     else 
     { 
      tmp += program.at(i); 
     } 
    } 
    if (!tmp.isEmpty()) 
     args += tmp; 
    return args; 
} 
+0

具有'workingDirectory'參數的重載如何?我可以有你提到的重載並設置工作目錄嗎? – deepmax

+0

有一個單獨的函數調用QProcess :: setWorkingDirectory:「將工作目錄設置爲dir,QProcess將在此目錄中啓動進程。」所以在你調用startDetached之前調用它。但是,您可能需要創建一個QProcess的實例才能正常工作。 – TheDarkKnight

+0

'startDetached'是一個靜態方法,你確定它爲'startDetached'使用'QProcess'的內部屬性嗎? – deepmax

1

是的,您必須「解析」該字符串,將其拆分到正確的位置,然後將每個子字符串輸入到傳遞給函數的QStringList對象中。

+0

這是不是很奇怪?傳遞參數字符串通常是一項非常簡單的任務。爲什麼'startDetached'需要'QStringList'?如何更復雜的論點? – deepmax

+0

@MM。可能是因爲該函數不能合理地分析參數字符串,如果它創建一個'argv'樣式的數組。 –

+0

+1我使用瞭解析字符串的Qt源代碼中的'parseCombinedArgString'。你是對的,我必須解析它。 – deepmax

相關問題