Argparse: How to make mutually exclusive arguments optional?

I want to use my script as follows:

python test.py run python test.py stop 

and my code looks like this:

 parser = argparse.ArgumentParser() command_group = parser.add_mutually_exclusive_group(required=True) command_group.add_argument('run', help='run it', action='store_true') command_group.add_argument('stop', help='stop it', action='store_true') 

when I execute it, an exception is thrown:

 ValueError: mutually exclusive arguments must be optional 

so I am trying to add required=False when I add each argument. Then I get another exception:

 TypeError: 'required' is an invalid argument for positionals 

I'm confused.

+5
source share
2 answers

The best way to do this is to add one positional argument, which can have two options. Since you want it to be optional, use nargs='?' that means zero or once:

 parser = argparse.ArgumentParser() parser.add_argument('run', help='run or stop', nargs='?', choices=('run', 'stop')) 

If run is given, the value will be 'run' . If stop specified, it will be 'stop' . If none of them are specified, it will be None .


If you really want to use a mutually exclusive group, I’m not sure that you can do it exactly as you want. However, you can make them optional arguments by adding a hyphen:

 import argparse parser = argparse.ArgumentParser() command_group = parser.add_mutually_exclusive_group() command_group.add_argument('-run', help='run it', action='store_true') command_group.add_argument('-stop', help='stop it', action='store_true') 

Of course, the problem is that the user also needs to provide a hyphen, but this is the problem you can expect if you limit yourself this way.

+4
source

You can achieve this with nargs='?'

 parser = argparse.ArgumentParser() command_group = parser.add_mutually_exclusive_group() command_group.add_argument('run', help='run it', nargs='?') command_group.add_argument('stop', help='stop it', nargs='?') 

That will allow you to call the program with

 python test.py run 

or

 python test.py stop 

but not

 python test.py run stop 
+1
source

All Articles