Skip to content

Instantly share code, notes, and snippets.

@WingTillDie
Last active July 16, 2023 23:41
Show Gist options
  • Save WingTillDie/0ef4dcfb13fbba84c1f9f52c2a324003 to your computer and use it in GitHub Desktop.
Save WingTillDie/0ef4dcfb13fbba84c1f9f52c2a324003 to your computer and use it in GitHub Desktop.
Parse arbitrary number of keyword arguments
#!/usr/bin/env python3
import argparse
def parse_args():
usage = 'kwarg-nargs.py [-h] [pos_args ...] [-dict_args [value] ... ] ...'
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('pos_args', nargs='*')
#args, list_kwargs = parser.parse_known_args('asdf asdg --few wegew ewgew --wewg'.split())
args, list_kwargs = parser.parse_known_args()
pos_args = args.pos_args
parser_kwargs = argparse.ArgumentParser(
usage=usage,
description='positional arguments:\n pos_args',
formatter_class=argparse.RawDescriptionHelpFormatter,
)
for arg in list_kwargs:
if arg[0] == '-':
if arg != '-h' and arg != '--help':
parser_kwargs.add_argument(arg, nargs='*')
args2 = parser_kwargs.parse_args(list_kwargs)
dict_args = vars(args2)
for key, value in dict_args.items():
if len(value) == 0:
dict_args[key] = None
elif len(value) == 1:
dict_args[key] = value[0]
return pos_args, dict_args
pos_args, dict_args = parse_args()
def test__parse_args(*pos_args, **dict_args):
print(pos_args)
print(dict_args)
test__parse_args(*pos_args, **dict_args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment