Pergunta

I want to pass the arguments in various ways like :

python abc.py 1 2
python abc.py -d 3 
python abc.py -c 6

I have tried with subparsers but i could do with

python abc.py def 1 2
python abc.py spec -d 3
python abc.py spec -c 6

is this possible ?

Foi útil?

Solução

I don't think you need subparser in your case. Something like this should be fine:

import argparse


parser = argparse.ArgumentParser()
parser.add_argument('-d', type=int, nargs='?')
parser.add_argument('-c', type=int, nargs='?')
parser.add_argument('args', type=int, nargs='*')

print(parser.parse_args())

Which results in:

$python3 test_argparse.py 1 2                                                 
Namespace(args=[1, 2], c=None, d=None)                                                                           
$python3 test_argparse.py -d 3
Namespace(args=[], c=None, d=3)
$python3 test_argparse.py -c 6
Namespace(args=[], c=6, d=None)

If you want the options to be mutually exclusive argparse provides a mutually exclusive group. Unfortunately positionals are always considered as required and hence you must manually check for them if you don't want the user to use them when specifying a given option (however I believe in this case you are provided a bad interface to your command).

Outras dicas

In argparse.add_argument you can provide the argument text not as a string, but as a list of strings, so having mulltiple forms of the same argument. Browse argparse docs carefully - this module can do everything you need.

A parser with two optionals of type int, and a positional with nargs='*‘, would accept your 3 inputs. Do you have any more constraints on the inputs?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top