[英]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.