本文主要介绍在PyQt5中,使用dbus监控U盘插拔。
测试环境:python3 + dbus + pyqt5
当无法引入dbus.mainloop.pyqt5
时,安装对应的包即可:
sudo apt install python3-dbus.mainloop.pyqt5
测试代码如下:
#!/usr/bin/env python3
# encoding: utf-8
"""
@time: 18-4-23 上午11:54
"""
import sys
import dbus
from PyQt5.QtWidgets import QWidget, QApplication
from dbus.mainloop.pyqt5 import DBusQtMainLoop
class Window(QWidget):
def __init__(self):
super().__init__()
# loop = DBusGMainLoop()
DBusQtMainLoop(set_as_default=True)
sessionbus = dbus.SessionBus()
sessionbus.add_signal_receiver(signal_name="MountAdded",
dbus_interface="org.gtk.Private.RemoteVolumeMonitor",
path="/org/gtk/Private/RemoteVolumeMonitor",
bus_name=None,
handler_function=self.mount_added)
sessionbus.add_signal_receiver(signal_name="MountRemoved",
dbus_interface="org.gtk.Private.RemoteVolumeMonitor",
path="/org/gtk/Private/RemoteVolumeMonitor",
bus_name=None,
handler_function=self.mount_removed)
def mount_added(self, sender, id_, data):
print("-" * 10, "MountAdded", "-" * 10)
print(sender)
print(id_)
print(data)
def mount_removed(self, sender, id_, data):
print("-" * 10, "MountRemoved", "-" * 10)
print(sender)
print(id_)
print(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
win.show()
app.exec_()
版权声明:本文为「txfly」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://www.jianshu.com/p/cee5f693c41c