Issue
I am trying to make a Python script which runs in the background and checks the USB IDs of all plugged in devices to see if it matches a list of recognized IDs. This is going to be ran in a Linux environment with preferably Python 2.x
I know in in linux I can run lsusb
in a shell or run it through os.system()
and that will give me this output:
Bus 003 Device 009: ID 046d:c534 Logitech, Inc. Unifying Receiver
Bus 003 Device 007: ID 046d:082b Logitech, Inc. Webcam C170
Bus 003 Device 005: ID 1532:0043 Razer USA, Ltd
Bus 003 Device 010: ID 05e3:0608 Genesys Logic, Inc. Hub
Bus 003 Device 008: ID 05e3:0608 Genesys Logic, Inc. Hub
Bus 003 Device 006: ID 0424:2137 Standard Microsystems Corp.
Bus 003 Device 004: ID 0451:8044 Texas Instruments, Inc.
However, as you can see this returns way more information than I need and filtering through this will be difficult and take more time. What i need would be something like this:
046d:c534
046d:082b
1532:0043
05e3:0608
05e3:0608
0424:2137
0451:8044
In the interest of keeping this script as fast as possible, is there some way that I can run a command to the system and get back just the USB IDs of everything plugged in, or use grep
or something similar in Python to filter through it somehow?
Thanks in advance!
Solution
Would this solve your problem?
guru@dileant:~$ lsusb
Bus 002 Device 002: ID 8087:8001 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 006 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 005 Device 003: ID 2687:fb01
Bus 005 Device 002: ID 0a5c:21e8 Broadcom Corp. BCM20702A0 Bluetooth 4.0
Bus 005 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8009 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
The following solutions use sed
(stream editor) to print only the relevant parts of the output. This program uses a perl-like syntax to do string replacements. Thus, the command lines are often of the form: sed <flags> 's/<find>/<replace>/g'
.
Finally, sed
uses \( \)
to denote regex groups. You can use regex groups when you want to retain certain parts of the input pattern.
Thus, if you want the Bus and Device numbers, you could do:
guru@dileant:~$ lsusb | sed -e 's/Bus \([0-9]\+\) Device \([0-9]\+\).*/\1:\2/g'
002:002
002:001
006:001
005:003
005:002
005:001
001:002
001:001
Likewise, if you wanted the vendor and product IDs, you could do:
guru@dileant:~$ lsusb | sed -e 's/.*ID \([a-f0-9]\+:[a-f0-9]\+\).*/\1/g'
8087:8001
1d6b:0002
1d6b:0003
2687:fb01
0a5c:21e8
1d6b:0002
8087:8009
1d6b:0002
Answered By - Guru Prasad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.