python笔记--磁盘使用率
2015-06-11 15:32
676 查看
方法一:
使用commands.getoutput调用shell命令df获取磁盘使用率:
方法二(感觉有点麻烦,并且不是很明白):
在网上查了可使用os.statvfs函数处理(返回包含文件描述符fd的文件的文件系统的信息,在unix中有效):
使用os.popen()函数获取shell命令执行结果:
使用commands.getoutput调用shell命令df获取磁盘使用率:
import commands >>> import commands >>> disk_use=commands.getoutput('df -h') >>> disk_use 'Filesystem Size Used Avail Use% Mounted on\n/dev/sda2 18G 5.7G 12G 34% /\ntmpfs 931M 0 931M 0% /dev/shm' >>> print disk_use.split('\n')[1].split()[4] 34%该命令返回df命令执行的结果,然后根据该结果进行处理得到使用率的百分比
方法二(感觉有点麻烦,并且不是很明白):
在网上查了可使用os.statvfs函数处理(返回包含文件描述符fd的文件的文件系统的信息,在unix中有效):
>>> os.statvfs('/') posix.statvfs_result(f_bsize=4096, f_frsize=4096, f_blocks=4656351, f_bfree=3172146, f_bavail=2935615, f_files=1183200, f_ffree=1105800, f_favail=1105800, f_flag=4096, f_namemax=255)返回结果说明:
statvfs.F_BSIZE Preferred file system block size. statvfs.F_FRSIZE Fundamental file system block size. statvfs.F_BLOCKS Total number of blocks in the filesystem. statvfs.F_BFREE Total number of free blocks. statvfs.F_BAVAIL Free blocks available to non-super user. statvfs.F_FILES Total number of file nodes. statvfs.F_FFREE Total number of free file nodes. statvfs.F_FAVAIL Free nodes available to non-super user. statvfs.F_FLAG Flags. System dependent: see statvfs() man page. statvfs.F_NAMEMAX Maximum file name length.代码:
>>> import os方法三:
>>> os.statvfs('/') posix.statvfs_result(f_bsize=4096, f_frsize=4096, f_blocks=4656351, f_bfree=3172146, f_bavail=2935615, f_files=1183200, f_ffree=1105800, f_favail=1105800, f_flag=4096, f_namemax=255)
>>> vfs=os.statvfs('/')
>>> print '%d%%' % int((vfs.f_blocks-vfs.f_bfree)/float(vfs.f_blocks)*100)
31%
使用os.popen()函数获取shell命令执行结果:
>>> os.popen('df -h').read() 'Filesystem Size Used Avail Use% Mounted on\n/dev/sda2 18G 5.7G 12G 34% /\ntmpfs 931M 0 931M 0% /dev/shm\n'本来想使用os.system来执行df命令获取结果,但是执行之后发现该命令是返回一个exit_status。
>>> os.system('df -h') Filesystem Size Used Avail Use% Mounted on /dev/sda2 18G 5.7G 12G 34% / tmpfs 931M 0 931M 0% /dev/shm 0最后面一个0才是这个函数的返回值,并且该返回值是一个int类型。当将该结果转换成列表时,就只有一个元素‘0’:
>>> list(str(os.system('df -h'))) Filesystem Size Used Avail Use% Mounted on /dev/sda2 18G 5.7G 12G 34% / tmpfs 931M 0 931M 0% /dev/shm ['0']所以只能使用os.statvfs和commands.getouput来获取磁盘使用率了,但是不知道为什么两个得到的结果不一样。如果有人看到了帮我指出错误,感激不尽。
相关文章推荐
- python写小工具GUI框架wxPython
- Python之学习笔记(QT:GUI设计)
- Python内置的字符串处理函数整理
- 【Python】strip函数
- Python Split函数的用法总结
- 【教程】【PDF】Python2.7教程
- python如何获取某模块的版本信息
- 安装python游戏图形框架pygame
- python求素数
- Python 安装pythoncom、pyHook
- win7 x64环境python2.7下装配sulley的注意点-对于Windows Installation原文的几点补充说明
- 轻松自动化---selenium-webdriver(python) (二)
- 轻松自动化---selenium-webdriver(python) (一)
- Python排序介绍
- Python sys.argv的用法
- Python 2.7 Data Type for Text Strings: Unicode and Str
- W32 python+selenium环境配置
- python入门
- 网络端口的转发和重定向(Python)
- Python标准库13 循环器 (itertools)