一,使用 subprocess + shell 命令實現node
二,使用 Psutil 實現 (用python實現系統相關的命令行功能)python
一,使用 subprocess + shell 命令實現shell
# -*- coding=utf-8 -*- # Created Time: 2016年12月16日 星期五 16時53分27秒 # File Name: 02_os_disk_info.py """ 獲取磁盤信息 """ import subprocess def get_one(path): # 指定單位 -BK -BM -BG df = subprocess.Popen(['df', '-BG', path], stdout=subprocess.PIPE) output = df.communicate()[0] print output device, size, used, available, percent, mountpoint = \ output.split('\n')[1].split() print 'device: ', device print 'seize: ', size print 'used: ', used print 'available: ', available print 'percent: ', percent print 'mountpoint: ', mountpoint print '########################' def get_all(): # 指定單位 -BK -BM -BG df = subprocess.Popen(['df', '-BG'], stdout=subprocess.PIPE) output = df.communicate()[0] print output for i in xrange(30): try: device, size, used, available, percent, mountpoint = \ output.split('\n')[i+1].split() print '########################' print 'device: ', device print 'seize: ', size print 'used: ', used print 'available: ', available print 'percent: ', percent print 'mountpoint: ', mountpoint except: break def main(): path = '/dev/sda1' get_one(path) get_all() if __name__ == '__main__': main()
輸出:ui
$ python 02_os_disk_info.py Filesystem 1G-blocks Used Available Use% Mounted on /dev/sda1 902G 38G 819G 5% / device: /dev/sda1 seize: 902G used: 38G available: 819G percent: 5% mountpoint: / ######################## df: /run/user/1000/gvfs: Transport endpoint is not connected Filesystem 1G-blocks Used Available Use% Mounted on udev 8G 1G 8G 1% /dev tmpfs 2G 1G 2G 1% /run /dev/sda1 902G 38G 819G 5% / none 1G 0G 1G 0% /sys/fs/cgroup none 1G 0G 1G 0% /run/lock none 8G 1G 8G 3% /run/shm none 1G 1G 1G 1% /run/user ######################## device: udev seize: 8G used: 1G available: 8G percent: 1% mountpoint: /dev ######################## device: tmpfs seize: 2G used: 1G available: 2G percent: 1% mountpoint: /run ######################## .. ..
二,使用 Psutil 實現命令行
In [1]: import psutil In [2]: partitions = psutil.disk_partitions() In [3]: partitions Out[3]: [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro,data=ordered'), sdiskpart(device='/dev/sdb4', mountpoint='/media/bwhite/\\xc7\xd7\xb0\\xae\\xb5\\xc4-B4FE-5315', fstype='vfat', opts='rw,nosuid,nodev,noexec,relatime,uid=1000,fmask=0022,dmask=0022,codepage=936,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro')] In [4]: foo = psutil.disk_usage(partitions[1].mountpoint) In [5]: foo Out[5]: sdiskusage(total=4015390720, used=1512292352, free=2503098368, percent=37.7) In [6]: