Parser wiersza poleceń dla Qt4
Szukam parsera linii poleceń dla Qt4.
Zrobiłem małe wyszukiwanie w google i znalazłem to: http://www.froglogic.com/pg?id=PublicationsFreeware&category=getopt nie ma jednak wsparcia dla przełączników "-- enable-foo " i "--disable-foo". Poza tym wygląda na prawdziwego zwycięzcę.
EDIT:
Wygląda na to, że Frologic to usunął. Więc najlepsze opcje widzę za pomocą Boost (który nie jest API ani ABI stabilny) lub rozwidlenie wsparcie dla kdelibs. Yay...
11 answers
Od Qt 5.2 można wreszcie znaleźć rozwiązanie w samym QtCore: ja tam wstawiłem QCommandLineParser .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-20 17:41:15
QCoreApplication
'konstruktory s wymagają (int &argc, char **argv)
(i QApplication
dziedziczą z QCoreApplication
). Jak stwierdza dokumentacja , zaleca się, aby
Ponieważ QApplication zajmuje się również wspólnymi argumentami wiersza poleceń, zwykle dobrym pomysłem jest utworzenie go zanim zostanie dokonana jakakolwiek interpretacja lub modyfikacja
argv
w samej aplikacji.
I jeśli pozwalasz Qt uzyskać pierwsze przejście w obsłudze argumentów tak czy inaczej, będzie to również dobry pomysł do wykorzystania QStringList QCoreApplication::arguments()
zamiast iść przez argv
; QApplication
może usunąć niektóre z argumentów, które podjął na własny użytek.
To nie nadaje się do bycia bardzo kompatybilnym z innymi bibliotekami parsującymi argumenty...
Jednakże, kdelibs posiada ładny parser argumentów, KCmdLineArgs
. Jest to LGPL i może być używany bez KApplication
, jeśli naprawdę chcesz (call KCmdLineArgs::init
).
KCmdLineOptions options;
options.add("enable-foo", ki18n("enables foo"));
options.add("nodisable-foo", ki18n("disables foo"));
// double negatives are confusing, but this makes disable-foo enabled by default
KCmdLineArgs::addCmdLineOptions(options);
KApplication app;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
if (args->isSet("enable-foo") && !args->isSet("disable-foo"))
cout << "foo enabled" << endl;
else
cout << "foo disabled" << endl;
Untested (who ever tests what they post on S. O.?).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-09 16:02:37
Jest to mniej więcej taka sama odpowiedź jak efemient, ale z prostym wyrażeniem regularnym, które pomaga w analizie args. (Ten sposób może być przydatny, jeśli potrzebujesz tylko garści args)
Run with this:
./QArgTest --pid=45 --enable-foo
I Kod:
int main(int argc, char *argv[]) {
QApplication app(argc, argv, false);
qDebug() << "QApp arg test app";
QStringList args = app.arguments();
int pid = 0;
QRegExp rxArgPid("--pid=([0-9]{1,})");
QRegExp rxArgFooEna("--enable-foo");
QRegExp rxArgFooDis("--disable-foo");
for (int i = 1; i < args.size(); ++i) {
if (rxArgPid.indexIn(args.at(i)) != -1 ) {
pid = rxArgPid.cap(1).toInt();
qDebug() << i << ":" << args.at(i) << rxArgPid.cap(1) << pid;
}
else if (rxArgFooEna.indexIn(args.at(i)) != -1 ) {
qDebug() << i << ":" << args.at(i) << "Enable Foo";
}
else if (rxArgFooDis.indexIn(args.at(i)) != -1 ) {
qDebug() << i << ":" << args.at(i) << "Disable Foo";
}
else {
qDebug() << "Uknown arg:" << args.at(i);
}
}
return 0;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-31 08:48:11
Istnieje również QxtCommandOptions z http://www.libqxt.org/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-06 19:51:10
Ten pakiet obsługuje --disable-foo I --enable-foo poprzez opcje .addSwitch ("disable-foo", &foo_disabled); i .addSwitch ("enable-foo", &foo_enabled); . Musisz obsłużyć sprawdzanie obu i radzenie sobie z kimś określającym oba (oops).
Nie rozumiem, jak to ma coś wspólnego z QT4...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-15 18:59:44
Zobacz też: http://code.google.com/p/qtargparser/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-21 10:13:25
Bardzo prostą metodą jest skanowanie" klucz=wartość " args,
połóż je na stole, powiedz "zz".Mapa: QString - > QVariant,
i zdobądź ich wartości Z zz.Mapa.wartość (klucz, domyślnie).
Przykład:
#include "ztest.h"
Ztest zz;
int main( int argc, char* argv[] )
{
zz.eqargs( ++ argv ); // scan test=2 x=str ... to zz.map
QString xx = zz.map.value( "xx", "" );
if( Zint( Size, 10 )) // a #def -> zz.map.value( "Size", 10 )
...
ztest.h
jest
(Everybody has his / her favorite options parser;
ten jest najprostszy.
Warto powtórzyć: jakkolwiek określisz opcje, prześlij je do plików wyjściowych --
"każdy naukowiec, którego znam, ma problemy z utrzymaniem Tor
jakich parametrów użyli ostatnio, gdy uruchomili skrypt".)
Aby qpoints itd. działały, potrzebny jest oczywiście parser QString - > QPoint. Wie ktoś dlaczego to nie działa (w Qt 4.4.3)?
QPoint pt(0,0);
QDataStream s( "QPoint(1,2)" );
s >> pt;
qDebug() << "pt:" << pt; // QPoint(1364225897,1853106225) ??
Dodano 25nov --
// ztest.h: scan args x=2 s=str ... to a key -> string table
// usage:
// Ztest ztest;
// int main( int argc, char* argv[] )
// {
// QApplication app( argc, argv );
// ztest.eqargs( ++ argv ); // scan leading args name=value ...
// int x = Zint( x, 10 ); // arg x= or default 10
// qreal ff = Zreal( ff, 3.14 );
// QString s = Zstr( s, "default" );
// care: int misspelled = Zint( misspellled ) -- you lose
//version: 2009-06-09 jun denis
#ifndef ztest_h
#define ztest_h
#include <QHash>
#include <QString>
#include <QVariant>
#include <QRegExp>
//------------------------------------------------------------------------------
class Ztest {
public:
QHash< QString, QVariant > map;
int test; // arg test=num, if( ztest.test )
Ztest() : test( 0 ) {}
QVariant val( const QString& key, const QVariant& default_ = 0 )
{
return map.value( key, default_ );
}
void setval( const QString& key, const QVariant& val )
{
map[key] = val;
if( key == "test" || key == "Test" )
test = val.toInt();
}
//------------------------------------------------------------------------------
// ztest.eqargs( ++ argv ) scans test=2 x=3 ... -> ztest table
void eqargs( char** argv )
{
char** argv0 = argv;
char *arg;
QRegExp re( "(\\w+)=(.*)" ); // name= anything, but not ./file=name
for( ; (arg = *argv) && re.exactMatch( arg ); argv ++ ){
setval( re.cap(1), re.cap(2) );
}
// change argv[0..] -> args after all name=values
while(( *argv0++ = *argv++) != 0 ) {}
}
};
extern Ztest ztest;
// macros: int x = Zint( x, 10 ): x= arg or default 10
#define Zstr( key, default ) ztest.val( #key, default ).toString()
#define Zint( key, default ) ztest.val( #key, default ).toInt()
#define Zreal( key, default ) ztest.val( #key, default ).toDouble()
#endif
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-25 17:21:21
Jest rok 2013 i nadal nie ma parsera arg "1st party". W każdym razie..jeśli ktoś znajdzie się w obliczu tego samego problemu i chciałby uniknąć krzywych uczenia, które pochodzą z libs parsera cmd, oto" szybka i brudna " poprawka dla Ciebie: - {]}
QString QArgByKey(QString key, QChar sep = QChar('\0') ) //prototype usually in separate header
QString QArgByKey(QString key, QChar sep )
{
bool sepd=sep!=QChar('\0');
int pos=sepd?qApp->arguments().indexOf(QRegExp('^'+key+sep+"\\S*")):qApp->arguments().indexOf(QRegExp(key));
return pos==-1?QString::null:
(sepd?qApp->arguments().at(pos).split(sep).at(1):(++pos<qApp->arguments().size()?qApp->arguments().at(pos):QString::null));
}
Przykład:-
user@box:~$ ./myApp firstKey=Value1 --secondKey Value2 thirdKey=val3.1,val3.2,val3.3 --enable-foo
Użycie:
QString param1 = QArgByKey("firstkey",'='); // Returns `Value1` from first pair
QString param2 = QArgByKey("--secondkey"); // Returns `Value2` from second pair
QString param3-1 = QArgByKey("thirdkey",'=').split(',').at(0); // Returns `val3.1`
bool fooEnabled = qApp->arguments().contains("--enable-foo"); //To check for `--enable-foo`
Paramy mogą być przekazywane w dowolnej kolejności
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-11 23:19:40
Czy to musi być specyficzne dla Qt4? Jeśli nie, GNU Getopt jest naprawdę fajny, chociaż licencjonowanie może być problemem, jeśli nie tworzysz oprogramowania open source.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-15 18:55:14
Również dla niektórych fantazyjnych opcji parsowania możesz spróbować gperf.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-10 13:48:17
Inna opcja, na którą też wpadłem, gdy chciałem to zrobić:
Http://code.google.com/p/qgetopts/
Nie używałem go jednak.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-16 18:48:42