RightmireM
RightmireM

Reputation: 2492

Capture switch in a avriable via Argparse

Is there a way using Argparse to capture the switch and it's value as separate parameters?

I.e.

python MyScript.py --myswitch 10 --yourswitch 'fubar' --herswitch True

…results in something like …

MyScript.var1 == myswitch 
MyScript.var2 == 10 
MyScript.var3 == yourswitch 
MyScript.var4 == 'fubar' 
MyScript.var5 == herswitch 
MyScript.var6 == True

… or …

{'myswitch':10, 'yourswitch':'fubar', 'herswitch':True}

=== EDIT ===
This worked using just sys.argv. Is there way to do this with argparse. Is there any benefit to using argparse even if there IS a way?

def _parse_unknown_args(self, args):
    """"""
    scriptname = args.pop(0) # Just gets rid of it
    args_dict = {}
    flags_list = []
    key = None

    for item in args:
        # Must come first as a 'not'
        if not item.startswith('-'): 
            # This means is a value, not a switch
            # Try to add. If value was not preceded by a switch, error
            if key is None:
                # We got what appears t be a value before we got a switch
                err = ''.join(["CorrectToppasPaths._parse_unknown_args: ", "A value without a switch was found. VALUE = '", item, "' (", str(args), ")."])
                raise RuntimeError(err)
            else:
                # Add it to the dict
                args_dict[key] = item
                key = None # RESET!

        else: # '-' IS in item
            # If there is ALREADY a switch, add to flags_list and reset
            if key is not None: 
                flags_list.append(key)
                key = None # RESET!
            # Make it a key. always overrides.
            key = item
            while key.startswith('-'): key = key[1:] # Pop off the switch marker                

    # Last check. If key is not None here (at end of list)
    # It was at the end. Add it to flags
    if key is not None: flags_list.append(key)

    return args_dict, flags_list

===

bash-3.2# python correct_toppas_paths.py -a -b -c -set1 1 -set2 2 -d -e
args_dict= {'set1': '1', 'set2': '2'}
flags_list= ['a', 'b', 'c', 'd', 'e']

Upvotes: 0

Views: 46

Answers (1)

hpaulj
hpaulj

Reputation: 231395

Properly coded an argparse parser would produce a Namespace object like:

In [267]: args=argparse.Namespace(myswitch='10', yourswitch='fubar', herswitch=True)

It's a good idea when testing to print this object, e.g. print(args)

In [268]: args
Out[268]: Namespace(herswitch=True, myswitch='10', yourswitch='fubar')

Each of those arguments is an attribute, which you can access with (provided the names aren't something strange):

In [269]: args.myswitch
Out[269]: '10'

and the documentation indicates that you can easily turn it into a dictionary with vars:

In [270]: vars(args)
Out[270]: {'herswitch': True, 'myswitch': '10', 'yourswitch': 'fubar'}

The rest is just ordinary Python coding - accessing attributes of an object or keys/values of a dictionary.

Upvotes: 1

Related Questions