ディスクスペースの使用状況を取得する

呼称: ファイルシステムのディスクサイズ取得
目的: df コマンドの特定の出力を取得したい
特徴: df コマンドへパスを渡すことで、そのパスを含むパーティションの情報が取得できる
用例: 大容量ファイルのインストールやコピー時の空きサイズチェック
備考: Unix 系 OS のみ使用可

#!/bin/env python

import os

def get_diskspace(dstpath, sizeopt='k'):
    if sizeopt != 'k' and sizeopt != 'm':
        sizeopt = 'k'

    if os.path.isdir(dstpath):
        pipe = os.popen("/bin/df -%s %s | /bin/sed -n 2p" % (sizeopt, dstpath), 'r')
        diskspace = pipe.read().split()
        pipe.close()
        return diskspace

    return None

if __name__ == '__main__':
    # get diskspace mounted "/usr/lib" using "megabytes"
    ds = get_diskspace("/usr/lib", 'm')
    print "FileSystem, blocks, Used, Available, Use%, Mounted on"
    print ds

    if ds:
        needed_size = 15000 # megabytes
        # check Available size
        if int(ds[3]) >= needed_size:
            print  "the system has enough diskspace :", ds[3]
        else:
            print  "the system has no diskspace :",  str(needed_size)

実行結果。

FileSystem, blocks, Used, Available, Use%, Mounted on
['/dev/sda1', '49596', '30530', '16507', '65%', '/']
the system has enough diskspace : 16507

2008/09/02 追記:
ファイルシステムに LVM を選択した場合、df コマンドの出力が2行で返されます。従って、sed コマンドへのアドレス指定を2〜3行と変更すれば良いです。また仮に3行目が存在しなくても正しく動作します。

pipe = os.popen("/bin/df -%s %s | /bin/sed -n 2,3p" % (sizeopt, dstpath), 'r')


リファレンス:
6.1.2 ファイルオブジェクトの生成