簡體   English   中英

使用python3.x在Linux中查看分區

[英]view partitions in Linux using python3.x

最近,我剛剛開始使用python3,並且意識到python2.6進行了很多更改。 我想知道是否有使用fdisk格式化Linux系統中可用硬盤視圖的方式? 在python2.6中,它的工作原理如下:

def parse_fdisk(fdisk_output):
    result = {}
    for line in fdisk_output.split("\n"):
        if not line.startswith("/"): continue
        parts = line.split()

        inf = {}
        if parts[1] == "*":
            inf['bootable'] = True
            del parts[1]

        else:
            inf['bootable'] = False

        inf['start'] = int(parts[1])
        inf['end'] = int(parts[2])
        inf['blocks'] = int(parts[3].rstrip("+"))
        inf['partition_id'] = int(parts[4], 16)
        inf['partition_id_string'] = " ".join(parts[5:])

        result[parts[0]] = inf
    return result

def main():
    fdisk_output = commands.getoutput("fdisk -l")
    for disk, info in parse_fdisk(fdisk_output).items():
        print disk, " ".join(["%s=%r" % i for i in info.items()])

看一下psutil包。

psutil是一個模塊,提供了一個接口,該接口通過使用Python以可移植的方式檢索所有正在運行的進程和系統利用率(CPU,磁盤,內存)的信息,實現了命令行工具提供的許多功能,例如:ps,top,df,kill ,免費,lsof,netstat,ifconfig,nice,ionice,iostat,iotop,正常運行時間,tty。

從他們的自述文件

當前,它通過使用單個代碼庫即可支持32位64位的 LinuxWindowsOSXFreeBSD以及Python的2.43.3版本。

磁盤示例:

>>> psutil.disk_partitions()
[partition(device='/dev/sda1', mountpoint='/', fstype='ext4'),
 partition(device='/dev/sda2', mountpoint='/home', fstype='ext4')]
>>>
>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
>>>
>>> psutil.disk_io_counters()
iostat(read_count=719566, write_count=1082197, read_bytes=18626220032, 
       write_bytes=24081764352, read_time=5023392, write_time=63199568)

據我所知,尚不支持分區詳細信息(例如可啟動標志)。

commands模塊已從Python3中刪除。 您可以改為使用subprocess模塊:

import subprocess
import shlex
import sys

def parse_fdisk(fdisk_output):
    result = {}
    for line in fdisk_output.split("\n"):
        if not line.startswith("/"): continue
        parts = line.split()

        inf = {}
        if parts[1] == "*":
            inf['bootable'] = True
            del parts[1]

        else:
            inf['bootable'] = False

        inf['start'] = int(parts[1])
        inf['end'] = int(parts[2])
        inf['blocks'] = int(parts[3].rstrip("+"))
        inf['partition_id'] = int(parts[4], 16)
        inf['partition_id_string'] = " ".join(parts[5:])

        result[parts[0]] = inf
    return result

def main():
    proc = subprocess.Popen(shlex.split("fdisk -l"),
                            stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    fdisk_output, fdisk_error = proc.communicate()
    fdisk_output = fdisk_output.decode(sys.stdout.encoding)
    for disk, info in parse_fdisk(fdisk_output).items():
        print(disk, " ".join(["%s=%r" % i for i in info.items()]))

main()

parse_fdisk函數parse_fdisk任何更改。 唯一需要更改的是main()commands.getoutput的調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM