ITeye博客

python获得磁盘剩余空间 statvfs

pypy · 2010-04-01 14:43 · python · 编程语言 · Markdown

在linux上工作大家都会用到df命令

[tommy@tommy-1 ~]$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda5             4.8G  389M  4.2G   9% /
/dev/sda7             271G  3.5G  254G   2% /home
/dev/sda3             4.8G  1.1G  3.5G  24% /usr
/dev/sda2             4.8G  199M  4.3G   5% /var
/dev/sda1              99M   18M   77M  19% /boot
tmpfs                 997M     0  997M   0% /dev/shm

这个df命令有个问题,即是磁盘的某个卷有问题,比如offline了 那么很有可能就是当你执行df命令的时候,就挂掉了,

在开发一个系统中,需要随时获得指定磁盘的剩余空间的功能 (如果使用df,很有可能会导致程序block在那里)

所以,我们这里使用python自带的statvfs模块来完成侦测磁盘剩余空间的功能

参考 http://docs.python.org/library/statvfs.html http://docs.python.org/library/os.html

[mps@mps-1 ~]$ python
Python 2.4.3 (#1, Sep  3 2009, 15:37:37)
[gcc 4.1.2 20080704 (red hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import statvfs
>>> vfs=os.statvfs("/home")
>>> vfs
(4096, 4096, 70959944, 70058799, 66396080, 73269248, 73234981, 73234981, 0, 255)
>>> dir(statvfs)
['f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize', 'f_namemax', '__builtins__', '__doc__', '__file__', '__name__']
>>> available=vfs[statvfs.f_bavail]*vfs[statvfs.f_bsize]/(1024*1024*1024)
>>> available
253
>>> capacity=vfs[statvfs.f_blocks]*vfs[statvfs.f_bsize]/(1024*1024*1024)
>>> capacity
270
>>> used=capacity-available
>>> used
17
>>>

评论(3)

  1. #3 楼 · pypy · 2010-04-19 16:14

    恩,这个可能是设计上方向的问题,

    不过,你可以看下 statvfs.py 库

    如果你对linux的C熟悉的话,你就可以理解,这些都是一些标准定义罢了

    """Constants for interpreting the results of os.statvfs() and os.fstatvfs()."""
    
    # Indices for statvfs struct members in the tuple returned by
    # os.statvfs() and os.fstatvfs().
    
    F_BSIZE   = 0           # Preferred file system block size
    F_FRSIZE  = 1           # Fundamental file system block size
    F_BLOCKS  = 2           # Total number of file system blocks (FRSIZE)
    F_BFREE   = 3           # Total number of free blocks
    F_BAVAIL  = 4           # Free blocks available to non-superuser
    F_FILES   = 5           # Total number of file nodes
    F_FFREE   = 6           # Total number of free file nodes
    F_FAVAIL  = 7           # Free nodes available to non-superuser
    F_FLAG    = 8           # Flags (see your local statvfs man page)
    F_NAMEMAX = 9           # Maximum file name length
    
    
  2. #2 楼 · Zandy · 2010-04-16 19:28

    Deprecated since version 2.6: The statvfs module has been deprecated for removal in Python 3.0. @see http://docs.python.org/library/statvfs.html

  3. #1 楼 · coffeesweet · 2010-04-15 09:47

    对这个不是很熟,回头看看API

评论功能维护中,当前仅展示历史评论。