传递参数字符串,其中包含空格和引号

Passing argument string which contains spaces and quotes

本文关键字:空格 包含 参数 字符串      更新时间:2023-10-16

使用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 is 是一个包含程序名及其参数的文本字符串。参数之间用一个或多个空格分隔。

程序字符串也可以包含引号,以确保包含空格的参数被正确地提供给新进程。

您可能需要将"替换为",但您可以从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对象中。