user138530
user138530

Reputation: 1

python : NameError: name

After running successfully i suddenly see below error for python script. Not much experienced in python. The script fetch's information over 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

Below is the script.

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

Upvotes: 0

Views: 96

Answers (1)

chepner
chepner

Reputation: 532508

If requests.get raises an exception, no value is ever assigned to r. But you still try to call r.json() following that exception.

Upvotes: 1

Related Questions