I'm working on something where I need to use argparse.
Here's the code I got a problem with:
parser = argparse.ArgumentParser()
parser.add_argument('--create n file', dest='create',
nargs=2, default=(1, 'world1.json'),
help='Create a party of n player with mission parameters in file')
I'm trying to find a way to either set both n and file to another value, or set only one of them. n is an int and file a str.
Here's what I would like to get, using the following command:
| Command | Expected result |
|---|---|
| python mission.py --create 2 | create = [2, 'world1.json'] |
| python mission.py --create world2.json | create = [1, 'world2.json'] |
| python mission.py --create 3 world2.json | create = [3, 'world2.json'] |
When --create is used (with or without specifying n/file), I'll need to start a function using the list as arguments.
I've tried multiple things and read argparse documentation more than once but can't find a way to do it.
add_argument('--create', nargs='+'). After parsing decide for yourself what to do with the 1 or more strings in theargs.createlist.argparseisn't set up decode a mix of int and str types.beginshelp with this spec? How do you express this requirement as a function's arguments?typefunction andActionclass that does what you want, even replacing default values piecemeal. But it will be just as easy to do that conversion after parsing. Why don't you do that, and I can then suggest how to make it a part of the parser?nargs='+'doesn't work for what i need. Since user could just use--createalone to make a party using the default list [1, 'world1.json]. After that what you suggest me to do is to just decode the list after?