python 获取硬盘信息_Python 获取磁盘信息

一,使用 subprocess + shell 命令实现

二,使用 Psutil 实现 (用python实现系统相关的命令行功能)

一,使用 subprocess + 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()

输出:

$ 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]:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值