如何在 USB 闪存驱动器插入上运行 Python 脚本

Posted

技术标签:

【中文标题】如何在 USB 闪存驱动器插入上运行 Python 脚本【英文标题】:How to run Python script on USB flash-drive insertion 【发布时间】:2017-12-07 09:33:45 【问题描述】:

我的目标是在插入 USB 闪存驱动器时运行 Python 脚本。我已经编写了一个 udev 规则和一个在该规则中调用的 shell 脚本。

udev 规则:/etc/udev/rules.d/10-usb.rules

KERNEL=="sd*[!0-9]|sr*", ENVID_SERIAL!="?*", SUBSYSTEMS=="usb", RUN+="/home/Hypotheron/Desktop/script.sh" 

script.sh:

#!/bin/sh

echo 'Hello, world.' > /home/Hypotheron/Desktop/foo.txt
#/home/Hypotheron/Desktop/job.py & exit

我的 Python 文件的第一行是:

#!/usr/bin/python 

我还执行了以下命令:

chmod +x job.py
chmod +x script.sh

在 script.sh 中,当写入 foo.txt 的行未注释时,每次插入闪存驱动器都会创建 foo.txt 文件。

当我注释该行并取消注释运行 Python 文件的行时,它不起作用。

通过终端运行 script.sh 在这两种情况下都有效,但在插入闪存驱动器时,只有 foo.txt 案例有效。

任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:
   RUNtype
       Add a program to the list of programs to be executed after
       processing all the rules for a specific event, depending on "type":

       "program"
           Execute an external program specified as the assigned value. If
           no absolute path is given, the program is expected to live in
           /lib/udev; otherwise, the absolute path must be specified.

           This is the default if no type is specified.

       "builtin"
           As program, but use one of the built-in programs rather than an
           external one.

       The program name and following arguments are separated by spaces.
       Single quotes can be used to specify arguments with spaces.

       This can only be used for very short-running foreground tasks.
       Running an event process for a long period of time may block all
       further events for this or a dependent device.

       Starting daemons or other long-running processes is not appropriate
       for udev; the forked processes, detached or not, will be
       unconditionally killed after the event handling has finished.

从 udev 手册页,特别注意最后 2 段。 我猜,是你发现了无条件杀人的部分

一年后编辑: 在有人投票后我重新审视了这个问题,我已经解决了这些问题,即root(谁正在运行这个进程)没有一个 X 终端条目对于某些事情来说是必不可少的,比如notify-send 或启动一个 Gui 程序和如前所述,事件发生后仍然会杀死进程。 下面在插入 USB 设备时向终端发送通知并启动 wxPython Gui 程序。

脚本:

#!/bin/sh
DISPLAY=:0
export DISPLAY
/usr/bin/notify-send "Usb Device detected" "Starting Reminder program" | at now
/usr/bin/python3 /home/rolf/reminders/reminders2.1.0/reminder.py | at now

通过定义 DISPLAY,我们解决了 root 没有 X 词条目的问题 通过将我们希望运行的命令传递给 at 程序,并带有立即运行的指令,我们可以避免 udev 杀死进程。

/lib/udev/rules.d/10-usbinsert.rules 文件:

KERNEL=="sd*[!0-9]|sr*", ENVID_SERIAL!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/sudo -u rolf /home/rolf/script.sh &"

我希望这能帮助你或让你朝着正确的方向前进。

【讨论】:

以上是关于如何在 USB 闪存驱动器插入上运行 Python 脚本的主要内容,如果未能解决你的问题,请参考以下文章

电脑如何区分键盘USB和鼠标USB?

重新启动 Windows 8 并从 USB 闪存驱动器启动的代码

如何在 Linux 下的 C 中确定 USB 存储(USB 闪存驱动器)“设备路径”

如何获取 USB 闪存驱动器的制造商序列号?

如何模拟 USB 闪存驱动器并同时读取数据

USB闪存驱动器制造商序列号