I am working on Python 2.7.9 and using argparse module for command line arguments. I want to extend my code such that it should be able to take the command line arguments depending on the arguments already given by the user in the same command line. Lets say, the arguments are -a,-b,-c,-d
If the user gives -a <value>
then only he should be able to enter -x <value>
and same applies to the other case. If the user enters -b <value>
then only he should be able to enter -y <value>
.
Can anyone please help me with this.
Thank you!
Asked
Active
Viewed 260 times
2

Vipul
- 125
- 2
- 11
-
I am not able to understand how do I do it. I can use nargs to make user input 2 values followed by -a but I don't want to use that. – Vipul Mar 03 '15 at 09:52
2 Answers
1
One way would be to parse the args in two steps using parse_known_args
, for example:
ap = argparse.ArgumentParse()
ap.add_argument('-a')
args, unknown = ap.parse_known_args()
if args.a and '-x' in unknown:
ap.add_argument('-x')
args = ap.parse_args()

bereal
- 32,519
- 6
- 58
- 104
-
This does work, but I guess because of the parse_known_args() any argument is being accepted which I want to limit. Is there a way I can do that? Eg. say the name of the file is abc.py `python abc.py -a name -w surnane` The code shows no error with this, but I want it show an error like -w is not accepted. – Vipul Mar 04 '15 at 05:51
-
@Vipul sure, if you re-parse with `parse_args()` unconditionally. I updated the code in the answer. – bereal Mar 04 '15 at 06:17
-
thank you very much @bereal. `ap = argparse.ArgumentParser() ap.add_argument('-a') flag=0 args, unknown = ap.parse_known_args() if args.a and '-x' in unknown: ap.add_argument('-x') flag=1 args = ap.parse_args() if flag==1: print args.x ap.add_argument('-p',required=True)` Can you please tell me what's wrong with this code? – Vipul Mar 04 '15 at 06:36
-
@Vipul it's hard to tell because of the layout, but most likely because you're adding `-p` after `parse_args`. – bereal Mar 04 '15 at 07:03
-
I want to add `-p` only if -x is present in the command line. But I am not able to do that. I am sorry about the layout. – Vipul Mar 04 '15 at 07:22
-
@Vipul then you need to call `parse_known_args` after you add `-x` in the same branch again, and conditionally add `-p`, all the same way as for `-a` and `-x`. – bereal Mar 04 '15 at 07:37
-1
When designing command line arguments, follow the best practices/standards used in *nix systems.
- The order of arguments shouldn't matter
- You have to check in your program whether mandatory arguments are given if not give a useful message
If you are looking for example to use argparse
refer this link
Good luck!