首页 文章

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

提问于
浏览
6

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

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

KERNEL=="sd*[!0-9]|sr*", ENV{ID_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

在脚本.sh中,当写入foo.txt的行被取消注释时,每次闪存驱动器插入时都会创建foo.txt文件 .

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

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

任何帮助,将不胜感激 .

1 回答

  • 3
    RUN{type}
           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段 .
    我的猜测是,你发现了无条件的杀戮部分

    编辑1年后:
    在有人投票之后我重新审视了这个问题,我已经解决了问题,即 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*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/sudo -u rolf /home/rolf/script.sh &"
    

    我希望这有助于或让你朝着正确的方向前进 .

相关问题