在Linux中使用Python向USB闪存写文件?
我在写文件的时候遇到了比预期更多的麻烦。我有一台运行在arm处理器上的小型单板电脑,使用的是Angstrom嵌入式系统。我正在用Python为它写一个应用程序。这个应用程序应该能够识别USB闪存盘,然后把文件写入到上面。问题是,即使我的脚本看起来正确地写入了文件,并且在Linux中用“ls”和“cat”命令查看时文件也显示存在,但当我拔掉USB闪存盘,尝试在Windows或其他Linux系统中查看这个文件时,它要么是空的,要么根本就不存在。我的应用程序是多线程的。我以root身份创建了/media/mymntpnt这个目录。
任何帮助都非常感谢。
以下是我代码的一些片段:
这部分是我用来识别USB闪存盘的:
class MediaScanner():
def __init__(self):
self.lok = thread.allocate_lock()
self.running = True
self.started = False
def register_cb(self,func):
self.cb = func
def start(self):
if not self.started:
thread.start_new_thread(self.scan_thread,())
def scan_thread(self):
self.quit = False
self.started = True
last_devices = []
while self.running:
devices = self.scan_media()
if (devices != last_devices):
self.cb(devices) #call the callback as its own thread
last_devices = devices
time.sleep(0.1)
self.quit = True
def stop(self):
self.running = False
while(not self.quit):
pass
return True
def is_running(self):
return self.running
def scan_media(self):
with self.lok:
partitionsFile = open("/proc/partitions")
lines = partitionsFile.readlines()[2:]#Skips the header lines
devices = []
for line in lines:
words = [x.strip() for x in line.split()]
minorNumber = int(words[1])
deviceName = words[3]
if minorNumber % 16 == 0:
path = "/sys/class/block/" + deviceName
if os.path.islink(path):
if os.path.realpath(path).find("/usb") > 0:
devices.append('/dev/'+deviceName)
partitionsFile.close()
return devices
这是我用来写文件的脚本示例:
from mediascanner import *
from util import *
from database import *
from log import *
ms = MediaScanner()
devices = ms.scan_media()
print devices
if devices:
db = TestDatabase(init_tables=False)
data = db.get_all_test_data()
for device in devices:
print device
mount_partition(get_partition(device))
write_and_verify('/media/mymntpnt/test_'+get_log_file_name(),flatten_tests(data))
unmount_partition()
还有我的一些工具函数:
def write_and_verify(f_n,data):
f = file(f_n,'w')
f.write(data)
f.flush()
f.close()
f = file(f_n,'r')
verified = f.read()
f.close()
return verified == data and f.closed
def get_partition(dev):
os.system('fdisk -l %s > output' % dev)
f = file('output')
data = f.read()
print data
f.close()
return data.split('\n')[-2].split()[0].strip()
def mount_partition(partition):
os.system('mount %s /media/mymntpnt' % partition)
def unmount_partition():
os.system('umount /media/mymntpnt')
1 个回答
1
错误出在写入函数上,它在关闭文件之前应该先同步文件,下面有示例代码。读取操作总是能成功,因为数据已经在内存中。你可能想尝试其他方法来验证,比如检查字节数。
def write_and_verify(f_n,data):
f = file(f_n,'w')
f.write(data)
f.flush()
os.fsync(f.fileno())
f.close()
f = file(f_n,'r')
verified = f.read()
f.close()
return verified == data and f.closed
如果你这样获取文件信息 finfo = os.stat(f_n)
,那么你可以将 finfo.st_size
和你预期写入的字节数进行比较。