使用Python打开设备进行原始写入

1 投票
1 回答
3533 浏览
提问于 2025-04-17 02:06

我正在写一些代码,用来读取和解释一个格式化为fat32的U盘的主引导记录(MBR)和文件分配表(FAT),一切都进行得很顺利。现在我想在设备的特定位置写入数据,所以在关闭我之前打开的设备后,我又尝试了这样:

dr = file("/dev/disk5","r+")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 IOError: [Errno 16] Resource busy: '/dev/disk5'

所以我把所有东西都关掉,然后用sudo重新启动解释器(sudo python),再试一次,结果还是一样。

我该怎么做才能打开设备进行写入呢?谢谢。

编辑,附上一些代码。

import sys,os
disk = file("/dev/disk5",'rb')
disk.seek(0)
sector_size=512
first_sector = disk.read(1*sector_size)
fat_part_list = (first_sector[-66:])[:64]
part1=fat_part_list[:16]
#more code here in order to analyse the first partition information in the MBR and get the required offset to actually read the partition itself.
#now for instance lets say I want to write here in sector 1 byte 0 ( so basically at seek(0).
disk.close()#close the device
disk = file("/dev/disk5","r+")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  IOError: [Errno 16] Resource busy: '/dev/disk5'

其实你可以简单地把问题看作这样:

http://pastie.org/2521541

我从来没有成功让格式化正常工作……

这看起来像是权限错误,但用sudo运行解释器并没有改变什么。

1 个回答

1

在用Python打开块设备之前,你应该先卸载它。

撰写回答