【发布时间】:2015-04-09 23:11:51
【问题描述】:
我正在编写一个程序,它使用 urllib2 从 http 站点下载 CSV 数据。该程序在 Python 中运行时运行良好,但我也尝试使用 argparse 以便能够从命令行输入 url。
运行时出现以下错误:
File "urlcsv.py", line 51, in downloadData
return urllib2.urlopen(url)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 396, in open
protocol = req.get_type()
AttributeError: 'Namespace' object has no attribute 'get_type'
我猜这是 urllib2 库的一部分,因为它不是我编写的代码。 argparse 或 urllib2 模块是否有其他人遇到过类似问题?
相关部分代码如下:
parser = argparse.ArgumentParser()
parser.add_argument("url")
def main():
"""Runs when the program is opened"""
args = parser.parse_args()
if args is False:
SystemExit
try:
csvData = downloadData(args)
except urllib2.URLError:
print 'Please try a different URL'
raise
else:
LOG_FILENAME = 'errors.log'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
)
logging.getLogger('assignment2')
personData = processData(csvData)
ID = int(raw_input("Enter a user ID: "))
if ID <= 0:
raise Exception('Program exited, value <= 0')
else:
displayPerson(ID)
main()
def downloadData(url):
return urllib2.urlopen(url)
【问题讨论】:
-
从给出的路径来看,堆栈跟踪当然表明
urllib2模块中存在问题。 -
向我们展示您编写的代码,以及您提供的输入。
-
您发布的代码不包含错误行。您将
req设置为什么? -
@tristan
protocol = req.get_type()行是 Python 标准库中 urllib2 模块的一部分;这不是我写的代码,而是urllib2.urlopen(url)调用的代码 -
但是您的示例中没有包含设置
protocol=req.get_type()的行,这意味着您仍然需要“发布代码”,可以这么说。我不知道你期望 req 存在哪里,因为没有成员方法urllib2.req。
标签: python