Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required commandline options in Python using argparse

I have the following scenario for command line argument. If there is a particular option then there should be some other required options. For example if there is -- create then there should be --name. Also if there is --remove then there should be --id. Is it possible to implement this scenario with argparse? or someother thing?

like image 680
bonzi Avatar asked Apr 06 '11 19:04

bonzi


People also ask

How do you make an Argparse optional argument in Python?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do you pass optional command line arguments in Python?

Accepting optional command-line arguments When running this program, this optional argument can be specified with either --expected=SOMETHING or -e SOMETHING . If this expected argument isn't provided then it will default to the value None .

How do you make an argument mandatory in Python?

required is a parameter of the ArugmentParser object's function add_argument() . By default, the arguments of type -f or --foo are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required to True .


1 Answers

This can be done with subcommands as long as you don't mind create and remove not being preceded with hyphens. This may make sense anyway, since those verbs are often used as actions rather than options.

like image 121
intuited Avatar answered Nov 10 '22 13:11

intuited