Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse: "-p" or "-p=value" but not "-p value"

Is there a way to add an argument that is only usable as -p or -p=value, but not -p value

I want to add an optional argument --parallel/-p to the script. Here is how I want user to pass it:

./script arg1 arg2 -p    # this defaults to 10
./script arg1 arg2 -p=13 # This is fine and will set the value to 13
./script arg1 arg2 -p 13 # This is NOT fine and I want to ban this. Next line will tell why.
./script -p arg1 arg2    # I want -p to be usable regardless of its position. 
# But here arg1 will be considered as an argument of -p option, which is unwanted.
like image 770
Georgii Avatar asked Jun 23 '21 07:06

Georgii


1 Answers

Unfortunately you have two problems here :

  • argparse only allow --option=value for long argument, which are generated when the name is longer than one character.

  • argparse give no way to enforce the --option=value syntax, and --option value will always be possible.

You may have to write your own parser using what is inside sys.args (if you only have one option, it can be done quickly by searching the argument starting with "-p".

like image 134
qcoumes Avatar answered Oct 19 '22 22:10

qcoumes