I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good example.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Update: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and udev, I keep the Hal version for historical reasons.
This is basically the example in the pyudev documentation, adapted to work with older versions, and with the glib loop, notice that the filter should be customized for your specific needing:
Old version with Hal and d-bus:
You can use D-Bus bindings and listen to
DeviceAdded
andDeviceRemoved
signals. You will have to check the capabilities of the Added device in order to select the storage devices only.Here is a small example, you can remove the comments and try it.
You need to connect to Hal Manager using the System Bus.
And you need to connect a listener to the signals you are interested on, in this case
DeviceAdded
.I'm using a filter based on capabilities. It will accept any
volume
and will calldo_something
with if, you can read Hal documentation to find the more suitable queries for your needs, or more information about the properties of the Hal devices.Example function that shows some information about the volume:
I think D-Bus would work as Chris mentioned, but if you're using KDE4, you might use the Solid framework in a manner similar to the KDE4 "New Device Notifier" applet.
The C++ source for that applet is here, which shows how to use Solid to detect new devices. Use PyKDE4 for Python bindings to these libraries, as shown here.
I haven't tried writing such a program myself, however I've just looked at the following two links (thanks Google!), which I think will be of help:
In particular, read about the
org.freedesktop.Hal.Manager
interface, and itsDeviceAdded
andDeviceRemoved
events. :-)Hope this helps!
Here is a solution in 5 lines.
Save this to a file say
usb_monitor.py
, runpython monitor.py
. Plug any usb and it will print device detailsTested on Python 3.5 with
pyudev==0.21.0
.