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

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

概述我的目标是在USB闪存驱动器插入时运行Python脚本.我编写了一个udev规则和一个在该规则中调用的shell脚本.udev规则:/etc/udev/rules.d/10-usb.rulesKERNEL=='sd*[!0-9]|sr*', ENV{ID_SERIAL}!='?*', SUBSYSTEMS=='usb', RUN+='/home/Hypoth

我的目标是在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/shecho 'Hello,world.' > /home/Hypotheron/Desktop/foo.txt#/home/Hypotheron/Desktop/job.py & exit

我的Python文件的第一行是:

#!/usr/bin/python 

我还做了以下命令:

chmod +x job.pychmod +x script.sh

在脚本.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-send或启动Gui程序,仍然存在如前所述,事件发生后仍然是杀戮过程.
当插入USB设备时,以下内容向终端发送通知并启动wxPython Gui程序.

剧本:

#!/bin/shdisPLAY=:0export 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*",RUN+="/usr/bin/sudo -u rolf /home/rolf/script.sh &"

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

以上是内存溢出为你收集整理的如何在USB闪存驱动器插入上运行Python脚本全部内容,希望文章能够帮你解决如何在USB闪存驱动器插入上运行Python脚本所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/1048569.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存