Python中查询块设备文件大小
我有一个 Python 脚本,它读取标记不可读扇区的文件(通常来自光学介质),以允许重新尝试在不同的光学读取器上读取所述不可读扇区。
我发现我的脚本不适用于块设备(例如 /dev/sr0),以便创建包含的 ISO9660/UDF 文件系统的副本,因为 os.stat().st_size 为零。该算法目前需要提前知道文件大小;我可以更改它,但是问题(了解块设备大小)仍然存在,并且这里没有得到解答,所以我提出这个问题。
我知道以下两个相关的SO问题:
- 确定块设备的大小(/proc/partitions,通过ctypes进行ioctl)
- 如何在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.
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.
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)
Therefore, I'm asking: in Python, how can I get the file size of a block device file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我所达到的“最干净”(即不依赖于外部卷并且最可重用)的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:
Linux 特定的基于 ioctl 的解决方案:
当然,其他 Unix 系统的 req、buf、fmt 会有不同的值。
Linux-specific ioctl-based solution:
Other unixes will have different values for req, buf, fmt of course.
另一种可能的解决方案是
或 f.tell()
部分是为了 Python 2 可移植性而存在的 - file.seek() 在 Python 2 中返回 None。魔术常量
2
可以替换为io.SEEK_END
。Another possible solution is
or f.tell()
part is there for Python 2 portability's sake — file.seek() returns None in Python 2.Magic constant
2
may be substituted withio.SEEK_END
.在Linux中,即使没有sudo也可以读取
/sys/block/${dev}/size
。要获取/dev/sdb
的大小,只需执行以下操作:另请参阅 https://unix.stackexchange .com/a/52219/384116
In Linux, there is
/sys/block/${dev}/size
that can be read even without sudo. To get the size of/dev/sdb
simply do:See also https://unix.stackexchange.com/a/52219/384116
此解决方案使用 lsblk(由 util-linux 提供)并且不需要 sudo:
更短的解决方案仅从 lsblk 获取大小:
This solution uses lsblk (provided by util-linux) and does not require sudo:
Shorter solution to only get size from lsblk:
尝试适应其他答案:
我手头没有合适的计算机来测试这一点。我很想知道它是否有效:)
Trying to adapt from the other answer:
I don't have a suitable computer at hand to test this. I'd be curious to know if it works :)