I am using PyUSB library to read data from my USB mouse in windows. I was able to run the code in a UBUNTU virtual machine, but I can't replicate the same in windows. Can someone tell me what am I doing wrong? Following is the code and the error it throws :
import usb.core
import usb.util
# decimal vendor and product values
dev = usb.core.find(idVendor=1133, idProduct=49278)
if dev is None :
raise ValueError('Device is not found')
print(dev)
# first endpoint
interface = 0
endpoint = dev[0][(0,0)][0]
# if the OS kernel already claimed the device, which is most likely true
if dev.is_kernel_driver_active(interface) is True:
# tell the kernel to detach
dev.detach_kernel_driver(interface)
# claim the device
usb.util.claim_interface(dev, interface)
collected = 0
attempts = 50
while collected < attempts :
try:
data = dev.read(endpoint.bEndpointAddress,endpoint.wMaxPacketSize)
collected += 1
print(data)
except usb.core.USBError as e:
data = None
if e.args == ('Operation timed out',):
continue
# release the device
usb.util.release_interface(dev, interface)
# reattach the device to the OS kernel
dev.attach_kernel_driver(interface)
Traceback (most recent call last):
File "c:\BCD\i360\python\usb_reader.py", line 27, in <module>
if dev.is_kernel_driver_active(interface) is True:
File "C:\Python\Python38\lib\site-packages\usb\core.py", line 1107, in is_kernel_driver_active
self._ctx.managed_open()
File "C:\Python\Python38\lib\site-packages\usb\core.py", line 113, in wrapper
return f(self, *args, **kwargs)
File "C:\Python\Python38\lib\site-packages\usb\core.py", line 131, in managed_open
self.handle = self.backend.open_device(self.dev)
File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 804, in open_device
return _DeviceHandle(dev)
File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 652, in __init__
_check(_lib.libusb_open(self.devid, byref(self.handle)))
File "C:\Python\Python38\lib\site-packages\usb\backend\libusb1.py", line 600, in _check
raise NotImplementedError(_strerror(ret))
NotImplementedError: Operation not supported or unimplemented on this platform
The error says exactly what's wrong: You're using a function that makes no sense on your operating system (Windows).
So, don't do that? Either, if you know this is something only running on Windows, remove the check, or better, try:-handle the exception.
dev.is_kernel_driver_active(interface) is not supported in Windows
Related
I was trying Streamlit 1.13 on Windows 10, where I encountered the following error:
Z:\>streamlit run st1.py
2022-10-04 02:25:28.218 INFO numexpr.utils: NumExpr defaulting to 4 threads.
Welcome to Streamlit!
If you're one of our development partners or you're interested in getting
personal technical support or Streamlit updates, please enter your email
address below. Otherwise, you may leave the field blank.
http://localhost:8501
Traceback (most recent call last):
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\tornado\http1connection.py", line 276, in _read_message
delegate.finish()
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\tornado\routing.py", line 268, in finish
self.delegate.finish()
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\tornado\web.py", line 2322, in finish
self.execute()
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\tornado\web.py", line 2344, in execute
self.handler = self.handler_class(
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\tornado\web.py", line 239, in __init__
self.initialize(**kwargs) # type: ignore
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\streamlit\web\server\routes.py", line 49, in initialize
self._pages = get_pages()
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\streamlit\web\server\server.py", line 397, in <lambda>
for page_info in source_util.get_pages(
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\streamlit\source_util.py", line 155, in get_pages
"script_path": str(main_script_path.resolve()),
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\pathlib.py", line 1215, in resolve
s = self._flavour.resolve(self, strict=strict)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\pathlib.py", line 215, in resolve
s = self._ext_to_normal(_getfinalpathname(s))
OSError: [WinError 1] Incorrect function: 'st1.py'
The installation of streamlit was complete: initially there was a conflict which I fixed, I also installed it in Anaconda and the error was the same.
I checked the exact streamlit file which rised the exception and changed the script to print the actual path of the script and it was correct, as well as the file was there.
#File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\streamlit\source_util.py", line 155, in get_pages
def get_pages(main_script_path_str: str) -> Dict[str, Dict[str, str]]:
global _cached_pages
print("main_script_path_str=",main_script_path_str) #DEBUG
# Avoid taking the lock if the pages cache hasn't been invalidated.
pages = _cached_pages
if pages is not None:
return pages
The problem was with the location of the script on a RAM disk. Moving it to the a regular disk resolved it.
Another question with this Win error reminded me that the drivers of Windows RAM drives, at least the ones I've used such as Imdisk or OSFMount, seem to have missing support of some of the OS file functions.
OSError: [WinError 1] Incorrect function
E.g. "Rust" also had errors when trying to build source located in any of these RAM drives on Windows.
I have been trying to read a thermocouple temperature on my raspberrypi however cant get the raspi to communicate with the adafruit MAX 31856. I have downloaded necessary libraries and checked that all connections are secure and correct however keep running into this error when I try to execute this code.
Any help is greatly appreciated!!
CODE
import board
import digitalio
import adafruit_max31856
spi = board.SPI()
cs = digitalio.DigitalInOut(board.D5)
cs.direction = digitalio.Direction.OTUPUT
thermocouple = adafruit_max31856.MAX31856(spi,cs)
print(thermocouple.temperature)
ERROR:
Traceback (most recent call last):
File "/home/pi/test4.py", line 6, in <module>
spi = board.SPI()
File "/usr/local/lib/python3.7/dist-packages/board.py", line 299, in SPI
return busio.SPI(SCLK, MOSI, MISO)
File "/usr/local/lib/python3.7/dist-packages/busio.py", line 289, in __init__
self._spi = _SPI(portId)
File "/usr/local/lib/python3.7/dist-packages/adafruit_blinka/microcontroller/generic_linux/spi.py", line 25, in __init__
self._spi = spi.SPI(device=(portid, 0))
File "/usr/local/lib/python3.7/dist-packages/Adafruit_PureIO/spi.py", line 167, in __init__
raise IOError("{} does not exist".format(device))
OSError: /dev/spidev0.0 does not exist
Code
Errors
Most probably there is a device driver loaded for spi0-0 and that removes /dev/spidev0.0 device.
check your /boot/config.txt for overlays loading MAX 31856 driver module.
if you want to use adafruit_max31856 lib you shouldn't be loading this driver. hope that helps
I'm trying to connect a POS receipt printer to python and have been using python-escpos to do so. I'm running windows 10.
My code in my file 'print.py' is:
from escpos.printer import Usb
p = Usb(0x0456,0x0808)
p.text('Hello World\n')
but when i run it i get the following error log:
Traceback (most recent call last):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 223, in get_interface_and_endpoint
return self._ep_info[endpoint_address]
KeyError: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "print.py", line 5, in <module>
p.text('Hello World\n')
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\escpos.py", line 437, in text
self._raw(txt.encode())
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\escpos\printer.py", line 73, in _raw
self.device.write(self.out_ep, msg, self.timeout)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 940, in write
intf, ep = self._ctx.setup_request(self, endpoint)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 215, in setup_request
intf, ep = self.get_interface_and_endpoint(device, endpoint_address)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 225, in get_interface_and_endpoint
for intf in self.get_active_configuration(device):
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 102, in wrapper
return f(self, *args, **kwargs)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\core.py", line 239, in get_active_configuration
bConfigurationValue=self.backend.get_configuration(self.handle)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 510, in get_configuration
100)
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 593, in ctrl_transfer
timeout
File "C:\Users\Harry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\usb\backend\libusb0.py", line 431, in _check
raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control message failed, win error: A device which does not exist was specified.\r\n\n'
Does anyone know what i need to do to make this work.
I have installed libusb into my System32 and SysWOW64 folders, aswell as installing a libusb-32 driver for my printer with zadig.
The printer i'm using is a 'Hoin 58mm POS Printer'.
I would be grateful if someone could explain to me why i'm having this error and how to solve it!
Firstly, you can check this link for the complete thread.
As suggested by KM4YRI,
I ran into the same No backend available exception when trying to follow the tutorial on a Windows 7 machine. The following worked for me, per one of the StackOverflow replies:
1. Download the latest Windows binary: https://sourceforge.net/projects/libusb/files/libusb-1.0/libusb-1.0.21/libusb-1.0.21.7z/download
2. Unzip using 7zip into a temp dir
3. If on 64-bit Windows, copy `MS64\dll\libusb-1.0.dll` into `C:\windows\system32`. If on 32-bit windows, copy `MS32\dll\libusb-1.0.dll` into `C:\windows\SysWOW64`.
I've verified the above answer on Windows-10 64-bit version.
I had a tight experience with that error using at least 3 different USB Storage Devices. After hours of trials I ended up to a feeling that USB transmission errors are the cause of this error.
The USB bus will return it in a random pattern for a low quality connection as if a device remove has presumably happened.
In my scenario I was bulk writing sectors to a \\.\PhysicalDriveN device and I noticed that after a short period the connection reestablished and the file handle was still valid and going.
To overcome the error I've ended up with the following steps:
Seek To File Position;
Write Sector;
For any 433 error:
250 ms delay;
Seek To file Position, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and trying for at least 1000 ms before giving up;
Read Sector, ignoring ERROR_NO_SUCH_DEVICE and ERROR_NOT_READY errors and retrying for up to 1000 ms before giving up;
Specially for my scenario: I've compared input buffer and read buffer and stop if matching;
Repeat the whole procedure up to 5 times.
So the idea here is the following: The device driver returns ERROR_NO_SUCH_DEVICE assuming a device remove scenario, but still in a pending state. As the problem is simply quality of physical connection, the link continues and the bus driver starts a renegotiation, in which case a ERROR_NOT_READY is temporarily returned. When the link is stable and negotiated, communication continues without the need to reopen the device handle.
I would recommend adding a sleep statement of a second or two in between the instantiation of the USB printer, and the attempt to print to it. e.g:
from escpos.printer import Usb
from time import sleep
p = Usb(0x0456,0x0808)
sleep(1)
p.text('Hello World\n')
I am using the Flask-WeRobot plugin and I am seeing an error being thrown here:
class FileStorage(SessionStorage):
"""
FileStorage 会把你的 Session 数据以 dbm 形式储存在文件中。
:param filename: 文件名, 默认为 ``werobot_session``
"""
def __init__(self, filename='werobot_session'):
print filename
try:
self.db = dbm.open(filename, "c")
except Exception, e:
print e
raise e
This is what is being outputted:
Traceback (most recent call last):
File "application.py", line 18, in <module>
another_robot = WeRoBot(token='abcdefg', enable_session=True)
File "/Users/vng/Dropbox/Code/Paw/venv/lib/python2.7/site-packages/flask_werobot.py", line 42, in __init__
super(WeRoBot, self).__init__(*args, **kwargs)
File "/Users/vng/Dropbox/Code/Paw/venv/lib/python2.7/site-packages/werobot/robot.py", line 47, in __init__
filename=os.path.abspath("werobot_session")
File "/Users/vng/Dropbox/Code/Paw/venv/lib/python2.7/site-packages/werobot/session/filestorage.py", line 20, in __init__
self.db = dbm.open(filename, "c")
File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/anydbm.py", line 85, in open
return mod.open(file, flag, mode)
gdbm.error: (35, 'Resource temporarily unavailable')
At first I thought it would have something to do with permissions, but changing the file, werobot_session didn't work.
I am on OSX running python 2.7. This code works on my ubuntu production server.
Any ideas what's causing this?
We find this bug too and we are working on it now.
It seems that it's a bug of gdbm. And everything works fine on linux.
You can check this issue for further information.
https://github.com/whtsky/WeRoBot/issues/102
I am trying to get the usb.find command to work properly in a python script I'm writing on Angstrom for the Beagleboard.
Here is my code:
#!/usr/bin/env python
import usb.core
import usb.util
import usb.backend.libusb01 as libusb
PYUSB_DEBUG_LEVEL = 'debug'
# find our device
# Bus 002 Device 006: ID 1208:0815
# idVendor 0x1208
# idProduct 0x0815
# dev = usb.core.find(idVendor=0xfffe, idProduct=0x0001)
# iManufacturer 1 TOROBOT.com
dev = usb.core.find(idVendor=0x1208, idProduct=0x0815,
backend=libusb.get_backend() )
I don't know what's missing, but here is what I do know.
When I don't specify the backend, no backend is found. When I do specify the backend "usb.backend.libusb01" I get the following error:
root#beagleboard:~/servo# ./pyServo.py
Traceback (most recent call last):
File "./pyServo.py", line 17, in <module>
dev = usb.core.find(idVendor=0x1208, idProduct=0x0815, backend=libusb.get_backend() )
File "/usr/lib/python2.6/site-packages/usb/core.py", line 854, in find
return _interop._next(device_iter(k, v))
File "/usr/lib/python2.6/site-packages/usb/_interop.py", line 60, in _next
return next(iter)
File "/usr/lib/python2.6/site-packages/usb/core.py", line 821, in device_iter
for dev in backend.enumerate_devices():
File "/usr/lib/python2.6/site-packages/usb/backend/libusb01.py", line 390, in enumerate_devices
_check(_lib.usb_find_busses())
File "/usr/lib/python2.6/ctypes/__init__.py", line 366, in __getattr__
func = self.__getitem__(name)
File "/usr/lib/python2.6/ctypes/__init__.py", line 371, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: python: undefined symbol: usb_find_busses
What am I missing so that this will work properly?
Thank you.
Python, pyusb, libusb.
I think that's it.
Well libc, ld-linux.so too of course, but those are in your system by default.
Do nm -D /path-to/libusb.so and see if usb_find_busses symbol is really there. There's always a chance that your libusb is outdated or somehow specially compiled.
Check if you get any log, for example missing libusb.so should produce something like 'Error loading libusb 0.1 backend'