Синтаксический анализатор командной строки для Qt4

Любую временную ошибку (я думаю, у вас здесь есть временная ошибка) можно решить с помощью комбинации until / retry: https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops .html # do-till-loops

Пример:

- name: Install packages
  become: true
  apt:
    name: [packages]
    update_cache: true
    cache_valid_time='{{ apt_cache_valid_time|d(3600) }}'
  register: apt_result
  retries: '{{ apt_retries }}'
  delay: 10
  until: apt_result|success
  tags:
   - apt
   - install

24
задан elcuco 2 July 2010 в 17:52
поделиться

7 ответов

QCoreApplication's constructors require (int &argc, char **argv) (and QApplication inherits from QCoreApplication). As the documentation states, it is highly recommended that

Since QApplication also deals with common command line arguments, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself.

And if you're letting Qt get the first pass at handling arguments anyways, it would also be a good idea to use QStringList QCoreApplication::arguments() instead of walking through argv; QApplication may remove some of the arguments that it has taken for its own use.

This doesn't lend itself to being very compatible with other argument-parsing libraries...

However, kdelibs does come with a nice argument parser, KCmdLineArgs. It is LGPL and can be used without KApplication if you really want (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.?).

23
ответ дан 28 November 2019 в 22:37
поделиться

Этот пакет поддерживает --disable-foo и --enable-foo через opts.addSwitch ("disable-foo", & foo_disabled); и opts .addSwitch ("enable-foo", & foo_enabled); . Вам нужно проверить оба дескриптора и иметь дело с кем-то, кто указывает оба (ой).

Я не понимаю, какое отношение это имеет к QT4 ...

3
ответ дан 28 November 2019 в 22:37
поделиться

Должен ли он быть специфичным для Qt4? Если нет, GNU Getopt действительно хорош, хотя с лицензированием могут возникнуть проблемы, если вы не работаете с ПО с открытым исходным кодом.

1
ответ дан 28 November 2019 в 22:37
поделиться

Очень простой метод - просмотреть аргументы "ключ = значение",
поместите их в таблицу, скажем, zz.map: QString -> QVariant,
и получить их значения с помощью zz.map.value (ключ, по умолчанию). Пример:

#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 меньше 1 страницы, ниже; то же самое для Python ~ 10 строк.

(У каждого есть свой любимый парсер опций; этот о самом простом.
Стоит повторить: как бы вы ни указали параметры, выводите их в выходные файлы -
"каждый ученый, которого я знаю, не может отслеживать какие параметры они использовали в последний раз, когда запускали скрипт ".)

Чтобы заставить QPoints и т.д. работать, конечно, нужен синтаксический анализатор QString -> QPoint. Кто-нибудь знает, почему это не работает (в Qt 4.4.3)?

QPoint pt(0,0);
QDataStream s( "QPoint(1,2)" );
s >> pt;
qDebug() << "pt:" << pt;  // QPoint(1364225897,1853106225) ??

Добавлено 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
2
ответ дан 28 November 2019 в 22:37
поделиться

Также для синтаксического анализа некоторых необычных параметров вы можете попробовать gperf .

У IBM есть хорошее учебное пособие .

0
ответ дан 28 November 2019 в 22:37
поделиться
2
ответ дан 28 November 2019 в 22:37
поделиться

Другой вариант, с которым я столкнулся, пытаясь сделать это, тоже:

http://code.google.com/p/qgetopts/

Но я не использовал его.

0
ответ дан 28 November 2019 в 22:37
поделиться
Другие вопросы по тегам:

Похожие вопросы: