Code Monkey home page Code Monkey logo

pyusb's Introduction

PyUSB – Easy USB access for Python

Introduction

PyUSB provides for easy access to the host machine's Universal Serial Bus (USB) system for Python 3.

Until 0.4 version, PyUSB used to be a thin wrapper over libusb. Starting with the 1.0 version, things changed considerably: now PyUSB is an API rich, backend neutral Python USB module easy to use.

Documentation

The best way to get started with PyUSB is to read the following documents:

For more detailed information, PyUSB's API documentation, as with most Python modules, is based on Python doc strings and can be manipulated by tools such as pydoc1:

$ python -m pydoc usb

The libusb 1.0 documentation is also a recommended read, especially when using that backend (more on this below).

Requirements and platform support

PyUSB is primarily developed and tested on Linux and Windows, but it should also work fine on any platform running Python >= 3.8, ctypes and at least one of the built-in backends.

PyUSB supports libusb 1.0, libusb 0.1 and OpenUSB. Of those, libusb 1.0 is currently recommended for most use cases.

On Linux and BSD, these will generally be available on the distribution's official repositories.

On macOS, libusb 1.0 can easily be installed through Homebrew:

$ brew install libusb

On Windows, pyocd/libusb-package is a convenient23 way to provide the necessary libusb 1.0 DLL, as well as a suitable PyUSB backend and a easy to use wrapper over PyUSB's find() API:

# with pure PyUSB
for dev in usb.core.find(find_all=True):
    print(dev)

# with pyocd/libusb-package
for dev in libusb_package.find(find_all=True):
    print(dev)

Alternatively, the libusb 1.0 DLL can be manually copied from an official release archive into the C:\Windows\System32 system folder, or packaged together with the complete application.

Installing

PyUSB is generally installed through pip4:

# the latest official release
python -m pip install pyusb

# install a specific version (e.g. 1.2.1)
python -m pip install pyusb==1.2.1

# the latest snapshop from the official git repository
python -m pip install pyusb git+https://github.com/pyusb/pyusb#egg=pyusb

Most Linux distributions also package PyUSB in their official repositories.

Getting help

If you have a question about PyUSB:

To report a bug or propose a new feature, use our issue tracker. But please search the database before opening a new issue.

Footnotes


  1. On systems that still default to Python 2, replace python with python3.

  2. Unlike PyUSB, pyocd/libusb-package uses the more restrictive Apache 2.0 license.

  3. While pyocd/libusb-package supports platforms other than Windows, there are advantages to sticking to a system-provided libusb, if it is available and the platform has a robust package manager (e.g. Linux, BSD, macOS with Homebrew).

  4. On systems that still default to Python 2, replace python with python3.

pyusb's People

Contributors

alanjas avatar andreysv avatar andygoulden avatar ap-- avatar braiden avatar clach04 avatar cobyj33 avatar davidhalter avatar dywisor avatar endolith avatar jaseg avatar jcflack avatar jnrowe avatar jonasmalacofilho avatar mattheard avatar nicoelayda avatar norberg avatar pabigot avatar pazeshun avatar pprabhu avatar querela avatar rnixx avatar simplicityguy avatar stefanod avatar swinman avatar thijstriemstra avatar timgates42 avatar tormodvolden avatar walac avatar yawara avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyusb's Issues

[Errno 16] Resource busy

Hi guys,
I'm not sure if i made a mistake...
I'm always getting this error and no solution worked for me :(
My software: Python 2.7.8, libusb 1.0.19-1 and the current PyUSB version from this rep...
I'm working on Arch Linux Arm (Raspberry Pi model B)
Her's my udev rule:

UBSYSTEMS=="usb", ATTRS{idVendor}=="04f2", ATTRS{idProduct}=="0402", GROUP=users", MODE="0660"

From itdaniher/WeDoMore#4

And a testcode:

#!/usr/bin/python2

import usb.core
import usb.util
import sys

def getData():
    VENDOR_ID = 0x04f2
    PRODUCT_ID = 0x0402
    DATA_SIZE = 1
    device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
    if device is None:
        sys.exit("Could not find Keyboard")

    if device.is_kernel_driver_active(0):
        try:
                device.detach_kernel_driver(0)
                print "kernel driver detached"
        except usb.core.USBError as e:
                sys.exit("Could not detach kernel driver: %s" % str(e))
    else:
        print "no kernel driver attached"
    try:
        usb.util.claim_interface(device, 0)
        print "claimed device"
    except:
        sys.exit("Could not claim the device: %s" % str(e))
    try:
        device.set_configuration()
        device.reset()
    except usb.core.USBError as e:
        sys.exit("Could not set configuration: %s" % str(e))

When I execute my script:

$sudo python2 ./test.py
no kernel driver attached
claimed device
Could not set configuration: [Errno 16] Resource busy

Can you tell me whats wrong?
Thanks :)

Speed improvment

Change the array initialization for read command for libusb0 and libusb1 backed.
Current initialization can take long time because a tuple is created, changing this to string improves read speed for fast devices.

Details:
instead : data = _interop.as_array((0,) * size)
use : data = _interop.as_array( '\x00' * size )

In libusb1.py and libusb0.py.

tutorial example failing with libusb-win32

The tutorial code works perfectly under Linux, but having installed pyusb (1.0.0b1) and
libusb-win32-bin-1.2.6.0 (whose test app seems to work), I find I get a 'request is not supported' exception from line 79 of tutorial.rst (usb.control.getinterface).
I enclose an image showing my exception traceback.
pyusb
My testing is running on XP running under VirtualBox

add relative imports

By now, the package imports its modules by from usb import .... Thats not very useful if you rename the package name by any reason. Better would be from . import ...

See the Python docs about intra package references for more details.

libusb_strerror not implemented in libusb-1.0.9

Using pyusb 1.0.0b2, and libusb-1.0.9 on Linux

File "/usr/lib/python2.7/site-packages/usb/core.py", line 364, in read
  return self.device.read(self, size_or_buffer, timeout)
File "/usr/lib/python2.7/site-packages/usb/core.py", line 918, in read
  self.__get_timeout(timeout))
File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 787, in intr_read
  timeout)
File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 872, in __read
  _check(retval)
File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 552, in _check
  raise USBError(_strerror(ret), ret, _libusb_errno[ret])
File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 541, in _strerror
  return _lib.libusb_strerror(errcode).decode('utf8')
File "/usr/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__
  func = self.__getitem__(name)
File "/usr/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__
  func = self._FuncPtr((name_or_ordinal, self))
AttributeError: /usr/lib/libusb-1.0.so.0: undefined symbol: libusb_strerror

Can't use libusb-1.0.19 because libudev is not readily available on my distribution. I get the following when trying to build it: configure: error: "udev support requested but libudev not installed". Tried to go down the path of building libudev, but it had its own dependencies, so too many dragons down that path...

[UPDATE January 8]

For those who arrive here via google, and the configure error message above. To build libusb without libudev (seemingly obvious with hindsight):

./configure --disable-udev
make

[/UPDATE January 8]

I have increased my timeout, and I am not hitting this now, but it probably isn't the best behavior to have the error reporting code take an exception.

As a hacky work around I changed _strerror from:

def _strerror(errcode):
    return _lib.libusb_strerror(errcode).decode('utf8')

to:

def _strerror(errcode):
    errcode_strings = [
        "Success",
        "Input/Output Error",
        "Invalid parameter",
        "Access denied (insufficient permissions)",
        "No such device (it may have been disconnected)",
        "Entity not found",
        "Resource busy",
        "Operation timed out",
        "Overflow",
        "Pipe error",
        "System call interrupted (perhaps due to signal)",
        "Insufficient memory",
        "Operation not supported or unimplemented on this platform",
        "Other error",
        ]

    try:
        return _lib.libusb_strerror(errcode).decode('utf8')

    except AttributeError:
        errcode_index = -errcode;
        if errcode_index < 0 or errcode_index >= len(errcode_strings):
            errcode_index = -1
        return errcode_strings[errcode_index]

usb.util.get_string() returns garbage...

usb.util.get_string(dev, 256, 2) (and 0, 1, 2 as the last argument as well), which is supposed to return the description of the device, returns a single character (Љ) instead of the actual description from the device.

This script reproduces the problem here with a USB to serial adapter:

import usb
for dev in usb.core.find(find_all=True, idVendor = 0x067b, idProduct = 0x2303):
print("desc = {}".format(usb.util.get_string(dev, 256, 2)))

This works as expected with pyusb version 1.0.0b1, but broke in b2.

undefined symbol: libusb_strerror

I'm trying to use pyusb with Linux (openSUSE 13.1) with libusb1. I've cloned the repository and executed:
sudo python setup.py install
I checked out the latest pyusb commit: 5640944 (Jul 20 2014).

I have written this simple Python script (t.py):
import usb.core
dev = usb.core.find(idVendor=0x04d8, idProduct=0x003f)
and run it via:
export PYUSB_DEBUG=debug
python -i t.py

What I get is (among many other messages):

2014-08-01 14:01:48,556 ERROR:usb.backend.libusb1:Error loading libusb 1.0 backend
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 880, in get_backend
_setup_prototypes(_lib)
File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 453, in _setup_prototypes
lib.libusb_strerror.argtypes = [c_uint]
File "/usr/lib64/python2.7/ctypes/init.py", line 378, in getattr
func = self.getitem(name)
File "/usr/lib64/python2.7/ctypes/init.py", line 383, in getitem
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: /usr/local/lib/libusb-1.0.so.0: undefined symbol: libusb_strerror

The function libusb_strerror seems not to exist in libusb1 since Feb 27 2011 (commit 4be84ab49 in their git repo). Am I wrong?

Signature change in util.get_string breaks client code

Commit dac7893 "Removed unnecessary length argument to util.get_string" modified the function signature such that foreign code will now throw an exception. There is no reason provided why it is necessary to remove the length parameter other than that internally it may not be needed. I thought the function util.get_string would be part of the API and thus safe to use. Unless there was any good reason to change the signature, could the commit just be reverted?

Backends are reimported each time find() is called with backend parameter None

If find() is called multiple times with backend=None, the backend is reimported and consequently the backend library is reinitalized. For libusb, this results in libusb_init() and libusb_exit() getting called on each call to find() and renders the backend module's mechanism for caching the library (i.e. the global "_lib" variable) useless.

On windows, this was somehow leading to the intermittent "Access Denied" errors as detailed here: http://sourceforge.net/p/pyusb/mailman/message/33076849/

An easy workaround is for the caller to get the specific backend once, cache it themselves, and pass it explicitly.

usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control message failed

I used following lamp and installed libusb-win32 (v1.2.6.0) using zadig.
http://dx.com/p/usb-universal-e-mail-webmail-im-notifier-gmail-outlook-outlook-express-pop3-27062

And I used following python script to sending msg to usb.
https://code.google.com/p/usbmailnotifier/

But, I got these faults as below:
D:\Python33\pyusb-master>python setcolor.py 5
<usb.legacy.Bus object at 0x01BD66D0>
[<usb.legacy.Device object at 0x01BDED30>]
Traceback (most recent call last):
File "setcolor.py", line 62, in
main(sys.argv)
File "setcolor.py", line 59, in main
m.setColor(int(argv[1]))
File "setcolor.py", line 18, in setColor
self.dev.handle.interruptWrite(0x02, self.makeData(color), 1000)
File "D:\Python33\pyusb-master\usb\legacy.py", line 171, in interruptWrite
return self.dev.write(endpoint, buffer, self.__claimed_interface, timeout)
File "D:\Python33\pyusb-master\usb\core.py", line 623, in write
intf = self._ctx.get_interface(self, interface)
File "D:\Python33\pyusb-master\usb\core.py", line 150, in get_interface
cfg = self.get_active_configuration(device)
File "D:\Python33\pyusb-master\usb\core.py", line 165, in get_active_configura
tion
bConfigurationValue=self.backend.get_configuration(self.handle)
File "D:\Python33\pyusb-master\usb\backend\libusb0.py", line 464, in get_confi
guration
100
File "D:\Python33\pyusb-master\usb\backend\libusb0.py", line 544, in ctrl_tran
sfer
timeout
File "D:\Python33\pyusb-master\usb\backend\libusb0.py", line 392, in _check
raise USBError(errmsg, ret)
usb.core.USBError: [Errno None] b'libusb0-dll:err [control_msg] sending control
message failed, win error: \xcf\xb5\xcd\xb3\xd5\xd2\xb2\xbb\xb5\xbd\xd6\xb8\xb6
xa8\xb5\xc4\xce\xc4\xbc\xfe\xa1\xa3\r\n\n'

Problem in combination with OpenCV

I just noticed a very interesting bug in combination with the cv2 module from OpenCV:

import usb
import cv2

print "All ok"
print usb.core.find()
print "Still ok, but we never finish"

The find() function works all right, but after this, python never terminates.

Suggestion: move all imports to top of file

This is to avoid getting caught in an import lock if we are using threads and running pyusb from an import (which we probably shouldn't, but I did). I specifically found one problem in backend/libusb1.py line 401.

What I did:

I imported a test which run a test which was threaded. And suddenly the thread hang on import because the lock was occupied in another thread, a couple of hours later I learned of the import lock. This would probably have worked if import where done when importing pyusb, but since MainThread was still doing imports (aka running the test) the thread that tried to read data, which timed out and caused pyusb to try to import USBException, just hang. Took a while before I figured out what was going on there.

How can i remove pyusb

this is giving me some issues with another sw
ho can i remove it?

sudo apt-get remove pyusb doesn't work

thanks

Exception when script using pyusb finishes

When my script executes sys.exit(), I get an exception:

Exception AttributeError: "'NoneType' object has no attribute 'copy'" in <bound method Device.__del__ of <usb.core.Device object at 0x029F09D0>> ignored

I traced this to the release_all_interfaces() method in core.py. It tries to copy self._claimed_intf, but in my case this happens to be an empty set and the exception occurs. I stopped this error by putting in a test for len(self._claimed_intf) == 0.

Am I making an error in how I'm using pyusb? Or is this an error in core.py?

I'm using pyusb-1.0.0b1 with python 2.7.6 and libusb-1.0 on Windows 7.

Expose extra descriptors through core objects

libusb exposes extra descriptors that can not be parsed as a byte array in the
Configuration, Interface and Endpoint objects. Expose this byte array as a
python list through pyusb.

This would be helpful in a project in ChromeOS where we want to be able to parse class specific functional descriptors as specified by the CDC sub-classes.

Segmentation fault in Weewx using latest pyusb(1.0.0a4)

With pyusb 1.0.0a3 I didn't have this error so it must be something that was added in a4 version that is causing this:

Aug  1 01:10:44 hvarbrain weewx[2199]: wxengine: Initializing weewx version 2.3.3
Aug  1 01:10:44 hvarbrain weewx[2199]: wxengine: Using Python 2.6.6 (r266:84292, Jul 10 2013, 22:43:23) #012[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)]
Aug  1 01:10:44 hvarbrain weewx[2199]: wxengine: Using configuration file /home/meteo/weewx-2.3.3/weewx.conf
Aug  1 01:10:44 hvarbrain weewx[2199]: wxengine: Loading station type WMR100 (weewx.drivers.wmr100)
Aug  1 01:10:44 hvarbrain kernel: python[2199]: segfault at 24 ip 008932cd sp bf9bd764 error 4 in libpthread-2.12.so[88b000+17000]
Aug  1 01:10:44 hvarbrain abrtd: Directory 'ccpp-2013-08-01-01:10:44-2199' creation detected
Aug  1 01:10:44 hvarbrain abrt[2202]: Saved core dump of pid 2199 (/usr/bin/python) to /var/spool/abrt/ccpp-2013-08-01-01:10:44-2199 (6168576 bytes)
Aug  1 01:10:45 hvarbrain abrtd: Interpreter crashed, but no packaged script detected: 'python ./bin//weewxd weewx.conf'
Aug  1 01:10:45 hvarbrain abrtd: 'post-create' on '/var/spool/abrt/ccpp-2013-08-01-01:10:44-2199' exited with 1
Aug  1 01:10:45 hvarbrain abrtd: Corrupted or bad directory '/var/spool/abrt/ccpp-2013-08-01-01:10:44-2199', deleting

usb.core.USBError: [Errno 2] Entity not found when using libusb 1.0

C:\Users\MartianZ\Desktop\User_Application\App>python x.py
Traceback (most recent call last):
File "x.py", line 58, in btn_dfu_upload_clicked
dev, config, intf = self.get_dfu_device()
File "x.py", line 37, in get_dfu_device
for bus in busses:
File "C:\Python27\lib\site-packages\usb\legacy.py", line 346, in
return (Bus(g) for k, g in _interop.groupby(
File "C:\Python27\lib\site-packages\usb\legacy.py", line 340, in init
self.devices = [Device(d) for d in devices]
File "C:\Python27\lib\site-packages\usb\legacy.py", line 325, in init
self.configurations = [Configuration(c) for c in dev]
File "C:\Python27\lib\site-packages\usb\core.py", line 1022, in iter
yield Configuration(self, i)
File "C:\Python27\lib\site-packages\usb\core.py", line 548, in init
configuration
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 701, in get

configuration_descriptor
config, byref(cfg)))
File "C:\Python27\lib\site-packages\usb\backend\libusb1.py", line 560, in _che
ck
raise USBError(_str_error[ret], ret, _libusb_errno[ret])
usb.core.USBError: [Errno 2] Entity not found

My code is as follows:

    busses = usb.busses()
    for bus in busses:
        devices = bus.devices
        print devices

I was trying to make an old DFU python program work on Windows, my os is Windows 7 64-Bit python 2.7 and pyusb from GitHub branch.
the backend is libusb-1.0.19, I tried the same python code on Mac OS X and it worked fine.

and I also tried the following code and it worked find, so i think it may be a legacy problem.

    b = usb.backend.libusb1.get_backend(find_library=lambda C: "\libusb-1.0.dll")
    dev = usb.core.find(backend=b, idVendor=0x0001, idProduct=0xdf11)
    dev.set_configuration()

Thank you.

AttributeError: '_ResourceManager' object has no attribute 'get_interface'

The lines 732-755 use the method get_interface which has been removed recently.

Yielding this error:

AttributeError: '_ResourceManager' object has no attribute 'get_interface'

Locally, I changed those lines to

def is_kernel_driver_active(self, interface):
    r"""Determine if there is kernel driver associated with the interface.

    If a kernel driver is active, and the object will be unable to perform I/O.
    """
    self._ctx.managed_open()
    return self._ctx.backend.is_kernel_driver_active(self._ctx.handle,
            interface)

def detach_kernel_driver(self, interface):
    r"""Detach a kernel driver.

    If successful, you will then be able to perform I/O.
    """
    self._ctx.managed_open()
    self._ctx.backend.detach_kernel_driver(self._ctx.handle,
        interface)

def attach_kernel_driver(self, interface):
    r"""Re-attach an interface's kernel driver, which was previously
    detached using detach_kernel_driver()."""
    self._ctx.managed_open()
    self._ctx.backend.attach_kernel_driver(self._ctx.handle,
        interface)

but wasn't sure what you wanted the api to actually be. In this version I just pass in the bInterfaceNumber and it works, but wasn't sure if you wanted the actual interface or both.

Problem in combination with OpenCV

I just noticed a very interesting bug in combination with the cv2 module from OpenCV:

import usb
import cv2

print "All ok"
usb.core.find()
print "Still ok, but we never finish"

python: can't open file 'setup.py': [Errno 2] No such file or directory

Minimal experience using this stuff - trying to do this on a raspberrypi B+, I'd probably have better luck on windows with navigating files but I have no idea how this things file structure works.

I typed in: sudo apt-get install python libusb-1.0...
it prompted and I said yes.
when issuing the command : sudo python setup.py install
I get the response: python: can't open file 'setup.py': [Errno 2] No such file or directory

The 'answer' is: Run it as root from within the same directory as this README file..

  1. I thought that using SUDO was running it as 'Root' or "admin"..?
  2. (what I think the real problem is) I have NO IDEA where this thing got downloaded into directory.. because i didn't download a zipfile or anything. I don't know how to locate it through the terminal or using the GUI (startx prompted interface). I don't see a way of searching it, and since I don't really know how the file structure works..

Using the LXTerminal for doing this (installing/downloading) has me all kinds of confused, mostly due to lack of experience. Sorry for my ignorance, but the simple "run as root from the same directory.." has had me stumped for an hour or more now.

Thanks for the help.

read data in iso mode seems calling intr_read

hi, i find iso_read seems not works correctly.

core.py:

fn_map = {

util.ENDPOINT_TYPE_BULK:backend.bulk_read,

util.ENDPOINT_TYPE_INTR:backend.intr_read,

util.ENDPOINT_TYPE_ISO:backend.iso_read

}

...

fn = fn_map[util.endpoint_type(ep.bmAttributes)]

when ep.bmAttributes is 1, it should means iso_read, but this set seems not ordered correctly. According to debug log, it's using intr_read.....

Am i right?

Tutorial wrong?

Hi!

I really appreciate your tutorial and while reading and following it, I came across a mistake - or so I think.

In the "Talk to me Honey" section, in that control message example. There is said to use ret = dev.ctrl_transfer(0x40, CTRL_LOOPBACK_READ, 0, 0, len(msg))
to receive data from the device. I think this has to be:
ret = dev.ctrl_transfer(0b11000000, CTRL_LOOPBACK_READ, 0, 0, len(msg))

Thanks and best regards

USBError(19, u'No such device ...) in libusb1.release_interface()

Seeing the following on the console on removing the usb device:

Exception usb.core.USBError: USBError(19, u'No such device (it may have been disconnected)') in
<bound method Device.__del__ of <DEVICE ID 0bd3:0333 on Bus 002 Address 066>> ignored

Using python 2.7.4, libusb-1.0.19, the current tip of pyusb (previously also occurred on beta 2) on Linux.

According to https://docs.python.org/2/reference/datamodel.html#object.__del__

Warning Due to the precarious circumstances under which del() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when del() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the del() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, del() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the del() method is called.

In an effort to try and find what I was doing wrong I ended up changing core.Device._finalize_object() from:

def _finalize_object(self):
    self._ctx.dispose(self)
    return 

to:

def _finalize_object(self):
    try:
        self._ctx.dispose(self)
    except USBError, e:
        # [Errno 19] No such device (it may have been disconnected)
        if e.errno != 19:
            raise
        else:
            # for [Errno 19] dump full stack
            import traceback, sys

            trace = '----------------------\n'
            trace += 'Traceback (most recent call last):\n'
            for line in traceback.format_stack()[:-1]:
                trace += line
            trace += '.\n'
            for line in traceback.format_tb(sys.exc_info()[2]):
                trace += line
            trace += "%s: %s\n" % (e.__class__.__name__, e)
            trace += '----------------------\n'
            sys.stderr.write(trace)

This yielded the following:

...
    del usb_devs[usbid]
  File "/usr/lib/python2.7/site-packages/usb/_objfinalizer.py", line 84, in __del__
    self.finalize()
  File "/usr/lib/python2.7/site-packages/usb/_objfinalizer.py", line 155, in finalize
    self._do_finalize_object()
  File "/usr/lib/python2.7/site-packages/usb/_objfinalizer.py", line 71, in _do_finalize_object
    self._finalize_object()
.
  File "/usr/lib/python2.7/site-packages/usb/core.py", line 1039, in _finalize_object
    self._ctx.dispose(self)
  File "/usr/lib/python2.7/site-packages/usb/core.py", line 226, in dispose
    self.release_all_interfaces(device)
  File "/usr/lib/python2.7/site-packages/usb/core.py", line 223, in release_all_interfaces
    self.managed_release_interface(device, i)
  File "/usr/lib/python2.7/site-packages/usb/core.py", line 160, in managed_release_interface
    self.backend.release_interface(self.handle, i)
  File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 799, in release_interface
    _check(self.lib.libusb_release_interface(dev_handle.handle, intf))
  File "/usr/lib/python2.7/site-packages/usb/backend/libusb1.py", line 588, in _check
    raise USBError(_strerror(ret), ret, _libusb_errno[ret])
USBError: [Errno 19] No such device (it may have been disconnected)

The exception is occurring in libusb1.release_interface(), so I assume is a behavior of the libusb library. I am unsure how my code could cause this. The exception happens every time when the device is in a certain configuration, but does not happen when the device is in another configuration.

My knowledge of the usb bus is minimal so maybe this is expected behavior, and the error code is legitimate. However, the exception is being 'caught' by python because it is in the del() method. The resulting problem this presents in my application is the 'errant' message to stderr listed at the top of this comment.

Error on array initialization in usb/util.py, line 150 with Python 3.4

Hello,
when reading from an usb device I get this error using latest pyusb from git and Python 3.4.0 on Ubuntu 14.04 (the same code works fine with Python 2.7.6):

Traceback (most recent call last):
  File "yaUsbir.py", line 38, in <module>
    data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
  File "/usr/local/lib/python3.4/dist-packages/usb/core.py", line 704, in read
    buff = util.create_buffer(size_or_buffer)
  File "/usr/local/lib/python3.4/dist-packages/usb/util.py", line 150, in create_buffer
    return array.array('B', '\x00' * length)
TypeError: cannot use a str to initialize an array with typecode 'B'

Replacing the string with a bytestring works for me with both Python 2.7 and Python 3.4:

diff --git a/usb/util.py b/usb/util.py
index 7310ede..a4e1761 100644
--- a/usb/util.py
+++ b/usb/util.py
@@ -147,7 +147,7 @@ def create_buffer(length):
     call. This function creates a compatible sequence buffer
     of the given length.
     """
-    return array.array('B', '\x00' * length)
+    return array.array('B', b'\x00' * length)

 def find_descriptor(desc, find_all=False, custom_match=None, **args):
     r"""Find an inner descriptor.

Cannot find any devices

I tried to use

usb.core.find(find_all=True)

but I cannot find any devices. I do have several usb devices plugged in. I was using python 2.7 and pyusb 1.0.0.b2 with win7. Thanks.

readme.md could mention that pip is supported

I used

pushd c:\Python27\Scripts && pip install pyusb==1.0.0b2 && popd

to install - I saw the issue where installing with 'pip install pyusb' with no version will not work until the version is out of beta, so please consider pluggin this approach as the installation method

No backend available

Hi,
I am getting the error "No Backend Available"

When I set PYUSB_DEBUG_LEVEL=debug
I get the following error.

Traceback (most recent call last):

Fi_lib = _load_library()/site-packages/usb/backend/libusb10.py", line 648, in$

Firaise OSError('USB library could not be found')d/libusb10.py", line 205, in$

OSError: USB library could not be found

I have both libusb1.0 and libusb0.4 installed. I have tried setting the LD_LIBRARY_PATH=/usr/lib but this is unsuccessful.

This is returned when I call the find function usb.core.find().

I'm using a linux OS. arm926 architecture

pip install pyusb fails on Ubuntu

On ubuntu 14.4 / Python 3.4, latest version of pip

I expect this fault is an artefact of pyusb's deploy process. Fixing this bug would make pyusb easier for non-admin users to install.


pip install pyusb

Could not find a version that satisfies the requirement pyusb (from blink1->blink1buildlight==0.0.1) (from versions: 1.0.0a2, 1.0.0a2, 1.0.0a3, 1.0.0a3, 1.0.0b1)
Some insecure and unverifiable files were ignored (use --allow-unverified pyusb to allow).
Cleaning up...
No distributions matching the version for pyusb (from blink1->blink1buildlight==0.0.1)
Storing debug log for failure in /home/sal/.pip/pip.log

_lib = None in _Initializer.__del__

Using pyusb, libusbx (1.0.14) and python3 I'm getting the following exception during shutdown:
Exception AttributeError: "'NoneType' object has no attribute 'libusb_exit'" in <bound method _Initializer.del of <usb.backend.libusb1._Initializer object at 0x7f3359ded790>> ignored

This only occurs using python3 and isn't reproducible all the time. It happens about 3 out of 10 iterations. python2 is fine all the time.

Adding a print(_lib) to _Initializer.del show that _lib is None when the exception happens. So it looks like _lib has already been destroyed before _init gets destroyed.

A simple fix is adding a reference to _lib to _Initializer: https://gist.github.com/manuelm/b981029383023baa973e

TypeError: write() got multiple values for keyword argument 'timeout'

Hi,

One of my users is reporting this issue with the version 1.0.0b1, and the following code: https://bitbucket.org/benallard/galileo/src/91910abf7f1c71d0316b41e9061bd3e9407db9df/galileo/dongle.py?at=default#cl-112

Original issue: https://bitbucket.org/benallard/galileo/issue/27/typeerror-write-got-multiple-values-for

I don't really know what's happening, as I can't figure out why would the timeout parameter already be set. Maybe that rings a bell on your side ...

Array typecode 'c' is gone and 'u' is deprecated in Python 3

In usb/_interop.py in the as_array function, the array typecodes c and u are used. I just ran into a problem in Python 3.3 because c is gone, and it looks like u is now deprecated.

        try:                                                                                                                                                          
            return array.array('c', data)                                          
        except TypeError:                                                          
            return array.array('u', data)

I think the proper fix would be to not accept unicode strings or char sequences in the as_array function, so the user of pyusb has to manually encode their string to bytes (using whatever encoding they need to) before calling write or ctrl_transfer.

PyUSB not compatible with Python 3.3.0 under Windows 7

My environment is Windows 7, and I have both Python 3.3.0 and Python 2.7.3 installed. Development environment is PyCharm.

An FTDI cable was connected and the driver replaced with libusb using Zadig i.e. libusb-win32 (v1.2.6.0). The DLLs are all present and correct in C:\Windows\system32.

pyusb-1.0.0a2 was installed via the GUI in PyCharm.

Using Python 3.3.0 as the interpreter, the error "No backend available". I stepped through the code, and got a different result - the DLL is found, loaded, and further progress is made. If I run the code with a few breakpoints, ctypes.util.find_library() in libusb10.py fails to find the DLL in system32.

If I change to Python 2.7.3, it works fine.

preserve 0.x PyUSB version

0.x and 1.x PyUSB versions are very different and they may not be fully compatible, that's why it would be good to be able use both of them on the same Python system.
Currently it is not possible because 1.x overwrites 0.x (they use the same module name)

Possible solution:

creating 2 packages:
- PyUSB 1.x: current module renamed to usb1
- PyUSB Legacy: a module named usb, redirecting calls to usb1, overwrites PyUSB 0.x

For curent behavior both packages should be installed.

Application → PyUSB Legacy → PyUSB 1.x

If someone needs both PyUSB versions then only PyUSB 1.x should be installed.

Now the application can decide which version is used:

import usb1.legacy as usb

or

import usb

Possible usage:

  • comparison tests
  • using 0.x as an 1.x backend (1.x API is much better and ctypes is not available everywhere ) Application → PyUSB 1.x → PyUSB 0.x

Using tuples + Async support

These are two questions about future direction really, asking them here makes them public:

  • I was wondering if there is a reason to not use namedtuples (or some less obnoxious cousins) to return the descriptors. Do you think there will be a performance penalty that we'd care about? Also, is this something with any clear benefit to justify a call to arms? Does immutability sell? :)
  • I see that there is currently no support for asynchronous IO in pyusb. If I understand correctly, both libusb1 and openusb support async IO. Is this a conscious decision, or something that just hasn't had enough attention yet? Would there be benefits of supporting it (I'd think so!)?

Thanks,
Prathmesh

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.