Python中如何獲取文件系統(tǒng)的使用率,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
from subprocess import Popen, PIPE
# 執(zhí)行操作系統(tǒng)命令并返回執(zhí)行結(jié)果
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
# 調(diào)用函數(shù)
res = get_disk_space_usage()
關(guān)于Python中如何獲取文件系統(tǒng)的使用率問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道了解更多相關(guān)知識。