挂载时自动将文件复制到 USB Raspberry Pi

Copy file to USB automatically on mount Raspberry Pi

我目前正在做一个项目,该项目需要在安装时自动将文件复制到 USB 记忆棒。根据我在互联网上的研究,我相信使用 udev 规则是可行的。因此,当 USB 插入我的 RPi2 时,udev 规则将执行 python 脚本,允许将文件复制到 USB 记忆棒。

问题是,我也听说脚本会在树莓派挂载USB之前执行,也就是说文件不会被复制。有针对这个的解决方法吗?当我在内部复制文件时执行了 python 脚本(在 RPi 本身而不是 USB 上),当我试图将它复制到 USB 时它不起作用。

下面是我的代码:

Udev 规则

KERNEL=="sd*1", ACTION=="add", RUN=="/home/pi/datalogger/autocopy.sh"

Shell 脚本

cd /
cd /home/pi/datalogger
sudo /usr/bin/python autocopy.py
cd / 
exit

Python 脚本

import shutil
import datetime

# File to be copied
source = "/home/pi/copied.txt"

# USB name must be changed to 'USB1' in order for auto copy to work
destination = "/media/pi/USB1/datalogger_backup_%s.txt" % datetime.datetime.now().date()

try:
   # Copy file to destination
   shutil.copy2(source, destination)
   # E.g. source and destination is the same location
except shutil.Error as e:
   print("Error: %s" % e)
   # E.g. source or destination does not exist
except IOError as e:
   print("Error: %s" % e.strerror)

Question: ... the destination is not available as the USB is yet to be mounted

将以下内容添加到您的 script 以验证 mount 状态:

mount >> /tmp/mount.log

读这个auto-mounting-usb-storage/
也许你可以适应你的需要。