Action on (dis) connecting usb device
The tiny script below will suspend the computer on the event of disconnecting a (any) usb volume.
#!/usr/bin/env python3
import gi
from gi.repository import GLib, Gio
import subprocess
class WatchOut:
def __init__(self):
someloop = GLib.MainLoop()
self.setup_watching()
someloop.run()
def setup_watching(self):
self.watchdrives = Gio.VolumeMonitor.get()
# event to watch (see further below, "Other options")
self.watchdrives.connect("volume_removed", self.actonchange)
def actonchange(self, *args):
# command to run (see further below, "Other options")
subprocess.Popen(["systemctl", "suspend"])
WatchOut()
To use:
Other options
In this script, obviously the signal on "volume_removed"
is used. Other possible events:
"volume_added", "volume_removed", "mount_added", "mount_removed"
To make it perform other commands on event, replace the command in the line:
subprocess.Popen(["systemctl", "suspend"])
(command and args are set as a list, like ["systemctl", "suspend"]
)
EDIT - Only act on specifically named volumes
As mentioned in a comment, you'd prefer to only run a command on specifically named volumes. If you run the example below with one or more volumenames as arguments, action will be limited to only those volumes:
#!/usr/bin/env python3
import gi
from gi.repository import GLib, Gio
import subprocess
import sys
args = sys.argv[1:]
class WatchOut:
def __init__(self):
someloop = GLib.MainLoop()
self.setup_watching()
someloop.run()
def setup_watching(self):
self.watchdrives = Gio.VolumeMonitor.get()
# event to watch (see further below, "Other options")
self.watchdrives.connect("volume_removed", self.actonchange)
def actonchange(self, event, volume):
if volume.get_name() in args:
# command to run (see further below, "Other options")
subprocess.Popen(["systemctl", "suspend"])
WatchOut()
Usage
Is pretty much the same as the first one, just add the volumenames as arguments, e.g.
python3 /path/to/watchout.py <volumename_1> <volumename_2>
tail -f /var/log/syslog.log
and try to connect/disconnect your USB device. – FedKad Sep 22 '19 at 14:10