Linux:在PyQt5 GUI上显示所有当前连接的USB记忆棒的名称

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (50)

以下代码显示了Linux上控制台中新插入的USB记忆棒的名称(作为PyQt5 GUI的替代品)。

不幸的是,只要拔出USB记忆棒而没有正确弹出它,就会在控制台中出现pyudev.device._errors.DeviceNotFoundAtPathError

需要更改什么来修复此错误?

main.py:

from functools import partial
import os
import sys

import pyudev

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QSocketNotifier, QObject, pyqtSignal


class MainWindow():

    def __init__(self, parent=None):
        super().__init__()
        # GUI code
        pass

    def print_name(self, name):
        print(name)


class LinuxDeviceMonitor(QObject):
    devices_changed = pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self._context = pyudev.Context()

        self._monitor = pyudev.Monitor.from_netlink(self._context)
        self._monitor.start()

        self._devices = set()

        self._process_devices(self._context.list_devices(), action="add")

    def fileno(self):
        return self._monitor.fileno()

    @property
    def device_names(self):
        return [pyudev.Devices.from_path(self._context, device).get("DEVNAME") for device in self._devices]

    def process_incoming(self):
        read_device = partial(pyudev._util.eintr_retry_call, self._monitor.poll, timeout=0)
        self._process_devices(iter(read_device, None))
        self.devices_changed.emit(self.device_names)

    def _process_devices(self, devices, action=None):
        for device in devices:
            action = device.action if action is None else action

            if action in ("add", "change") and self._is_usb_mass_storage_device(device):
                self._devices.add(device.sys_path)
            elif action == "remove" and device.sys_path in self._devices:
                self._devices.remove(device.sys_path)

    @classmethod
    def _read_device_flag(self, device, name):
        path = os.path.join(device.sys_path, name)
        try:
            with open(path) as data:
                return bool(int(data.read()))
        except (IOError, ValueError):
            return False

    def _is_usb_mass_storage_device(self, device):
        is_removable = self._read_device_flag(device, "removable")
        has_size = self._read_device_flag(device, "size")
        has_usb = device.get("ID_BUS") == "usb"
        has_no_disc = device.get("ID_CDROM") is None
        return is_removable and has_size and has_usb and has_no_disc


def main():
    app = QApplication(sys.argv)

    main_window = MainWindow()

    linux_device_monitor = LinuxDeviceMonitor()

    notifier = QSocketNotifier(linux_device_monitor.fileno(), QSocketNotifier.Read)
    notifier.activated.connect(linux_device_monitor.process_incoming)

    linux_device_monitor.devices_changed.connect(main_window.print_name)

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
提问于
用户回答回答于

你可以简单地捕获异常:

更改

    @property
    def device_names(self):
        return [pyudev.Devices.from_path(self._context, device).get("DEVNAME") for device in self._devices]

    def device_names(self):
        devices = []
        for device in self._devices:
            try:
                dev_name = pyudev.Devices.from_path(self._context, device).get("DEVNAME")
                devices.append(dev_name)
            except pyudev.DeviceNotFoundAtPathError:
                pass
        return devices

        self.devices_changed.emit(self.device_names)

        self.devices_changed.emit(self.device_names())

整个代码:

from functools import partial
import os
import sys

import pyudev

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QSocketNotifier, QObject, pyqtSignal


class MainWindow():

    def __init__(self, parent=None):
        super().__init__()
        # GUI code
        pass

    def print_name(self, name):
        print(name)


class LinuxDeviceMonitor(QObject):
    devices_changed = pyqtSignal(list)

    def __init__(self):
        super().__init__()
        self._context = pyudev.Context()

        self._monitor = pyudev.Monitor.from_netlink(self._context)
        self._monitor.start()

        self._devices = set()

        self._process_devices(self._context.list_devices(), action="add")

    def fileno(self):
        return self._monitor.fileno()

    def device_names(self):
        devices = []
        for device in self._devices:
            try:
                dev_name = pyudev.Devices.from_path(self._context, device).get("DEVNAME")
                devices.append(dev_name)
            except pyudev.DeviceNotFoundAtPathError:
                pass
        return devices

    def process_incoming(self):
        read_device = partial(pyudev._util.eintr_retry_call, self._monitor.poll, timeout=0)
        self._process_devices(iter(read_device, None))
        self.devices_changed.emit(self.device_names())

    def _process_devices(self, devices, action=None):
        for device in devices:
            action = device.action if action is None else action

            if action in ("add", "change") and self._is_usb_mass_storage_device(device):
                self._devices.add(device.sys_path)
            elif action == "remove" and device.sys_path in self._devices:
                self._devices.remove(device.sys_path)

    @classmethod
    def _read_device_flag(self, device, name):
        path = os.path.join(device.sys_path, name)
        try:
            with open(path) as data:
                return bool(int(data.read()))
        except (IOError, ValueError):
            return False

    def _is_usb_mass_storage_device(self, device):
        is_removable = self._read_device_flag(device, "removable")
        has_size = self._read_device_flag(device, "size")
        has_usb = device.get("ID_BUS") == "usb"
        has_no_disc = device.get("ID_CDROM") is None
        return is_removable and has_size and has_usb and has_no_disc


def main():
    app = QApplication(sys.argv)

    main_window = MainWindow()

    linux_device_monitor = LinuxDeviceMonitor()

    notifier = QSocketNotifier(linux_device_monitor.fileno(), QSocketNotifier.Read)
    notifier.activated.connect(linux_device_monitor.process_incoming)

    linux_device_monitor.devices_changed.connect(main_window.print_name)

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

输出:

[]
[]
[]
['/dev/sdc']
['/dev/sdc']
['/dev/sdc']
[]
[]
[]

热门问答

关于Linux DNS服务器设置问题?

mariolu

腾讯 · 后台开发工程师 (已认证)

CDN及云从业者
推荐

CNAME到XX.com,这个XX.COM本身也是需要能解析ip的。CNAME到XX.COM的意义是你能解析到CDN厂商A的域名XX.COM或者CDN厂商B的域名YY.COM。所以需要提供服务的CDN厂商给你他们的域名。这样,DNS查询链路才是完整的。

我刚申请的服务器,缺省给我的是linux,可我要Windows,怎么办?

蒋小爱

腾讯云 · 技术支持 (已认证)

推荐
云服务器提供 不同平台重装:仅支持中国大陆地区(不含中国香港)。 例如,Linux 重装为 Windows,Windows 重装为 Linux 。 参考 重装系统: https://cloud.tencent.com/document/product/213/4933 图片.p...... 展开详请

合作伙伴学院里的学习视频测试题和在线培训系统里的测试题能否提供答案?

骑牛看晨曦love&peace~
推荐

http://tencentcloudxuexi.com 合作伙伴可以登录此平台做练习题,有答案的喔

云服务器不能访问外部网站?

HappyLau谈云计算

腾讯云 · 云计算高级工程师 (已认证)

专注于公有云,私有云解决方案,在kubernetes,openstack,kvm,ceph,linux,shell有丰富的实战经验。
推荐
不能访问外部网站一般是网络和dns的问题,按照如下步骤排查: 1. 确保CVM有外网ip或者NAT转换,使用ping测试下外网的连通性,如果不通请购买弹性公网IP,先申请后购买参考https://cloud.tencent.com/document/product/215/201...... 展开详请

两台腾讯云的服务器在同一个地区,内网网段也相同,都是172.17.0.X,为啥ping内网地址不通?

HappyLau谈云计算

腾讯云 · 云计算高级工程师 (已认证)

专注于公有云,私有云解决方案,在kubernetes,openstack,kvm,ceph,linux,shell有丰富的实战经验。
推荐已采纳

首先看下两台机器是否在同个vpc内,在同个vpc内默认网络可以互通,如果不在同个vpc内需要通过对等连接或者云联网打通,如果在同个vpc下无法互通,请检查下安全组和os的防火墙规则,放行icmp连接。

求问keil5项目无法下载到开发板该怎么解决?

Supowang

腾讯 · 高级工程师 (已认证)

腾讯物联网操作系统TencentOS tiny产品接口人---岁寒知松柏,做最好的自己!
推荐
请检查st-link的驱动和stlink硬件,如果不行,尝试换其他stlink下载器试试,谢谢! 如果还没有解决,请加TencentOS tiny官方QQ群提问,谢谢! qq.png ... 展开详请

所属标签

扫码关注云+社区

领取腾讯云代金券