here is what i would like to do : A command that looks like git command behavior. You don't get the same options whether you typed git commit or git checkout. But in my case i want to provide different arguments based on an argument value (a file name) like this :
>cmd file.a -h
usage: cmd filename [-opt1] [-opt2]
positional arguments:
filename file to process
optional arguments:
-opt1 do something on files of type 'a'
-opt2 do something else on files of type 'a'
>cmd file.b -h
usage: cmd filename [-opt3] [-opt4]
positional arguments:
filename file to process
optional arguments:
-opt3 do something on files of type 'b'
-opt4 do something else on files of type 'b'
Is it possible to do this kind of thing using python and argparse ?
What i've tried so far is :
parser = argparse.Argument_parser(prog='cmd')
subparsers = parser.add_subparsers()
parser.add_argument('filename',
help="file or sequence to process")
args = parser.parse_args(args=argv[1:])
sub_parser = subparsers.add_parser(args.filename, help="job type")
base, ext = os.path.splitext(args.filename)
if ext == 'a':
sub_parser.add_argument("-opt1", action='store_true')
sub_parser.add_argument("-opt2", action='store_true')
elif ext == 'b':
sub_parser.add_argument("-opt3", action='store_true')
sub_parser.add_argument("-opt4", action='store_true')
args = parser.parse_args(args=argv[1:])
I don't know if i should use subparsers or child parsers or groups, i'm kind of lost in all the possibilities provided by argparse