溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中如何獲取文件系統(tǒng)的使用率

發(fā)布時間:2021-07-29 14:45:30 來源:億速云 閱讀:192 作者:Leah 欄目:編程語言

Python中如何獲取文件系統(tǒng)的使用率,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

from subprocess import Popen, PIPE

# 執(zhí)行操作系統(tǒng)命令并返回執(zhí)行結果

def exec_shell(shell_cmd):
    process = Popen(shell_cmd, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = process.communicate()
    return stdout, stderr

# 獲取磁盤使用率

# 參數(shù) target_path: 待檢測掛載點,如果指定了該參數(shù)則只檢測該掛載點,否則檢測所有本地文件系統(tǒng)

def get_disk_space_usage(target_path=''):
    data = []
    cmd = 'df -lm' # Local FileSystem only
    if target_path.strip() != '':
        if os.path.exists(target_path):
            cmd = 'df -m '+target_path.strip()
    res = exec_shell(cmd)[0]
    res_lines = res.split(os.linesep)
    del res_lines[0] # delete line header
    for line in res_lines:
        if '%' in line:
            line_tmp = re.split( r'\s+|\t', line.strip() )
            if '%' in line_tmp[-2] and '/' in line_tmp[-1]:
                line_data = {}
                line_data['total_mb'] = int( line_tmp[-5].strip() )
                line_data['used_mb'] = int( line_tmp[-4].strip() )
                line_data['free_mb'] = int( line_tmp[-3].strip() )
                line_data['used_pct'] = int( line_tmp[-2].strip().strip('%') )
                line_data['free_pct'] = 100 - line_data['used_pct']
                line_data['mount_point'] = line_tmp[-1].strip()
                data.append(line_data)
    return data

# 調用函數(shù)
res = get_disk_space_usage()

關于Python中如何獲取文件系統(tǒng)的使用率問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI