如果断开(任何)USB 卷的连接,下面的小脚本将挂起计算机。
#!/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()
Run Code Online (Sandbox Code Playgroud)
watchout.py
在后台运行它:
python3 /path/to/watchout.py
Run Code Online (Sandbox Code Playgroud)在这个脚本中,显然使用了信号 on "volume_removed"
。其他可能的事件:
"volume_added", "volume_removed", "mount_added", "mount_removed"
Run Code Online (Sandbox Code Playgroud)
要使其在事件上执行其他命令,请替换该行中的命令:
subprocess.Popen(["systemctl", "suspend"])
Run Code Online (Sandbox Code Playgroud)
(命令和参数被设置为一个列表,如["systemctl", "suspend"]
)
正如评论中提到的,您更愿意只在特定命名的卷上运行命令。如果您使用一个或多个卷名作为参数运行以下示例,则操作将仅限于这些卷:
python3 /path/to/watchout.py
Run Code Online (Sandbox Code Playgroud)
与第一个几乎相同,只需添加卷名作为参数,例如
python3 /path/to/watchout.py <volumename_1> <volumename_2>
Run Code Online (Sandbox Code Playgroud)