python:NameError:名称

时间:2019-01-03 08:33:53

标签: python

成功运行后,我突然看到以下python脚本错误。在python方面经验不足。脚本通过API获取信息。 Python 2.7.12

/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

下面是脚本。

# 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()

1 个答案:

答案 0 :(得分:1)

如果requests.get引发异常,则不会为r分配任何值。但是您仍然可以尝试在该异常之后致电r.json()