首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python : NameError:名称

python : NameError:名称
EN

Stack Overflow用户
提问于 2019-01-03 16:33:53
回答 1查看 56关注 0票数 0

运行成功后,我突然看到python脚本出现以下错误。在python方面没有太多经验。该脚本通过API获取信息。Python 2.7.12

代码语言:javascript
复制
/usr/local/lib/python2.7/dist-packages/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown.
  warnings.warn(warning, RequestsDependencyWarning)
Traceback (most recent call last):
  File "fetch-drives-ncpa.py", line 31, in <module>
    data = r.json()
NameError: name 'r' is not defined

下面是脚本。

代码语言:javascript
复制
# importing the requests library
import requests
import json
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# defining a params dict for the parameters to be sent to the API
PARAMS = {'token':'dddsxsdsdsd','units':'l'}

openfiledrives = open("device_drivelist.txt", 'w')
openfiledrives.truncate(0)
openfile = open('device_list.txt')

for devicename in openfile.readlines():
        devicename = devicename.strip()
        # api-endpoint
        URL = "https://"+devicename+":5666/api/"
        try:
                r = requests.get(url = URL, params = PARAMS, verify=False,timeout=30)
                r.raise_for_status()
        except requests.exceptions.HTTPError as errh:
                print ("Http Error:",errh)
        except requests.exceptions.ConnectionError as errc:
                print ("Error Connecting:",errc)
        except requests.exceptions.Timeout as errt:
                print ("Timeout Error:",errt)
        except requests.exceptions.RequestException as err:
                print ("OOps: Something Else",err)

        # extracting data in json format
        data = r.json()

        Machine = data['root']['system']['node']
        # print the keys and values
        for i in data['root']['disk']['logical']:
                Drive = data['root']['disk']['logical'][i]['device_name']
                FreeSpace = data['root']['disk']['logical'][i]['free']
                TotalSpace = data['root']['disk']['logical'][i]['total_size']
                FSType=data['root']['disk']['logical'][i]['opts']
                #print Machine.lower(),Drive[0],FreeSpace[0],TotalSpace[0]
                #openfiledrives.write('{0}\t{1}\t{2:.0f}\t{3:.0f}\n'.format(Machine.lower(),Drive[0],FreeSpace[0],TotalSpace[0]))
                if FSType != 'ro,cdrom':
                        openfiledrives.write('{0}\t{1}\t{2:.0f}\n'.format(Machine.lower(),Drive[0],FreeSpace[0]))

openfile.close()
openfiledrives.close()
EN

回答 1

Stack Overflow用户

发布于 2019-01-03 22:04:39

如果requests.get引发异常,则不会为r赋值。但是您仍然尝试在该异常之后调用r.json()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54023835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档