简体   繁体   English

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

[英]Writing a file to a USB stick in linux with Python?

I'm having a lot more trouble than expected writing to a file than I expected. 与编写文件相比,我遇到的麻烦要超出预期。 I have a small Single Board computer running on an arm processor with the Angstrom embedded distribution. 我有一台小型单板计算机,该计算机在具有Angstrom嵌入式发行版的手臂处理器上运行。 I'm writing an application for it with python. 我正在用python编写一个应用程序。 The application should detect the USB stick and then dump the file to it. 应用程序应检测到USB记忆棒,然后将文件转储到其中。 The issue I'm running into is that even when my script appears to write the file correctly, and the file appears to be there using "ls" and "cat" in Linux, when I remove the USB stick and try to look at the file in Windows or another linux distro it's empty or more often not there at all. 我遇到的问题是,即使我的脚本似乎可以正确写入文件,并且在Linux中使用“ ls”和“ cat”文件似乎也在那里,当我卸下USB记忆棒并尝试查看Windows或其他Linux发行版中的文件为空,或者经常根本不存在。 My application is multithreaded. 我的应用程序是多线程的。 I create /media/mymntpnt as root (directory.) 我创建/ media / mymntpnt作为根目录。

Any help is appreciated. 任何帮助表示赞赏。

Here are some snippets of my code: 以下是我的代码片段:

This part is what I use to identify the USB stick: 这是我用来识别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

And here's an example of my script to write the file: 这是我编写文件的脚本的示例:

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()

And here are my utility functions: 这是我的实用函数:

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')

The mistake is in the write function which should sync the file, before closing it, as seen below. 错误在于写功能,该功能应在关闭文件之前同步文件,如下所示。 The read will always succeed because the data is already in RAM. 读取将始终成功,因为数据已在RAM中。 You might want to try something different to verify it such as checking the 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

If you get the file info like this finfo = os.stat(f_n) then you can compare finfo.st_size with the number of bytes that you expected to write. 如果您获得像这样的文件信息finfo = os.stat(f_n)则可以将finfo.st_size与期望写入的字节数进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM