Skip to content Skip to sidebar Skip to footer

How To Iterate Over Arguments

I have such script: import argparse parser = argparse.ArgumentParser( description='Text file conversion.' ) parser.add_argument('inputfile', help

Solution 1:

Please add 'vars' if you wanna iterate over namespace object:

forargin vars(args):
     printarg, getattr(args, arg)

Solution 2:

Namespace objects aren't iterable, the standard docs suggest doing the following if you want a dictionary:

>>> vars(args)
{'foo': 'BAR'}

So

for key,value in vars(args).iteritems():
    # do stuff

To be honest I'm not sure why you want to iterate over the arguments. That somewhat defeats the purpose of having an argument parser.

Solution 3:

After

args = parser.parse_args()

to display the arguments, use:

print args # or print(args) in python3

The args object (of type argparse.Namespace) isn't iterable (i.e. not a list), but it has a .__str__ method, which displays the values nicely.

args.out and args.type give the values of the 2 arguments you defined. This works most of the time. getattr(args, key) the most general way of accessing the values, but usually isn't needed.

vars(args)

turns the namespace into a dictionary, which you can access with all the dictionary methods. This is spelled out in the docs.

ref: the Namespace paragraph of the docs - https://docs.python.org/2/library/argparse.html#the-namespace-object

Solution 4:

I'm using args.__dict__, which lets you access the underlying dict structure. Then, its a simple key-value iteration:

for k in args.__dict__:
  print k, args.__dict__[k]

Solution 5:

Parsing the _actions from your parser seems like a decent idea. Instead of running parse_args() and then trying to pick stuff out of your Namespace.

import argparse

parser = argparse.ArgumentParser(
                description='Text file conversion.')
parser.add_argument("inputfile", help="file to process", type=str)
parser.add_argument("-o", "--out", default="output.txt",
                help="output name")
parser.add_argument("-t", "--type", default="detailed",
                help="Type of processing")
options = parser._actions
for k in options:
    print(getattr(k, 'dest'), getattr(k, 'default'))  

You can modify the 'dest' part to be 'choices' for example if you need the preset defaults for a parameter in another script (by returning the options in a function for example).

Post a Comment for "How To Iterate Over Arguments"