简体   繁体   English

Python-变量未定义,但我认为是

[英]Python - variable not defined but I think it is

I am pulling images from the Internet Archive as a test of some python code and I am incorporating the requests module. 我正在从Internet存档中提取图像,作为对某些python代码的测试,并且正在合并请求模块。 My code is as follows: (note, not the entire code, just the relevant section) 我的代码如下:(请注意,不是整个代码,而是相关的部分)

    image_results = []
    image_hashes = []
    session = requests.Session()


    for image in image_list:
        if txtUrl not in image:
            continue
    try:
        self.rslBox.AppendText("[v] Downloading %s" % image + "\n")
        self.rslBox.Refresh()
        response = session.get(image)
    except:
        self.rslBox.AppendText("[!] Failed to download: %s" % image + "\n")
        self.rslBox.Refresh()
#        continue

    if "image" in response.headers['content-type']:

        sha1 = hashlib.sha1(response.content).hexadigest()

        if sha1 not in image_hashes:
            image_hashes.append(sha1)
            image_path = "WayBackImages/%s-%s" % (sha1.image.split("/")[-1])

            with open(image_path, "wb") as fd:
                fd.write(response.content)

            self.rslBox.AppendText("[*] Saved %s" % images + "\n")
            self.rslBox.Refresh()

            info = pyexifinfo.get_json(image_path)
            info[0]['ImageHash'] = sha1
            image_results.append(info[0])

            image_results_json = json.dumps(image_results)
            data_frame = pandas.read_json(image_results_json)
            csv = data_frame.to_csv('results.csv')

    self.rslBox.AppendText("[*] Finished writing CSV to results.csv" + '\n')
    self.rslBox.Refresh()
    return

When I run my code, I get the following message: 当我运行代码时,收到以下消息:

Traceback (most recent call last):
File "C:\eclipse-workspace\test\tabbedPage.py", line 136, in OnSearch
if "image" in response.headers['content-type']:
NameError: name 'response' is not defined

But response is defined in the try statement - or so I would think. 但是响应是在try语句中定义的-大概我会这样认为。 It only complains on the if "image" section - why?? 它只在if“图像”部分抱怨-为什么?

I am new to python and I am using python3.6 and pydev with Eclipse. 我是python的新手,并且正在Eclipse中使用python3.6和pydev。 Thanks! 谢谢!

Something inside your try failed. 您尝试中的某些内容失败了。 Your except caught it handle the error but since there is no raise in it, it continues execution, but response is not set. 您的除外抓住了它来处理该错误,但是由于其中没有加价,因此它将继续执行,但是未设置响应。

It's because you are declaring response in the try block. 这是因为您在try块中声明了响应。 If the exception gets thrown then response is not declared. 如果引发异常,则不会声明响应。

A work around for this would be putting the code that relies on response being declared into that try block. 解决此问题的方法是将依赖于声明的响应的代码放入该try块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM