parse command line args in form /variable=value ?
-
Hi,
What's the "Qt Way" of parsing command line arguments in this form:
my.exe /var1=value1 /var2=value2 /var3=value3
etc?
I need to make my Qt app (which is being ported from MFC ) launchable by an existing 3rd-party tool that is already coded to launch my (MFC) app with arguments in this "non traditional" form and QCommandLineParser and QCommandLineOption seem more suited to the more traditional "--option" type approach. I want to make my new Qt version work the same without having to make changes to the 3rd party tool which is calling mine.
Do I have to just manually parse things using RegEx (etc) or am I missing something?
Thanks!
-
Hi @pmh4514,
I want to make my new Qt version work the same without having to make changes to the 3rd party tool which is calling mine.
I think there's two approaches you could take here.
First, you could treat all arguments as positional arguments, and parse them yourself. It wouldn't be too hard, like:
QCoreApplication app(argc, argv); QCommandLineParser parser; parser.addHelpOption(); parser.addPositionalArgument("args", "Arguments in the old MFC app's style, eg /var1=value1", "[args...]"); parser.process(app); foreach (const QString &arg, parser.positionalArguments()) { if (arg.startsWith('/')) { qDebug() << "Arg" << arg.section('=',0,0).mid(1) << "set to" << arg.section('=',1); } }
If we execute that like:
./foo -h
we get:Usage: ./foo [options] [args...] Options: -h, --help Displays this help. Arguments: args Arguments in the old MFC app's style, eg /var1=value1
Then, if we execute like:
./foo /a=1 "/bbb=123=456"
we get:Arg "a" set to "1" Arg "bbb" set to "123=456"
However, another approach, which may or may not be preferable, is to manipulate the arguments before calling the parser, like:
QCoreApplication app(argc, argv); QStringList arguments; foreach (auto arg, app.arguments()) { if (arg.startsWith('/')) { arg.replace(0,1,"--"); } arguments.append(arg); } QCommandLineParser parser; parser.addHelpOption(); parser.addOptions({ // Just for example {{"a", "aaa"}, "Some option", "val"}, {{"b", "bbb"}, "Some other option", "val"}, }); parser.process(arguments); qDebug() << "Arg a is" << parser.value("a"); qDebug() << "Arg b is" << parser.value("b");
Now if we run
./foo -h
:Usage: ./foo [options] Options: -h, --help Displays this help. -a, --aaa <val> Some option -b, --bbb <val> Some other option
And
./foo /a=1 "/bbb=123=456"
Arg a is "1" Arg b is "123=456"
The second version has the advantage of supporting both the
-a --bbb
and/a /bbb
styles. They can even be mixed and matched.Hope that helps.
Cheers.