为什么我不能在python中调用HDIO_GETGEO?
问题描述:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########## THIS NOW WORKS! ##########
UNSUITABLE_ENVIRONMENT_ERROR = \
"This program requires at least Python 2.6 and Linux"
import sys
import struct
import os
from array import array
# +++ Check environment
try:
import platform # Introduced in Python 2.3
except ImportError:
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
if platform.system() != "Linux":
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
if platform.python_version_tuple()[:2] < (2, 6):
print >>sys.stderr, UNSUITABLE_ENVIRONMENT_ERROR
# --- Check environment
HDIO_GETGEO = 0x301 # Linux
import fcntl
def get_disk_geometry(fd):
geometry = array('c',"XXXXXXXX")
fcntl.ioctl(fd, HDIO_GETGEO, geometry, True)
heads, sectors, cylinders, start = \
struct.unpack("BBHL",geometry.tostring())
return { 'heads' : heads, 'cylinders': cylinders, 'sectors': sectors, "start": start }
from pprint import pprint
fd=os.open("/dev/sdb", os.O_RDWR)
pprint(get_disk_geometry(fd))
答
似乎没有人能告诉我为什么你不能这样做,但你可以用ctypes做到这一点,所以它并不重要。
#!/usr/bin/env python
from ctypes import *
import os
from pprint import pprint
libc = CDLL("libc.so.6")
HDIO_GETGEO = 0x301 # Linux
class HDGeometry(Structure):
_fields_ = (("heads", c_ubyte),
("sectors", c_ubyte),
("cylinders", c_ushort),
("start", c_ulong))
def __repr__(self):
return """Heads: %s, Sectors %s, Cylinders %s, Start %s""" % (
self.heads, self.sectors, self.cylinders, self.start)
def get_disk_geometry(fd):
""" Returns the heads, sectors, cylinders and start of disk as rerpoted by
BIOS. These us usually bogus, but we still need them"""
buffer = create_string_buffer(sizeof(HDGeometry))
g = cast(buffer, POINTER(HDGeometry))
result = libc.ioctl(fd, HDIO_GETGEO, byref(buffer))
assert result == 0
return g.contents
if __name__ == "__main__":
fd = os.open("/dev/sdb", os.O_RDWR)
print repr(get_disk_geometry(fd))
+0
使用'import *'会污染你的命名空间,使得程序难以阅读和调试。如果您需要简洁,请考虑使用'import extralongmodulename as e'。 – 2010-09-03 20:10:47
+0
ctypes是我使用过的唯一模块,我同意,但ctypes是屁股的一般疼痛。我想把它导入为C或者什么都行。 – user376403 2010-09-03 20:31:05
这里有问题吗? – 2010-06-27 07:32:22
是的,为什么这个代码不工作,一个工作示例会膨胀:D – user376403 2010-06-27 07:38:21
TypeError:ioctl需要文件或文件描述符,整数以及可选的整数或缓冲区参数 未捕获的异常。进入验尸调试 跑着 '续' 或 '步' 将重新启动程序 > /首页/抢/ ricedisk(25)get_disk_geometry() - > fcntl.ioctl(FD,HDIO_GETGEO,几何,真) (PDB) p HDIO_GETGEO (PDB)p型(HDIO_GETGEO) (PDB)p型(FD) –
user376403
2010-06-27 07:41:51