Can argparse associate positional arguments with named arguments?

I would like to associate positional arguments with the "state of argument" that exists when they occur. For example, the following command:

script.py -m 1 foo -r 2 bar -r 7 baz -m 6 quux

The following associations should be formed:

foo:  m=1, r=0 (default value for r)
bar:  m=1, r=2
baz:  m=1, r=7
quux: m=6, r=7

Can this be done using the module argparse?

+5
source share
1 answer

, , sys.argv - , , "" ( , , , ), . , sys.argv - . condition . () .

import argparse
import sys
import copy
import os

def split_list(lst,condition):
    current=[]
    out=[current]
    for arg in lst:
        current.append(arg)
        if(condition(arg)):
            current=[]
            out.append(current)

    return out


parser=argparse.ArgumentParser()
parser.add_argument('-m',action='store')
parser.add_argument('-r',default='0',action='store')
#pieces=split_list(sys.argv[1:],os.path.isfile)
pieces=split_list(sys.argv[1:],lambda x: x in ('foo','bar','baz','quux'))
options={} #use collections.OrderedDict if order matters -- or some more suitable data structure.
default=argparse.Namespace()
for args in pieces:
    if(not args):
        continue
    ns=copy.deepcopy(default)
    default=parser.parse_args(args[:-1],namespace=ns)
    options[args[-1]]=default

print (options)
+1

All Articles