I've got a fairly simple USB HID device that I've been trying to figure out how to read from and write to using Python. I've been able to read from it using PyWinUSB, but the problem comes in when I try to write to it. Trying to write to it makes things explode.
For example:
device = hid.HidDeviceFilter(vendor_id = 0x0003, product_id = 0x1001).get_devices()[0]
This works fine. Then for reading raw data, which is all that I care about right now (I'll work with that once I can figure out how to write to the cursed thing):
def readData(data):
print(data)
return None
This works fine (in fact, it was quite exciting when I got to see it work). So I would assign the data handler like so:
device.set_raw_data_handler(readData)
And every time I hit a button, it's fine. The data comes through as you would expect. Which is great!
The problem comes when I want to write to the device.
Following the sample simple_send file as a template (which was probably not the best choice), I would do the following:
report = device.find_output_reports()[0]
Which would return a report object with a dictionary holding 4 entries. Is that correct? Do you write to a device using the output_reports object? Trying to do so by setting the report value to ANYTHING:
report[<key>] = "pneumonoultramicroscopicvolcanoconiosis"
report.send()
This would keep returning some obnoxious error that I can't interpret:
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
report.send()
File "C:\Python27\lib\site-packages\pywinusb-0.3.1-py2.7.egg\pywinusb\hid\core.py", line 1446, in send
self.__prepare_raw_data()
File "C:\Python27\lib\site-packages\pywinusb-0.3.1-py2.7.egg\pywinusb\hid\core.py", line 1401, in __prepare_raw_data
byref(self.__raw_data), self.__raw_report_size) )
File "C:\Python27\lib\site-packages\pywinusb-0.3.1-py2.7.egg\pywinusb\hid\winapi.py", line 382, in __init__
raise helpers.HIDError("hidP error: %s" % self.error_message_dict[error_code])
HIDError: hidP error: data index not found
I'm using Windows 7. I've managed to find (finally) a reference for the HID DLL exported functions, and I don't HAVE to (or, for that matter even really WANT to) use the PyWinUSB library. I just want to make this work, and it didn't seem like it would be that tough, but it has been.
Can someone tell me what it is I've been doing wrong here?
Thanks.
Also, I tried tracing the error call, and made it so far before the program just closed which was kind of disheartening.
i made it work with this
buffer= [0xFF]*33 # 33 = report size + 1 byte (report id)
buffer[0]=0x0 # report id
buffer[1]=0xFE
buffer[2]=0x00
buffer[3]=0xFF
out_report.set_raw_data(buffer)
out_report.send()
dev.close()
For me worked only this:
report.send([0x70, ..., 0x73 ])
The function call sequence with set_raw_data([0x70, ..., 0x73) and subsequent send() didn't work for me.
Related
I am learning about exceptions and so performing some file operations and testing various parts of code that can possibly generate exceptions while working with files in Python. I am executing this Python 2.7 code on Canopy.
#!/usr/bin/python
import os
try:
fp = open('testfile', 'r')
except IOError:
print 'File not opened successfully'
else:
print 'File opened successfully'
try:
fp.write('Hello!')
except IOError:
print 'Write not allowed on this file'
else:
print 'Write successful'
try:
fp.close()
except IOError:
print 'File not closed properly'
else:
print 'File closed successfully'
finally:
if os.path.exists(fp.name):
os.remove(fp.name)
When I execute this code, I get the following output:
File not opened properly
NameErrorTraceback (most recent call last)
/home/sr/Python/tcs.py in ()
--> 185 if os.path.exists(fp.name)
NameError: name 'fp' is not defined
But if I change the access mode of file to 'w', Then everything seems to work properly with the correct output as:
File opened successfully
Write successful
File closed successfully
I cannot understand why the 'r' mode is not making the file open properly and thus the fp file object is not created. Please help me figure the problem out.
P.S.: Also I would like to know if there is a better way of implementing the same thing. But this is optional.
Explanation
The error combined with your printout should be pretty self-explanatory: the variable fp does not exist if you can't open the file.
The mode 'r' indicates that you want to open the file for reading. You can not read something that is not there, so you end up going to the finally block in your code after processing the IOError. But the error occurs before fp was set, so there is no variable fp, hence the error. [Solutions below]
The mode 'w' indicates that you want to open for writing, but from scratch. There is also an 'a' mode to append if the file already exists. You can write to a non-existent file just fine, so your code does not fail. In fact, if the file did exist in 'w' mode, it would be trucated and any previous contents would be lost.
Try creating an empty file and running with mode 'r'. You should get an exception that prints 'Write not allowed on this file'. That is because, as your error message correctly indicates, writing to a file opened in read mode is not allowed.
Improvements
There are two major improvements that you can make to your code. One is fixing the logical flaws, the other is a major stylistic improvement using with statements.
You have two major logic errors. The first is in the outermost finally block that you already saw. The simplest fix is moving the contents of the finally block into the else, since you don't have any action to take if the file was not opened. Another solution is to refer to the file name you are trying to open in the first place. For example, you could store the file name into a variable and use that:
filename = 'testfile'
try:
fp = open(filename, 'r')
...
finally:
if os.path.exists(filename):
os.remove(filename)
The second major logic error is that you do not close the file if your write fails. Notice that you call fp.close() only in the else clause of your try block. If should instead appear in a finally block. The print statement should of course stay in the else. Change
else:
print 'Write successful'
try:
fp.close()
...
to
else:
print 'Write successful'
finally:
try:
fp.close()
...
The entire code can be improved stylistically by using with blocks to manage your file operations. The obvious way to do this is as follows:
fname = 'testfile'
with open(fname, 'r') as fp:
fp.write('Hello!')
if os.path.exists(fname):
os.remove(fname)
You will not get as many detailed messages when things fail, but overall, this code is cleaner, shorter and more robust than what you have. It guarantees that the file will be closed whether or not an exception occurred anywhere along the way. If you need the detailed error output that you currently have, keep using the current try blocks. The reason that most people will prefer with is that any error that occurs will have a detailed desciption and a line number that it happened on, so you basically get all the necessary information with a lot less work.
Here are some additional resources to help you understand with and context managers:
Understanding Python's "with" statement (from effbot.org)
Official documentation for with
SO 1, 2, 3, 4
Here's the simplified example. I have this code:
from pygame import mixer
def say():
mixer.init()
mixer.music.load('/home/orif/Downloads/english.wav')
mixer.music.play()
while mixer.music.get_busy():
time.sleep(0.2)
It displays some warnings but works perfectly. The warnings:
ALSA lib pcm_dsnoop.c:606:(snd_pcm_dsnoop_open) unable to open slave
ALSA lib pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave ALSA
lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA
lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM
cards.pcm.center_lfe ALSA lib pcm.c:2266:(snd_pcm_open_noupdate)
Unknown PCM cards.pcm.side ALSA lib
pcm_dmix.c:1029:(snd_pcm_dmix_open) unable to open slave
But if I run it in child process it won't:
def test():
talk_process = Process(target=say)
talk_process.start()
print 'waiting for the process...'
talk_process.join()
print 'done'
It prints the same warnings, then:
waiting for the process...
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/home/orif/Projects/example.py", line 178, in say
mixer.init()
error: No available audio device
done
If I do the same but with threading, it runs fine. I have tried what's written here and here. In the former link the solution in the comments almost helped me. I initialized mixer just before running the subprocess:
mixer.init()
talk_process.start()
But now the sound doesn't play, and the waiting loop while mixer.music.get_busy() is endless
What is happening and how to solve it?
Alright, my bad, I didn't check everything before asking the question. The code snippet above is a bit incomplete. There were also several imports what I thought was irrelevant. I imported my module where I use SpeechRecognition. In the code there was a function declaration which looked like this:
def foo(m = sr.Microphone()):
pass
At the moment of writing that code I thought, since Python executes everything in the last possible moment, it should work too. And when I ran that code, it did, so everything seemed to be fine. I was wrong.
At the moment of function declaration, that method call was not treated as "if no argument given, substitute with the result of this call", but it was actually called and the return value was used as an optional argument. I don't know what exactly went wrong with sound card while multiprocessing, but that's why I got those weird and obscure error messages.
Here's a little example to show what was causing the issue:
def foo():
print 'TRIGGERED'
return 42
def bar(a = foo()):
print a
if __name__ == '__main__':
pass
Though seems it should do nothing, this code actually prints TRIGGERED. So, instead of assigning values to optional arguments like that, I do something like this:
def foo(a = None):
a = 'bar' if a is None else a
I've been running a program located here:
https://github.com/dennybritz/cnn-text-classification-tf
and the base code works fine with the posted example. But, I tried to split new data into a train/test split and then it gives me errors. The program trains on the train data I give it, but come evaluation time I get this error:
Traceback (most recent call last):
File "./eval.py", line 81, in correct_predictions = float(sum(all_predictions == y_test))
TypeError: 'bool' object is not iterable`
From the eval.py code I located where the problem is in this loop:
for x_test_batch in batches:
batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0})
all_predictions = np.concatenate([all_predictions, batch_predictions])
Wherein sess.run returns nothing and batch_predictions becomes an empty array, leading to a value error later on. Also of note:
batch_predictions is always empty.
x_test_batch is non-empty for every batch.
all_predictions is also always empty.
I brought up the issue with the github owner but he recommended I trace through execution. This is my first time using Tensorflow and I am unable to access their website. If anyone can
Tell me what my issue is
or
Tell me how to trace through the graph execution to find it
I would be endlessly appreciative. Thank you to anyone who reads this!
you say sess.run does not return anything, perhaps you could print x_test_batch before running sess.run and look whats inside, perhaps its empty, which is not your intention i think
Hope you can help me out, first question I ask myself but I am always impressed by the professional answers I find here!
I am using xlwings to both read and write data from .xls files. I am not a seasoned programmer, and I make mistakes. From time to time, this means rebooting processes, Python and what-not.
Every now and again, I would get the following AttributeError upon calling Workbook(). The real problem is not that I don't have a clue what is happening (I tried reading the modules the error diagnostics reference to, but they are written on a level of Python that is beyond my skills), but that restarting and even rebooting(!) my laptop don't (always) solve the problem.
I wish I could give some clues as to what is happening, but it appears to be a randomly occurring problem and right now, three reboots and several restarts didn't fix it. Google can't help either. I must have run my program a hundred times by now and it wasn't always a problem! The error message, upon simply calling Workbook():
wb = Workbook()
Traceback (most recent call last):
File "<ipython-input-22-4a3c36eb9bf9>", line 1, in <module>
wb = Workbook()
File "C:\Program Files\Anaconda\lib\site-packages\xlwings\main.py", line 141, in __init__
self.xl_app, self.xl_workbook = xlplatform.new_workbook()
File "C:\Program Files\Anaconda\lib\site-packages\xlwings\_xlwindows.py", line 104, in new_workbook
xl_app = _get_latest_app()
File "C:\Program Files\Anaconda\lib\site-packages\xlwings\_xlwindows.py", line 88, in _get_latest_app
return xl_workbook_current.Application
File "C:\Program Files\Anaconda\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Open.Application
And as a follow up, the piece of code from 'dyamic.py' raising the error:
[...]
# If we are still here, and have a retEntry, get the OLE item
if not retEntry is None:
invoke_type = _GetDescInvokeType(retEntry, pythoncom.INVOKE_PROPERTYGET)
debug_attr_print("Getting property Id 0x%x from OLE object" % retEntry.dispid)
try:
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
except pythoncom.com_error, details:
if details.hresult in ERRORS_BAD_CONTEXT:
# May be a method.
self._olerepr_.mapFuncs[attr] = retEntry
return self._make_method_(attr)
raise
debug_attr_print("OLE returned ", ret)
return self._get_good_object_(ret)
# no where else to look.
raise AttributeError("%s.%s" % (self._username_, attr))
As I mentioned before, the last bit it too much for me :P
I guessed some lingering Excel.exe (or similar) process was interfering with the script after I closed some random window due to some random error, but I cant find one in the task manager. Also, this is the kind of thing a reboot should fix, right?! I also upgraded to xlwings .34 (latest version, as of now).
Windows 8.1 64 bit, Python 2.7 (Anaconda distribution, Spyder IDE), Excel 2013.
Any help is very much appreciated, of course!
Thanks a lot, kind regards,
Gordon.
EDIT:
Following advice given in the comments, I can now report that even at times when wb = Workbook() fails, from win32com.client import dynamic followed by dynamic.Dispatch('Excel.Application') returns <COMObject Excel.Application>.
Hope it helps!
Always check either any issues to open the excel sheet, such as password protected/Licensed issues..
If there is any pop up coming while opening excel, you may get the same error.
I am fetching the call-logs, appending them on information note using:
CAknInformationNote* note = new (ELeave) CAknInformationNote;
note->ExecuteLD(callLogs);
I perfectly run on emulator (show all call-logs on note) but nothing shows up when run on the actual device (a Nokia N73). Any ideas?
i think you should use some kind of file logging(you can even use RFile) and see till what point your application executing.i am assuming you dont see a crash/panic on hardware.i doubt if you are able to get the call logs properly first on device.