python - using argparse add_argument in for loop -


i trying use parser.add_argument in loop getting error. following sample code , error. appreciated.thanks!


am using itemlist file in example.it plain file items listed in follows:

item1 item2 item3 

test.py contains following code

#!/usr/bin/python  import re import os import string import argparse  parser = argparse.argumentparser()  itemlist = open("itemlist").read().splitlines() item in itemlist:   print(item)   parser.add_argument(item)  version=parser.parse_args() item in itemlist:   print(getattr(version,item)) 

running script ./test.py 1.00 2.00 3.00

am expecting output

1.00 2.00 3.00 

error on running program :

 parser.add_argument(item)   file "/usr/local/lib/python3.4/argparse.py",     if not args or len(args) == 1 , args[0][0] not in chars: indexerror: string index out of range 

this works if have 1 item. not work if have more 1 item. doing wrong ?

you have empty line @ end of file.

i tested , worked fine (with python 3.4.3). after adding empty line @ end of itemlist fails error.

edit: i've checked argparse source code , seems args holds [""] when empty line read. if execute in console:

>>> [""][0][0] traceback (most recent call last):   file "<stdin>", line 1, in <module> indexerror: string index out of range 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -