[英]Passing argument string which contains spaces and quotes
使用QProcess::startDetached
,我需要將一個動態參數列表傳遞給起始進程,該列表來自另一個進程。
const QString & prog, const QStringList & args, const QString & workingDirectory ...)
請注意,包含空格的參數不會作為單獨的參數傳遞給進程。
...
Windows:包含空格的參數用引號括起來。 啟動的進程將作為常規獨立進程運行。
我有一個包含下面文本的字符串,它來自一個沒有任何控制權的外部程序:
-c "resume" -c "print 'Hi!'" -c "print 'Hello World'"
我需要將上面的字符串傳遞給QProcess::startDetached
以便啟動程序捕獲它與上面的字符串相同。
我是否必須解析字符串並構建字符串列表? 或者任何人有更好的解決方案?
您根本不需要使用QStringList作為參數,因為存在這個重載函數: -
bool QProcess::startDetached(const QString & program)
其中,正如文件所述: -
以新流程啟動程序程序。 program是包含程序名稱及其參數的單個文本字符串 。 參數由一個或多個空格分隔。
程序字符串還可以包含引號,以確保包含空格的參數正確提供給新進程。
您可能需要替換“with”,但您可以從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;
}
是的,您必須“解析”字符串,將其拆分到正確的位置,然后將每個子字符串輸入到傳遞給函數的QStringList
對象中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.