AttributeError: 'Namespace'对象没有属性

时间:2022-03-14 17:10:17

I am writing a program that uses urllib2 to download CSV data from an http site. The program works fine when run within Python, however I am also trying to use argparse to be able to enter the url from the command line.

我正在编写一个程序,使用urllib2从http站点下载CSV数据。该程序在Python中运行时运行良好,但是我还试图使用argparse从命令行输入url。

I get the following error when I run it:

我运行时得到如下错误:

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'

I guess this is part of the urllib2 library because it is not code that I have written. Has anybody else encountered similar problems with either the argparse or urllib2 modules?

我想这是urllib2库的一部分,因为它不是我写的代码。有没有人在argparse或urllib2模块上遇到过类似的问题?

The relevant part of the code is as follows:

守则的有关部分如下:

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)

1 个解决方案

#1


8  

You're parsing command line arguments into args, which is a Namespace with attributes set to the parsed arguments. But you're passing this entire namespace to downloadData, rather than just the url. This namespace is then passed to urlopen, which doesn't know what to do with it. Instead, call downloadData(args.url).

您正在将命令行参数解析为args,这是一个带有已解析参数的属性的名称空间。但是您将整个命名空间传递给了downloadData,而不仅仅是url。然后将这个名称空间传递给urlopen,它不知道如何处理它。相反,叫downloadData(args.url)。

#1


8  

You're parsing command line arguments into args, which is a Namespace with attributes set to the parsed arguments. But you're passing this entire namespace to downloadData, rather than just the url. This namespace is then passed to urlopen, which doesn't know what to do with it. Instead, call downloadData(args.url).

您正在将命令行参数解析为args,这是一个带有已解析参数的属性的名称空间。但是您将整个命名空间传递给了downloadData,而不仅仅是url。然后将这个名称空间传递给urlopen,它不知道如何处理它。相反,叫downloadData(args.url)。