Use python to get information about a computer's disk

  • 2021-01-19 22:18:38
  • OfStack

Using Python to access the computer's disk information requires a third party module, psutil. This module needs to be installed by itself. This function is not available under pure CPython.

Demonstrate the following in the iPython interactive interface:

To view your computer's disk partitions:


In [1]: import psutil
In [2]: psutil.disk_partitions()
Out[2]: [sdiskpart(device='/dev/disk2', mountpoint='/', fstype='hfs', opts='rw,local,rootfs,dovolfs,journaled,multilabel')]
In [3]: len(psutil.disk_partitions())
Out[3]: 1

As can be seen from the above results, the computer only has 1 partition. In view of the final result, we confirm 1 by judging the number of elements in the dictionary.

To view your computer's disk usage percentage:


In [4]: psutil.disk_usage('/')
Out[4]: sdiskusage(total=1114478608384, used=305497878528, free=808718585856, percent=27.4)

Relatively well, the new computer hasn't been used very long, and the hard disk hasn't filled up yet. The total was about 27.4 percent.

To view the IO count on the computer disk:


In [5]: psutil.disk_io_counters()
Out[5]: sdiskio(read_count=112237L, write_count=99750L, read_bytes=5243863040L, write_bytes=7047483392L, read_time=80568L, write_time=138699L)

In [7]: psutil.disk_io_counters(perdisk=True)
Out[7]: 
{'disk0': sdiskio(read_count=103533L, write_count=86260L, read_bytes=5120090624L, write_bytes=4813373440L, read_time=29774L, write_time=27654L),
 'disk1': sdiskio(read_count=8740L, write_count=13723L, read_bytes=124141056L, write_bytes=2237206528L, read_time=50840L, write_time=111871L)}

The above two methods are used respectively. The first method is to get the total IO information of the disk, and the second method is to view the disk information of the computer partition. As a result, information is not counted by logical partitions, but by physical disks. I happen to have two disks on my computer, one mechanical hard drive and one solid state drive, which is actually what the physical disk count is based on.


Related articles: