Python:winreg module :Windows 7:None is not valid HKEY error - python

I ran into issues while reading registry value for windows 7 winth winreg module .Any pointers to resolve the same?
Code :
try:
ParentKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")
i = 0
while 1:
name, value, type = _winreg.EnumValue(ParentKey, i)
print repr(name),
i += 1
except Exception as e:
print(Exception(e))
ParentKey =_winreg.DisableReflectionKey(ParentKey)
temp = _winreg.QueryValueEx(ParentKey, 'DisplayName')
temp1 = _winreg.QueryValueEx(ParentKey, 'DisplayVersion')
temp2 = _winreg.QueryValueEx(ParentKey, 'Publisher')
temp3 = _winreg.QueryValueEx(ParentKey, 'InstallLocation')
display = str(temp[0])
display_ver=str(temp1[0])
display_p=str(temp2[0])
display_loc=str(temp3)
print ('Display Name: ' + display + '\nDisplay version: ' + display_ver + '\nVendor/Publisher: ' + display_p +'\nRegkey: ' + display_loc +'\nInstall Location: ' )
Output:
[Error 259] No more data is available
Traceback (most recent call last):
File "C:\Users\Test\workspace\Pythontests\src\test.py", line 24, in <module>
temp = _winreg.QueryValueEx(ParentKey, 'DisplayName')
TypeError: None is not a valid HKEY in this context
**strong text**

This line:
ParentKey = _winreg.DisableReflectionKey(ParentKey)
will return None. The function DisableReflectionKey is not documented as returning anything (success or failure is indicated by whether or not an exception is raised). Such a function that does not return anything returns None implicitly. Since you bind the returned value to ParentKey, that variable will holds None from that point on.
So, of course the subsequent call,
_winreg.QueryValueEx(ParentKey, 'DisplayName')
will fail since QueryValueEx requires a defined key (not None) to work.

Related

Handling key error in python

The below function parses the cisco command output,stores the output in dictionary and returns the value for a given key. This function works as expected when the dictionary contains the output. However, if the command returns no output at all the length of dictionary is 0 and the function returns a key error . I have used exception KeyError: But this doesn't seem to work.
from qa.ssh import Ssh
import re
class crypto:
def __init__(self, username, ip, password, machinetype):
self.user_name = username
self.ip_address = ip
self.pass_word = password
self.machine_type = machinetype
self.router_ssh = Ssh(ip=self.ip_address,
user=self.user_name,
password=self.pass_word,
machine_type=self.machine_type
)
def session_status(self, interface):
command = 'show crypto session interface '+interface
result = self.router_ssh.cmd(command)
try:
resultDict = dict(map(str.strip, line.split(':', 1))
for line in result.split('\n') if ':' in line)
return resultDict
except KeyError:
return False
test script :
obj = crypto('uname', 'ipaddr', 'password', 'router')
out = obj.session_status('tunnel0')
status = out['Peer']
print(status)
Error
Traceback (most recent call last):
File "./test_parser.py", line 16, in <module>
status = out['Peer']
KeyError: 'Peer'
The KeyError did not happend in the function session_status,it is happend in your script at status = out['Peer'].So your try and except in session_status will not work.you should make a try and except for status = out['Peer']:
try:
status = out['Peer']
except KeyError:
print 'no Peer'
or :
status = out.get('Peer', None)
Your exception is not in the right place. As you said you just return an empty dictionary with your function. The exception is trying to lookup the key on empty dictionary object that is returned status = outertunnel['Peer']. It might be easier to check it with the dict get function. status = outertunnel.get('Peer',False) or improve the test within the function session_status, like testing the length to decide what to return False if len(resultDict) == 0
This explains the problem you're seeing.
The exception happens when you reference out['Peer'] because out is an empty dict. To see where the KeyError exception can come into play, this is how it operates on an empty dict:
out = {}
status = out['Peer']
Throws the error you're seeing. The following shows how to deal with an unfound key in out:
out = {}
try:
status = out['Peer']
except KeyError:
status = False
print('The key you asked for is not here status has been set to False')
Even if the returned object was False, out['Peer'] still fails:
>>> out = False
>>> out['Peer']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
out['Peer']
TypeError: 'bool' object is not subscriptable
I'm not sure how you should proceed, but dealing with the result of session_status not having the values you need is the way forward, and the try: except: block inside the session_status function isn't doing anything at the moment.

Distributed system: Raise error thrown on server side on client side

I have just started to create a distributed system that now got a single server and a bunch of clients. The language used is python and communication is done using sockets and JSON. When an error occurs on the server-side I send the error class-name and the error arguments to the client-side like this:
except Exception as e:
jsonResult = {"error":
{
"name":e.__class__.__name__,
"args": e.args
}
}
jsonResult = json.dumps(jsonResult)
jsonResult += "\n"
return jsonResult
And then try to raise it on the client-side like this:
errorFunc = decodedReply["error"]["name"]
args = decodedReply["error"]["args"]
print (args)
# Builds and appends the argumentstring to the error class-name.
errorFunc += '('
for arg in args:
# Handles when the argument is a string.
if isinstance(arg, str):
errorFunc += '\'' + arg + '\','
else:
errorFunc += arg + ','
# Removes the extra ',' from the string before adding the last ')'.
errorFunc = errorFunc[:-1]
errorFunc += ')'
# Debugging print.
print ("Here: " + errorFunc)
raise exec(errorFunc)
When I do this I get the error
TypeError: exceptions must derive from BaseException
From what I read here: Error exception must derive from BaseException even when it does (Python 2.7)
it looks like I have to declare it as a class. Is there anyway to get around that?
According to python you are raising something which is not an exception:
>>> type(exec("ValueError('ABC')"))
<class 'NoneType'>
You need to rewrite your code to have this:
>>> errorFunc = "ValueError('ABC')"
>>> exec('raise ' + errorFunc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
ValueError: ABC

Try function not running correctly

try:
left_break = signs_pos[dave - 1]
except IndexError:
left_error = True
try:
right_break = signs_pos[dave + 1]
except IndexError:
right_error = True
if left_error == True:
current_cal = user_input[:right_break]
elif right_error == True:
current_cal = user_input[left_break:]
else:
current_cal = user_input[left_break:right_break]
I've only started looking at try functions and I need some help with this. What I would like to happen is that if when it tries to find left_break and it gives an error it will set left_error to be true. But if it does not give an error left_break will be set properly.
When the code runs and either right or left does not give an error it does not set left_break or right_break properly.
Traceback (most recent call last):
File "C:\Users\Max\Desktop\MaxsCal.py", line 170, in <module>
current_cal = user_input[:right_break]
NameError: name 'right_break' is not defined
This is the error I get without the try function.
Traceback (most recent call last):
File "C:\Users\Max\Desktop\MaxsCal.py", line 157, in <module>
right_break = signs_pos[dave + 1]
IndexError: list index out of range
Both right_error and left_error will not be true.
The reason why this is happening, is that because you are trying to assign something to a variable inside a try/except, it will not actually exist if you raised an exception.
Here is a simple example to clarify this:
try:
x = 6 / 0
except ZeroDivisionError:
print('this failed')
print(x)
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
Now, to remedy this and you are looking to actually use the variable even if it fails in the try/except, you want to declare it before you are calling the thing that might fail.
x = 0
try:
x = 6 / 0
except ZeroDivisionError:
print('this failed')
print(x)
>>> print(x)
>>> 0
Or even inside your try works, but before what you are calling:
try:
x = 0
x = 6 / 0
except ZeroDivisionError:
print('this failed')
print(x)
>>> print(x)
>>> 0
As mentioned to me in the comments, you could also set a default in your except:
try:
x = 6 / 0
except ZeroDivisionError:
print('this failed')
x = 0
print(x)
>>> print(x)
>>> 0
left_break and right_break are only available within the scope of the try block. You can either define them before the try/except block or add an else block to the exception, as discussed in this thread.
Your error is coming from the fact that the variable is out of scope. Right break is only in scope within the try block, change it to
right_break = None
try:
right_break = signs_pos[dave + 1]
except IndexError:
right_error = True

Cannot concatenate 'str' and 'Nontype' objects error despite all arguments being pure string

I'm writing this python program and I'm getting this really confusing error in random. Here's part of my script:
Part of code in ai.py (starting at line #133)
elif (config.var0 < config.var1):
message = "SUCCESS_0021! var0 successfully adjusted."
print message
aux_func.write_log(message)
config.var0 = float(config.var1)
config.ask_trail = (1.0 + config.var2) * config.var3
The write_log function in aux_func.py file looks like this starting line #43
def write_log (message):
log_file = open(current_dir + '//logs//' + date_stamp(), 'a+')
temp_write = "\n " + time_stamp() + " : " + str(message)
log_file.write(temp_write)
log_file.close()
This works just fine and writes log file as expected most of the times. But, when I run this script for a while, then the console has this weird message that says:
Traceback <most recent call last):
File "main1.py", line 102, in <module>
func_flag = ai.decide()
File "C:\project\ai.py", line 137, in task_decide
aux_func.write_log(message)
File "C:\project\aux_func.py", line 45, in write_log
temp_write = "\n " + time_stamp() + " : " + str(message)
TypeError: cannot concatenate 'str' and 'NoneType' objects
The ai.py function is called from main1.py function.
I don't understand this error and I have banged my head against the wall to try and understand why I get this. The message is perfectly a string and I don't see any 'NoneType' objects in my the code where the error is being shown.
EDIT: Sorry, forgot to give you the time_stamp() code, here you go:
def time_stamp():
flag = 0
current_time = ''
system_date_time = str (datetime.datetime.now())
while (system_date_time == None):
system_date_time = str (datetime.datetime.now())
for c in system_date_time:
if (c == ' '):
flag = 1
if (c != '.'):
if (flag == 1):
current_time += c
else:
pass
else:
return current_time
It is the time_stamp() callable; it returns None.
Nothing else on that line could be None as they are either string literals, or the result of the str() function:
temp_write = "\n " + time_stamp() + " : " + str(message)
hence, the only remaining candidate is time_stamp().

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

Categories

Resources