Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over arguments

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?

like image 572
user3654650 Avatar asked Nov 28 '14 02:11

user3654650


People also ask

How do you pass arguments in a script?

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.

How do I pass multiple arguments to a shell 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 …

What is $@ in bash?

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.

Which variable should be used to iterate through all the command line inputs?

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.


2 Answers

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.

like image 32
Christophe Biocca Avatar answered Nov 15 '22 23:11

Christophe Biocca


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

 for arg in vars(args):      print arg, getattr(args, arg) 
like image 191
James Avatar answered Nov 15 '22 22:11

James