我为嵌入式linux创建python脚本,脚本监视USB存储插入和移除,如果USB驱动器插入则计算机将文件复制到USB驱动器。脚本需要在启动后启动所以我在我的系统ctl中创建服务这里是myscript.service:
[Unit]
Description=My Script Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python2 /home/kiki/PycharmProjects/copyfiletousb /copyfile.py
[Install]
WantedBy=multi-user.target
这是我的python文件(copyfile.py)
from __future__ import division
import pyudev
import serial
import time
from shutil import copyfile
import os.path
ser=serial.Serial('/dev/ttyUSB0')
ser.baudrate=19200
ser.write(bytearray(chr(27)))
ser.write(bytearray(" Standby"))
def copyfile(source, dest, buffer_size=1024 * 1024):
if os.path.exists(dest):
print "File %s already exists" % dest
return
if not os.path.exists(source):
print "File %s doesnt exist" % source
return
if not hasattr(source, 'read'):
source = open(source, 'rb')
if not hasattr(dest, 'write'):
dest = open(dest, 'wb')
print "Start copy..."
size=os.path.getsize('fedora.iso')
size=size//buffer_size
q=0
old_propgress=0
while 1:
q=q+1
copy_buffer = source.read(buffer_size)
progress=((q*100.0)//size)
if old_propgress != progress :
ser.write(bytearray(chr(27)))
ser.write(bytearray(" Copying file : \ "+str(int(progress))+" %"))
old_propgress=progress
if (progress==100):
ser.write(bytearray(chr(27)))
ser.write(bytearray(" Done"))
if copy_buffer:
try:
dest.write(copy_buffer)
except:
ser.write(bytearray(chr(27)))
ser.write(bytearray(" Ruang Tidak Cukup"))
break
else:
break
print (q)
source.close()
dest.close()
print "Finished!"
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
insert=0
remove=0
for device in iter(monitor.poll, None):
if device.action == 'add' and insert==0:
ser.write(bytearray(chr(27)))
ser.write(bytearray(" USB Terh ubung"))
time.sleep(5)
copyfile("fedora.iso", "/media/kiki/USBSTORAGENAME/vessel.iso")
insert=1
remove=0
print(device.sequence_number)
if device.action== 'remove' and remove==0:
insert = 0
remove = 1
ser.write(bytearray(chr(27)))
ser.write(bytearray(' USB terp utus'))
time.sleep(2)
ser.write(bytearray(chr(27)))
ser.write(bytearray(' standby'))
我的问题是数据没有转移到USB存储