gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:34:25 24 4
gpt4 key购买 nike

我的目标是在 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" 

脚本.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 情况下有效。

如有任何帮助,我们将不胜感激。

最佳答案

   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 -发送 或启动一个 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 &"

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

关于python - 如何在 USB 闪存驱动器插入时运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44897023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com