Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse for unknown number of arguments and unknown names

I'd like to fetch all parameters passed to sys.argv that have the format
someprogram.py --someparameter 23 -p 42 -anotherparam somevalue.

Result I'm looking for is a namespace containing all the variables, already parsed.

To my understanding, argparse is expecting the user to define what are the parameters he is expecting.

Any way to do that with argparse ? Thanks !

like image 233
jhagege Avatar asked Jul 10 '18 14:07

jhagege


1 Answers

If you know that the parameters will always be given in the format --name value or -name value you can do it easily

class ArgHolder(object):
    pass

name = None
for x in sys.argv[1:]:
    if name:
        setattr(ArgHolder, curname, x)
        name = None

    elif x.startswith('-'):
        name = x.lstrip('-')

Now you will have collected all arguments in the class ArgHolder which is a namespace. You may also collect the values in an instance of ArgHolder

like image 58
mementum Avatar answered Nov 11 '22 03:11

mementum