python筆記--磁碟使用率

來源:互聯網
上載者:User

標籤:python擷取磁碟使用率   python磁碟使用率   

方法一:

使用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_BSIZEPreferred file system block size.statvfs.F_FRSIZEFundamental file system block size.statvfs.F_BLOCKSTotal number of blocks in the filesystem.statvfs.F_BFREETotal number of free blocks.statvfs.F_BAVAILFree blocks available to non-super user.statvfs.F_FILESTotal number of file nodes.statvfs.F_FFREETotal number of free file nodes.statvfs.F_FAVAILFree nodes available to non-super user.statvfs.F_FLAGFlags. System dependent: see statvfs() man page.statvfs.F_NAMEMAXMaximum 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/shm0

最後面一個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筆記--磁碟使用率

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.