myślę, że to jest dość trudne do osiągnięcia, że (w tym ładnym komunikat pomocy), a jedynie za pomocą standardowych funkcji argparse. Możesz jednak łatwo przetestować go samodzielnie po analizie argumentów. Możesz opisać dodatkowe wymagania w epilogu. Zauważ, że nietypowe jest używanie liczb jako opcji, musiałem użyć dest = 'dwa', ponieważ arguments.2 nie jest prawidłową składnią.
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(
description='bla bla',
epilog='Note: arguments -3 and -4 are required when -2 is missing')
parser.add_argument('-2', dest='two', action='store_true')
parser.add_argument('-3', dest='three')
parser.add_argument('-4', dest='four')
parser.add_argument('-5', dest='five')
args = parser.parse_args()
if not args.two and (args.three is None or args.four is None):
parser.error('arguments -3 and -4 are required when -2 is missing')
print 'Good:', args
Z tych wyników:
[~]: ./test.py -h
usage: test.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
bla bla
optional arguments:
-h, --help show this help message and exit
-2
-3 THREE
-4 FOUR
-5 FIVE
Note: arguments -3 and -4 are required when -2 is missing
[~]: ./test.py -2
Good: Namespace(five=None, four=None, three=None, two=True)
[~]: ./test.py -3 a -4 b
Good: Namespace(five=None, four='b', three='a', two=False)
[~]: ./test.py -3 a
usage: test.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
test.py: error: arguments -3 and -4 are required when -2 is missing
[~]: ./test.py -2 -5 c
Good: Namespace(five='c', four=None, three=None, two=True)
[~]: ./test.py -2 -3 a
Good: Namespace(five=None, four=None, three='a', two=True)
Dodać subparser wprowadzonego na -2 który replikuje inne polecenia jako opcjonalne. Na najwyższym poziomie połącz -3 i -4 razem. – Jiminion
Użycie poleceń poleceń rozpoczynających się od '-' może być trudne. '-2' może działać, ale' -t' lub '--two' nie będzie, ponieważ wyglądają jak opcje. Ale jeśli '-3' jest zdefiniowany jako argument, to' -2' nie działa już jako polecenie akapert (lub wybór). – hpaulj