Let’s say that I want to enter info about multiple users from the command line AND that each user has multiple data associated with it.
Is it possible (syntactically permissible) to use argparse
to parse something like myprpgrm.py --user john --email [email protected] --valid Y --user jane --email [email protected] --valid N
?
As you can see, each user should have 3 parameters associated with it – a name, an email and a valid flag.
Can argparse
make sure that if a user parameter is seen, it must be accompanied by an email parameter and a validity parameter?
And can it give me the grouped information when I add multiple users, each with 3 parameters?
[Update] Could this be achieved somehow with Argument Groups?
7
I wouldn’t use command line arguments for this. Command line arguments are meant for simple, transient configuration. What you have here is structured data. You want to put it into a more permanent format, such as JSON:
[
{
'user': 'john',
'email': '[email protected]',
'valid': true
},
{
'user': 'jane',
'email': '[email protected]',
'valid': false
}
]
Python conveniently has a module for parsing JSON:
import json
with open('path/to/data.json') as file:
data = json.load(file)
Argparse has special facilities for passing files on the command line; you probably won’t have to call open()
by yourself.
2