Python AttributeError: 'Namespace' 对象没有属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28422883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:15:48  来源:igfitidea点击:

AttributeError: 'Namespace' object has no attribute

python

提问by Sam cd

I am writing a program that uses urllib2to download CSV data from an http site. The program works fine when run within Python, however I am also trying to use argparseto 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 urllib2library because it is not code that I have written. Has anybody else encountered similar problems with either the argparseor urllib2modules?

我猜这是urllib2库的一部分,因为它不是我写的代码。有没有其他人遇到过与argparseurllib2模块类似的问题?

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)

采纳答案by davidism

You're parsing command line arguments into args, which is a Namespacewith 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,这是一个Namespace属性设置为解析参数的属性。但是您将整个命名空间传递给downloadData,而不仅仅是 url。然后将此命名空间传递给urlopen,它不知道如何处理它。相反,调用downloadData(args.url).

回答by Andrii Abramov

Long story short.

长话短说。

Arguments in object returned from parser.parse_args()should be accessed via properties rather than via []syntax.

返回的对象中的参数parser.parse_args()应该通过属性而不是通过[]语法访问。

Wrong

错误的

args = parser.parse_args()
args['method']

Correct

正确的

args = parser.parse_args()
args.method

回答by jjjshade

I had this problem due to a whitespace before the option sting.

由于选项刺痛之前的空格,我遇到了这个问题。