2015-05-22 76 views
0

当我打印下列信息时它看起来非常难看。 文本显示非常长,您无法真正阅读它。Python输出格式

代码:

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')] 

在一个长行!有没有办法来过滤输出或在多行显示它?

谢谢你帮助我:)

+7

[pprint(https://docs.python.org/3/library/pprint.html)是你的朋友。 – miku

回答

1

psutil.disk_partitinos()给你的分区上您systme列表。

在该列表中的每个元素是sdiskpart实例,它是一个namedtuple具有以下属性:

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

将不得不进程列表和格式,并显示它您使用方式str.format()print()

请参阅psutil文档。

一个简单的函数,在一个 “更好的方法” 显示 “盘信息” 可以是作为简单的东西:

实施例:

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 
1

你可以这样做:

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') 
+0

感谢您的帮助! – tartaarsap