[英]using argparse add_argument in for loop
I am trying to use parser.add_argument in a for loop but am getting an error. 我正在尝试在for循环中使用parser.add_argument,但遇到错误。 Following is my sample code and error. 以下是我的示例代码和错误。 Any help is appreciated.Thanks! 感谢您的帮助。
Am using an itemlist file in my example.It is a plain file with items listed in it as follows: 我在示例中使用的是itemlist文件,它是一个普通文件,其中列出了如下项目:
item1
item2
item3
test.py contains the following code test.py包含以下代码
#!/usr/bin/python
import re
import os
import string
import argparse
parser = argparse.ArgumentParser()
itemlist = open("itemlist").read().splitlines()
for item in itemlist:
print(item)
parser.add_argument(item)
version=parser.parse_args()
for item in itemlist:
print(getattr(version,item))
Running the script as ./test.py 1.00 2.00 3.00
以./test.py 1.00 2.00 3.00
运行脚本
Am expecting the output to be 我期望输出是
1.00
2.00
3.00
Error on running the program : 运行程序时出错:
parser.add_argument(item)
File "/usr/local/lib/python3.4/argparse.py",
if not args or len(args) == 1 and args[0][0] not in chars:
IndexError: string index out of range
This works if I just have one item. 如果我只有一件物品,这行得通。 It does not work if I have more than one item. 如果我有多个项目,它将不起作用。 What is that am doing wrong ? 那是怎么了?
You have an empty line at the end of the file. 文件末尾有一个空行。
I tested it and it worked fine (with python 3.4.3). 我对其进行了测试,并且工作正常(使用python 3.4.3)。 After adding an empty line at the end of itemlist
it fails with that error. 在itemlist
的末尾添加空行后,它将失败并显示该错误。
Edit: I've just checked argparse
source code and it seems that args
holds [""]
when the empty line is read. 编辑:我刚刚检查了argparse
源代码,当读取空行时,似乎args
持有[""]
。 So if you execute that in your console: 因此,如果您在控制台中执行该操作:
>>> [""][0][0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.