I took the following python recipe from Activestate.org, then I simply added the method for deleting the key, however I getting error 5, access denied, and the key it's only a fake key which I have just created to try out the function . Here 's the code
## {{{ http://code.activestate.com/recipes/576860/ (r2)
import win32api
import win32con
def regquerysubkeys(handle, key, keylist=[]):
#get registry handle
reghandle = win32api.RegOpenKeyEx(handle, key, 0, win32con.KEY_ALL_ACCESS)
try:
i = 0
#enumerates subkeys and recursively calls this function again
while True:
subkey = win32api.RegEnumKey(reghandle, i)
#the following is the line I added myself
win32api.RegDeleteKey(handle, key)
i += 1
#braintwister here ;-)
regquerysubkeys(handle, key + subkey + "\\", keylist)
except win32api.error as ex:
#If no more subkeys can be found, we can append ourself
if ex[0] == 259:
keylist.append(key)
#unexpected exception is raised
else:
raise
finally:
#do some cleanup and close the handle
win32api.RegCloseKey(reghandle)
#returns the generated list
print keylist
#call to the function
regquerysubkeys(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\suga\\")
Those are the errors I m getting in the console.
Traceback (most recent call last):
File "C:\EclipseWorkspaces\csse120\MMS-auto\test1.py", line 34, in <module>
regquerysubkeys(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\suga\\")
File "C:\EclipseWorkspaces\csse120\MMS-auto\test1.py", line 14, in regquerysubkeys
win32api.RegDeleteKey(handle, key)
pywintypes.error: (5, 'RegDeleteKey', 'Access is denied.')
Can anyone help out with it?
Are you running 64-bit Windows 7 by any chance? There were some changes in the structure of the registry to account for running both 32-bit and 64-bit programs that require that you use different APIs for deletion. The RegDeleteKey Win32 API documentation mentions using RegDeleteKeyEx in some cases. The Win32 API is difficult to use reliably from one major version of Windows to the next. Unfortunately, pywin32 does its best to hide a number of the headaches, but it still requires that you really know the Win32 API and its caveats before you can effectively use it.
Related
I am trying to build a Phasor Measurement Unit using Beaglebone Black rev 3. The following is the code. While running it gives an error as:
prussdrv_open open failed
Traceback (most recent call last):
File "/var/lib/cloud9/pmu.py", line 36, in <module>
pru.open(0) # open connection to PRU 0
SystemError: error return without exception set
The code goes here:
import pypruss as pru
import mmap
import numpy as np
import struct
import time
## MEMORY LOCATIONS ##
PRU_ICSS=0x4A300000
PRU_ICSS_LEN=512*1024
RAM_START=0x00000000
RAM1_START=0x00002000
RAM2_START=0x00012000
TOTAL_BUFFER_LEN=0x00000FA0
BUFFER_LEN=TOTAL_BUFFER_LEN/2
BUFFER1_START=RAM2_START+4
BUFFER2_START=BUFFER1_START+BUFFER_LEN
## FUNCTION DEFINITIONS ##
def processRawADC(value):
value=0x00000FFF&value
value=int(value)
value=(value*1.8)/(2^12)
return value
def channelID(value):
value=0x000F0000&value
value=value>>16
return value
## PRU SETUP ##
pru.modprobe( ) # enable uio_pruss module
pru.init( ) #initialize PRU
pru.open(0) # open connection to PRU 0
pru.pruintc_init( ) # configure interrupt handlers
pru.exec_program(0,"./oneshot.bin") # load assembly file
counter = 0
f=open("/dev/mem","r+b")
output=open("./results.txt","w")
while counter<10 :
start=time.time()
pru.wait_for_event(0)
ddr_mem=mmap.mmap(f.fileno( ),PRU_ICSS_LEN,offset=PRU_ICSS)
shared=struct.unpack('L ',ddr_mem[RAM2_START:RAM2_START+4])
print(shared[0])
if shared[0]==1 :
print ("buffer 1")
for i in range(0,500) :
fifo = struct.unpack ( 'L ' ,ddr_mem[BUFFER2_START+( i*4)
:BUFFER2_START+4+(i*4)])[0]
value=processRawADC(fifo)
channelNum=channelID(fifo)
output.write(str(channelNum)+","+str(value)+"nn")
counter += 1
pru.clear_event(0)
elif shared[0] == 2:
shared=struct.unpack('L ',ddr_mem[RAM2_START:RAM2_START+4])
print("buffer 2")
for i in range(0,500):
fifo=struct.unpack('L',ddr_mem[BUFFER2_START+(i*4) :BUFFER2_START+4+
(i*4)])[0]
value = processRawADC(fifo)
channelNum = channelID(fifo)
output.write(str(channelNum)+","+str(value)+"nn")
counter +=1
pru.clear_event(0)
end=time.time( )
#print end-start
f.close( )
output.close( )
pru.clear_event(0)
pru.pru_disable(0)
pru.exit ( )
I am unable to find, where is the mistake lies. Please Help.
Looks like there is a bug in PyPRUSS code.
Its pypruss_open function does not properly set exception information but returns an error indication (NULL). Python doesn't like when a function does so.
Looking at the pypruss_open source, it will fail in such way if prussdrv_open fails and returns -1 as an error indication. It in turn might fail either itself (if that device is already opened) or if __prussdrv_memmap_init fails.
Unfortunately, looks like there is no way to get information about the exact reason of the error.
What can you do to debug this issue? If you won't be able to find anything obvious (like missing /dev/uid0 after calling pru.modprobe()) then you can run your script with strace to see which system calls precede an error. Then you look at the source code under links I gave you above and see when exactly does the failure happen.
I'm hitting this exception with jsonpickle, when trying to pickle a rather complex object that unfortunately I'm not sure how to describe here. I know that makes it tough to say much, but for what it's worth:
>>> frozen = jsonpickle.encode(my_complex_object_instance)
>>> thawed = jsonpickle.decode(frozen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/jsonpickle/__init__.py",
line 152, in decode
return unpickler.decode(string, backend=backend, keys=keys)
:
:
File "/Library/Python/2.7/site-packages/jsonpickle/unpickler.py",
line 336, in _restore_from_dict
instance[k] = value
File "/Library/Python/2.7/site-packages/botocore/vendored/requests/packages/urllib3/packages/ordered_dict.py",
line 49, in __setitem__
root = self.__root
AttributeError: 'OrderedDict' object has no attribute '_OrderedDict__root'
I don't find much of assistance when googling the error. I do see what looks like the same issue was resolved at some time past for simpler objects:
https://github.com/jsonpickle/jsonpickle/issues/33
The cited example in that report works for me:
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict()))
OrderedDict()
>>> jsonpickle.decode(jsonpickle.encode(collections.OrderedDict(a=1)))
OrderedDict([(u'a', 1)])
Has anyone ever run into this themselves and found a solution? I ask with the understanding that my case may be "differently idiosynchratic" than another known example.
The requests module for me seems to be running into problems when I .decode(). After looking at the jsonpickle code a bit, I decided to fork it and change the following lines to see what was going on (and I ended up keeping a private copy of jsonpickle with the changes so I can move forward).
In jsonpickle/unpickler.py (in my version it's line 368), search for the if statement section in the method _restore_from_dict():
if (util.is_noncomplex(instance) or
util.is_dictionary_subclass(instance)):
instance[k] = value
else:
setattr(instance, k, value)
and change it to this (it will logERROR the ones that are failing and then you can either keep the code in place or change your OrderedDict's version that have __root)
if (util.is_noncomplex(instance) or
util.is_dictionary_subclass(instance)):
# Currently requests.adapters.HTTPAdapter is using a non-standard
# version of OrderedDict which doesn't have a _OrderedDict__root
# attribute
try:
instance[k] = value
except AttributeError as e:
import logging
import pprint
warnmsg = 'Unable to unpickle {}[{}]={}'.format(pprint.pformat(instance), pprint.pformat(k), pprint.pformat(value))
logging.error(warnmsg)
else:
setattr(instance, k, value)
I am trying to control a Tektronix RSA306 Spectrum Analyzer by using the API. The program finds the RSA300API.dll file but throws an error when searching and connecting to the device. The program I am running is an example from Tektronix. The setup I am currently using is Python 2.7.12 x64(Anaconda 4.1.1) on 64 bit Windows 7.
from ctypes import *
import numpy as np
import matplotlib.pyplot as plt
I am locating the .dll file with:
rsa300 = WinDLL("RSA300API.dll")
The error occurs when executing the search function:
longArray = c_long*10
deviceIDs = longArray()
deviceSerial = c_wchar_p('')
numFound = c_int(0)
serialNum = c_char_p('')
nomenclature = c_char_p('')
header = IQHeader()
rsa300.Search(byref(deviceIDs), byref(deviceSerial), byref(numFound))
if numFound.value == 1:
rsa300.Connect(deviceIDs[0])
else:
print('Unexpected number of instruments found.')
exit()
When running the following error messages appear:
C:\Anaconda2\python.exe C:/Tektronix/RSA_API/lib/x64/trial
<WinDLL 'RSA300API.dll', handle e47b0000 at 3ae4e80>
Traceback (most recent call last):
File "C:/Tektronix/RSA_API/lib/x64/trial", line 44, in <module>
rsa300.Search(byref(deviceIDs), byref(deviceSerial), byref(numFound))
File "C:\Anaconda2\lib\ctypes\__init__.py", line 376, in __getattr__
func = self.__getitem__(name)
File "C:\Anaconda2\lib\ctypes\__init__.py", line 381, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'Search' not found
The issue that I am having is that the 'Search' function is not found. What would be the solution to this problem?
Tektronix application engineer here.
The problem here is a mismatch of API versions. Your code is referencing an old version of the API (RSA300API.dll) and the error message is referencing a newer version of the API (RSA_API.dll). Make sure you have installed the most current version of the API and that you reference the correct dll in your code.
Here is a link to download the latest version of the RSA API (as of 11/1/16):
http://www.tek.com/model/rsa306-software
Here is a link to download the API documentation (as of 11/1/16). There is an Excel spreadsheet attached to this document that outlines the differences between old functions and new functions:
http://www.tek.com/spectrum-analyzer/rsa306-manual-6
Function names were changed in the new version using for the sake of clarity and consistency. The old version of the API didn't have prefixes for most functions, and it was unclear which functions were grouped together just from reading the function names. The new version of the API applies prefixes to all functions and it is now much easier to tell what functional group a given function is in just by reading its declaration. For example the old search and connect functions were simply called Search() and Connect(), and the new version of the functions are called DEVICE_Search() and DEVICE_Connect().
Note: I use cdll.LoadLibrary("RSA_API.dll") to load the dll rather than WinDLL().
DEVICE_Search() has slightly different arguments than Search(). Due to different argument data types, the new DEVICE_Search() function doesn't play as well with ctypes as the old Search() function does, but I've found a method that works (see code below).
Here is the search_connect() function I use at the beginning of my RSA control scripts:
from ctypes import *
import os
"""
################################################################
C:\Tektronix\RSA306 API\lib\x64 needs to be added to the
PATH system environment variable
################################################################
"""
os.chdir("C:\\Tektronix\\RSA_API\\lib\\x64")
rsa = cdll.LoadLibrary("RSA_API.dll")
"""#################CLASSES AND FUNCTIONS#################"""
def search_connect():
#search/connect variables
numFound = c_int(0)
intArray = c_int*10
deviceIDs = intArray()
#this is absolutely asinine, but it works
deviceSerial = c_char_p('longer than the longest serial number')
deviceType = c_char_p('longer than the longest device type')
apiVersion = c_char_p('api')
#get API version
rsa.DEVICE_GetAPIVersion(apiVersion)
print('API Version {}'.format(apiVersion.value))
#search
ret = rsa.DEVICE_Search(byref(numFound), deviceIDs,
deviceSerial, deviceType)
if ret != 0:
print('Error in Search: ' + str(ret))
exit()
if numFound.value < 1:
print('No instruments found. Exiting script.')
exit()
elif numFound.value == 1:
print('One device found.')
print('Device type: {}'.format(deviceType.value))
print('Device serial number: {}'.format(deviceSerial.value))
ret = rsa.DEVICE_Connect(deviceIDs[0])
if ret != 0:
print('Error in Connect: ' + str(ret))
exit()
else:
print('Unexpected number of devices found, exiting script.')
exit()
I wrote a script:
import pythoncom, pyHook
import time
from time import strftime,localtime
def OKBE(event):
log =str("log "+str(time.strftime("%d,%B",localtime()))+".txt")
f=open(str(log),"a")
if(str(event.Ascii)=="8"):
f.write("<--")
print("<--")
elif(str(event.Ascii)=="13"):
f.write("\nENTER "+str(time.strftime("%H,%M",localtime()))+"\n")
print("\nENTER\n")
elif(str(event.Ascii)=="32"):
f.write(" ")
else:
f.write(chr(event.Ascii))
print(str(event.Ascii))
print(chr(event.Ascii))
manager = pyHook.HookManager()
manager.KeyDown = OKBE
manager.HookKeyboard()
pythoncom.PumpMessages()
but any time the event is a or p and some other letters i get this error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Users\Miran\Desktop\Pythonprojekt\Keylogger\keylogger.pyw", line 10, in OKBE
log =str("log "+str(time.strftime("%d,%B",localtime()))+".txt")
TypeError: an integer is required
Anyone knows why?
Event is a class (or should i say, instance of a class), you can call information from the instance (see code below) such as 'event.key' will give you the ASCII character code. event.alt will return the status of the 'alt' key.
I remember dealing with a similar issue when writing a python keylogger (although it has been an age). I cant see anything immediately wrong with your code. My 'OKBE' function looked more like this.
def OnKeyboardEvent(self, event):
if (event.Ascii > 31 and event.Ascii < 127) or event.Ascii == 13 or event.Ascii == 9:
data = (event.WindowName, event.Window, event.Time, event.Ascii, event.Key, event.Alt)
print data # debugging
I believe using the above method catches most (if not all) of the usual keystrokes. Using that function above i created a class with other logging functions.
If you need anything else, or work out whats going on in your code, let me know :)
I think the issue is a bug... when i replace
log =str("log "+str(time.strftime("%d,%B",localtime()))+".txt")
by
log="log.txt"
anything works fine
I am facing difficulties in reading a registry key created by my software. However with the same code, I am able to read other keys.
installdir = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\MediaPlayer\\Player\\Extensions\\Types"
) #this works perfect
#installdir1 = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\MySoftware\\MyEvent\\IS"
) #this gives Filenotfound error
# list values owned by this registry key
try:
i = 0
while 1:
name, value, type = winreg.EnumValue(installdir, i)
print (repr(name))
i += 1
except WindowsError:
print ("Bot donf")
value, type = winreg.QueryValueEx(installdir, "10")
print("user is", repr(value))
value, type = winreg.QueryValueEx(winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\MySoftware\\MyEvent\\IS"), "v2")
print("user is", repr(value))
Traceback shows
Traceback (most recent call last):
File "D:/python_scripts/myclass.py", line 32, in <module>
value, type = winreg.QueryValueEx(winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\MySoftware\\MyEvent\\IS"), "v2")
FileNotFoundError: [WinError 2] The system cannot find the file specified
However Windows reg query is able to retrieve the value set.
#reg query HKLM\SOFTWARE\MySoftware\MyEvent\IS /v v2
HKEY_LOCAL_MACHINE\SOFTWARE\MySoftware\MyEvent\IS
v2 REG_DWORD 0x12
Any help will be highly appreciated
There are 2 views of the registry. There is the 32-bit registry view and the 64-bit registry view. By default and in most cases, 32-bit applications will only see the the 32-bit registry view and 64-bit applications will only see the 64-bit registry view.
The other view can be accessed by using the KEY_WOW64_64KEY or the KEY_WOW64_32KEY access flags.
If you are running 32-bit python and your key is part of the 64-bit registry view, you should use something like this to open your key:
winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\MySoftware\\MyEvent\\IS", access=winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
If you are running 64-bit python and your key is part of the 32-bit registry view, you should use something like this to open your key:
winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\MySoftware\\MyEvent\\IS", access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY)
If you know the key is always part of the same view, adding the proper KEY_WOW64_* access flag will ensure that it works no matter what your python architecture is.
In the most generic case, if you have variable python architecture and you do not know in advance in which view the key will be, you can try finding the key in your current view and try the other view next. It could look something like this:
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\MySoftware\\MyEvent\\IS")
except FileNotFoundError:
import platform
bitness = platform.architecture()[0]
if bitness == '32bit':
other_view_flag = winreg.KEY_WOW64_64KEY
elif bitness == '64bit':
other_view_flag = winreg.KEY_WOW64_32KEY
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\MySoftware\\MyEvent\\IS", access=winreg.KEY_READ | other_view_flag)
except FileNotFoundError:
'''
We really could not find the key in both views.
'''
For more information, check out Accessing an Alternate Registry View.