使用Python将文件写入Linux中的USB记忆棒?

时间:2011-07-27 07:14:48

标签: python linux file usb-drive

我写的文件比预期的要多得多。我有一台小型单板计算机在带有Angstrom嵌入式发行版的arm处理器上运行。我用python编写了一个应用程序。应用程序应检测USB记忆棒,然后将文件转储给它。我遇到的问题是,即使我的脚本看起来正确地写了文件,并且文件似乎在那里使用" ls"和" cat"在Linux中,当我移除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 个答案:

答案 0 :(得分:0)

错误在于write函数,它应该在关闭之前同步文件,如下所示。读取将始终成功,因为数据已在RAM中。您可能想尝试不同的方法来验证它,例如检查bytecount。

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与您希望写入的字节数进行比较。