Ответы пользователя по тегу Python
  • Можно ли в argparse сделать позиционный аргумент необязательным?

    @V-ampre Автор вопроса
    Все вопрос снимается, цитирую:

    Arguments containing -

    The parse_args() method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. The parse_args() method is cautious here: positional arguments may only begin with - if they look like negative numbers and there are no options in the parser that look like negative numbers:
    >>>
    
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('-x')
    >>> parser.add_argument('foo', nargs='?')
    
    >>> # no negative number options, so -1 is a positional argument
    >>> parser.parse_args(['-x', '-1'])
    Namespace(foo=None, x='-1')
    Ответ написан
    Комментировать