Block device file request size in Python

I have a Python script that reads a file (usually from optical media) designating unreadable sectors in order to retry reading the specified unreadable sectors on another optical reader.

I found that my script does not work with block devices (e.g. / dev / sr0) to create a copy of the ISO9660 / UDF file system because it os.stat().st_sizeis zero. The algorithm currently needs to know the file size in advance; I can change this, but the problem (knowing the size of the device block) remains, and she did not answer here, so I open this question.

I am aware of the following two related questions:

So I ask: in Python, how can I get the file size of a block device?

+4
source share
4 answers

“Cleanest” (i.e., independent of external volumes and the most reusable). The Python solution I have achieved is to open the device file and search at the end, returning the file offset:

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)
+8
source

Ioctl Linux-specific 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 meanings for req, buf, fmt, of course.

+5
source

:

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

, . , :)

0

def blockdev_size(path):
    """Return device size in bytes.
    """
    with open(path, 'rb') as f:
        return f.seek(0, 2) or f.tell()

or f.tell() Python 2 or f.tell() - file.seek() None Python 2.

The magic constant 2can be replaced by . io.SEEK_END

0
source

Source: https://habr.com/ru/post/1744159/


All Articles