Python 输出格式

Python output format

当我在打印下面的信息时,它看起来真的很难看。 文字显示很长,看不懂

代码:

import psutil
print("Disk: ", psutil.disk_partitions())

我得到的输出是:

Disk:  [sdiskpart(device='C:\', mountpoint='C:\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\', mountpoint='D:\', fstype='', opts='cdrom'), sdiskpart(device='E:\', mountpoint='E:\', fstype='', opts='cdrom'), sdiskpart(device='F:\', mountpoint='F:\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='H:\', mountpoint='H:\', fstype='NTFS', opts='rw,removable')]

排长队!有没有办法过滤输出或将其显示在多行上?

谢谢你帮助我:)

psutil.disk_partitinos() 为您提供系统分区列表。

该列表中的每个元素都是 sdiskpart which is a namedtuple 的实例,具有以下属性:

['count', 'device', 'fstype', 'index', 'mountpoint', 'opts']

将必须处理此列表并使用str.format() and print()按照您想要的方式格式化和显示它。

请参考psutil文档。

在 "better way" 中显示 "disk information" 的简单函数可以像这样简单:

示例:

from psutil import disk_partitions


def diskinfo():
    for i, disk in enumerate(disk_partitions()):
        print "Disk #{0:d} {1:s}".format(i, disk.device)
        print " Mount Point: {0:s}".format(disk.mountpoint)
        print " File System: {0:s}".format(disk.fstype)
        print " Options: {0:s}".format(disk.opts)


diskinfo()

输出:

bash-4.3# python /app/foo.py
Disk #0 /dev/mapper/docker-8:1-2762733-bdb0f27645efd726d69c77d0cd856d6218da5783b2879d9a83a797f8b896b4be
 Mount Point: /
 File System: ext4
 Options: rw,relatime,discard,stripe=16,data=ordered

你可以这样做:

print("Disks:")
for disk in psutil.disk_partitions()):
    print(disk)

应该是这样的:

Disks:
sdiskpart(device='C:\', mountpoint='C:\', fstype='NTFS', opts='rw,fixed')
sdiskpart(device='D:\', mountpoint='D:\', fstype='', opts='cdrom')
sdiskpart(device='E:\', mountpoint='E:\', fstype='', opts='cdrom')
sdiskpart(device='F:\', mountpoint='F:\', fstype='NTFS', opts='rw,fixed')
sdiskpart(device='H:\', mountpoint='H:\', fstype='NTFS', opts='rw,removable')