代码之家  ›  专栏  ›  技术社区  ›  tzot

python中块设备文件的查询大小

  •  3
  • tzot  · 技术社区  · 16 年前

    我有一个python脚本,它读取一个标记不可读扇区的文件(通常是从光学介质读取的),以允许在不同的光学读取器上重新尝试读取上述不可读扇区。

    我发现我的脚本不能与块设备(例如/dev/sr0)一起工作,无法创建包含的iso9660/udf文件系统的副本,因为 os.stat().st_size 是零。算法目前需要预先知道文件大小;我可以更改它,但是(知道块设备大小)问题仍然存在,这里没有回答,所以我打开了这个问题。

    我知道以下两个相关的SO问题:

    因此,我要问:在python中,如何获得块设备文件的文件大小?

    3 回复  |  直到 13 年前
        1
  •  7
  •   tzot    16 年前

    我找到的最干净的python解决方案是打开设备文件并在最后查找,返回文件偏移量:

    def get_file_size(filename):
        "Get the file size by seeking at end"
        fd= os.open(filename, os.O_RDONLY)
        try:
            return os.lseek(fd, 0, os.SEEK_END)
        finally:
            os.close(fd)
    
        2
  •  5
  •   rmsr    13 年前

    基于Linux特定IOCTL的解决方案:

    import fcntl
    import struct
    
    device_path = '/dev/sr0'
    
    req = 0x80081272 # BLKGETSIZE64, result is bytes as unsigned 64-bit integer (uint64)
    buf = ' ' * 8
    fmt = 'L'
    
    with open(device_path) as dev:
        buf = fcntl.ioctl(dev.fileno(), req, buf)
    bytes = struct.unpack('L', buf)[0]
    
    print device_path, 'is about', bytes / (1024 ** 2), 'megabytes'
    

    当然,其他unix对于req、buf、fmt有不同的值。

        3
  •  0
  •   XTL    14 年前

    试图从另一个答案中适应:

    import fcntl
    c = 0x00001260 ## check man ioctl_list, BLKGETSIZE
    f = open('/dev/sr0', 'ro')
    s = fcntl.ioctl(f, c)
    print s
    

    我手头没有合适的电脑来测试这个。我很想知道它是否有效:)