I'm trying to group arguments such that the user can do either:
python sample.py scan -a 1 -b 2
or
python sample.pt save -d /tmp -n something
here is my code:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='this is the description'
)
parser.add_argument('op', choices=['scan','save'], help='operation', default='scan')
root_group = parser.add_mutually_exclusive_group()
group1 = root_group.add_argument_group('g1', 'scan')
group1.add_argument('-a', help='dir1')
group1.add_argument('-b', help='dir2')
group2 = root_group.add_argument_group('g2', 'save')
group2.add_argument('-d', help='dir')
group2.add_argument('-n', help='name')
args = parser.parse_args()
print args
as I run python sample.py --help
I'm getting an error. Can someone please tell me how to fix it?
Traceback (most recent call last):
File "sample.py", line 18, in <module>
args = parser.parse_args()
File "C:\Python27\lib\argparse.py", line 1688, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "C:\Python27\lib\argparse.py", line 1720, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "C:\Python27\lib\argparse.py", line 1926, in _parse_known_args
start_index = consume_optional(start_index)
File "C:\Python27\lib\argparse.py", line 1866, in consume_optional
take_action(action, args, option_string)
File "C:\Python27\lib\argparse.py", line 1794, in take_action
action(self, namespace, argument_values, option_string)
File "C:\Python27\lib\argparse.py", line 994, in __call__
parser.print_help()
File "C:\Python27\lib\argparse.py", line 2313, in print_help
self._print_message(self.format_help(), file)
File "C:\Python27\lib\argparse.py", line 2287, in format_help
return formatter.format_help()
File "C:\Python27\lib\argparse.py", line 279, in format_help
help = self._root_section.format_help()
File "C:\Python27\lib\argparse.py", line 209, in format_help
func(*args)
File "C:\Python27\lib\argparse.py", line 317, in _format_usage
action_usage = format(optionals + positionals, groups)
File "C:\Python27\lib\argparse.py", line 388, in _format_actions_usage
start = actions.index(group._group_actions[0])
IndexError: list index out of range
and if I add action='store_const', the error goes away and a new error occurrs asking for 4 inputs.