Query size of block device file in Python

后端 未结 4 1209
南笙
南笙 2021-01-05 22:53

I have a Python script that reads a file (typically from optical media) marking the unreadable sectors, to allow a re-attempt to read said unreadable sectors on a different

4条回答
  •  庸人自扰
    2021-01-05 23:30

    Linux-specific ioctl-based solution:

    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'
    

    Other unixes will have different values for req, buf, fmt of course.

提交回复
热议问题