在Python中查询块设备文件的大小 [英] Query size of block device file in Python

查看:235
本文介绍了在Python中查询块设备文件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,该脚本读取(通常从光学介质读取)标记不可读扇区的文件,以允许重新尝试在其他光学读取器上读取所述不可读扇区.

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 optical reader.

我发现我的脚本不适用于块设备(例如/dev/sr0),以便创建包含的ISO9660/UDF文件系统的副本,因为os.stat().st_size为零.该算法目前需要提前知道文件大小;我可以更改它,但是问题(知道块设备的大小)仍然存在,并且这里没有回答,所以我打开了这个问题.

I discovered that my script does not work with block devices (e.g. /dev/sr0), in order to create a copy of the contained ISO9660/UDF filesystem, because os.stat().st_size is zero. The algorithm currently needs to know the filesize in advance; I can change that, but the issue (of knowing the block device size) remains, and it's not answered here, so I open this question.

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

I am aware of the following two related SO questions:

  • Determine the size of a block device (/proc/partitions, ioctl through ctypes)
  • how to check file size in python? (about non-special files)

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

Therefore, I'm asking: in Python, how can I get the file size of a block device file?

推荐答案

我达到的最干净的"(即不依赖于外部卷和最可重复使用的)Python解决方案是打开设备文件并在最后,返回文件偏移量:

The "most clean" (i.e. not dependent on external volumes and most reusable) Python solution I've reached, is to open the device file and seek 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)

这篇关于在Python中查询块设备文件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆