簡體   English   中英

如何在USB閃存驅動器插入上運行Python腳本

[英]How to run Python script on USB flash-drive insertion

我的目標是在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案例有效。

任何幫助,將不勝感激。

   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 &"

我希望這有助於或讓你朝着正確的方向前進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM