I have such script:
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") args = parser.parse_args() for arg in args: print(arg)
But it doesnt work. I get error:
TypeError: 'Namespace' object is not iterable
How to iterate over arguments and their value?
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
The variable $@ is the array of all the input parameters. Using this variable within a for loop, we can iterate over the input and process all the arguments passed.
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.
Please add 'vars' if you wanna iterate over namespace object:
for arg in vars(args): print arg, getattr(args, arg)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With