0

What is the best way to have multiple options of command line arguments based on selected options. For example lets say we have sample.py

I would like to have say 3 options:

python sample.py Employee John Doe
python sample.py Address Washington Drive NY
python sample.py Number 1234567890

Was trying to add parser.add_argument('option', choices=['Employee', 'Address', 'Number']), so this will limit me to have the 3 options, but I guess it would be nice to have it check the required parameters as well, and maybe a detailed help -h. Say if Employee is chosen and only one parameter provided, it will say something like lastname is required. If Number is selected and provides a string, it will say something like invalid number. Is it better to do positional arguments, or named argument, like -num 1234567890 or -firstname John -lastname Doe. Seems positional is more simple, but can be confusing if it requires 7 parameters. How would you write the sample.py to use argparse and handle the simple example above

user1179317
  • 2,693
  • 3
  • 34
  • 62
  • 1
    You want three [subcommands](https://docs.python.org/3/library/argparse.html#sub-commands). – chepner Sep 07 '20 at 21:35
  • You would do best to follow conventions on command line parameters, so users don't have to guess or get frustrated using your script. And if you do, you'll find that `argparse` supports that quite handily. – Grismar Sep 07 '20 at 21:39
  • 1
    i would preferr to have `--Employee` `--Address` `--Number` and run all of them in one execution, `python sample.py --Employee "John Doe" --Address "Washington Drive NY" --Number 1234567890`. This way I assing address to person. Because I don't like to write long strings so I would create also shorter `-e` for `Employee`, `-a` for `Address` and `-n` for `Number` – furas Sep 07 '20 at 22:17
  • Are you going to allow just one of these options per call, or some combination? Must the name always have 2 fields? How about the address? Accepting quoted strings gives you the most flexibility. Some testing is easier done after parsing. – hpaulj Sep 08 '20 at 06:34
  • related: https://stackoverflow.com/q/57875917, https://stackoverflow.com/q/19414060 – djvg Jun 23 '22 at 07:52

0 Answers0