2010-06-27 45 views
0
#!/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)) 
+0

這裏有問題嗎? – 2010-06-27 07:32:22

+0

是的,爲什麼這個代碼不工作,一個工作示例會膨脹:D – user376403 2010-06-27 07:38:21

+0

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

回答

0

似乎沒有人能告訴我爲什麼你不能這樣做,但你可以用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

相關問題