Using: Python 3.7.6 , OS Linux (rmp)
I need to extract total and free sizes of disks and partitions in Python.
I tried different Python functions to retrieve block size in bytes (the results were the same). Then I compared to results of Linux commands (also in bytes), results were different (Linux commands different than Python).
Python functions:
- Using os.statvfs
import os statvfs = os.statvfs('/dev/sda') statvfs.f_frsize *statvfs.f_blocks statvfs.f_frsize * statvfs.f_bfree Results: size of /dev/sda is 1973968896 size of /dev/sda1 is 1973968896 (the same??!)
- Using shutil.disk_usage :
print(shutil.disk_usage('/dev/sda')) usage(total=1973968896, used=0, free=1973968896) print(shutil.disk_usage('/dev/sda1') ) usage(total=1973968896, used=0, free=1973968896)
I tried also psutil:
import psutil print(psutil.disk_usage('/dev/sda')) print(psutil.disk_usage('/dev/sda1')) same results as 1. and 2.
Linux command:
- blockdev –getsize64 #Print device size in bytes
blockdev --getsize64 /dev/sda 8001563222016 blockdev --getsize64 /dev/sda1 80014737408
- lsblk -b
What do I miss here ? Why Python results are different than Linux command (while all units in bytes)? Why Python sizes of sda and sda1 are the same ?
Advertisement
Answer
Both https://docs.python.org/3/library/shutil.html#shutil.disk_usage and https://docs.python.org/3/library/os.html#os.statvfs are used to get stats on filesystem and not a block device, so when you are using /dev/sda
or /dev/sda1
as argument – you are actually getting info about /dev
You can get similar results with stat
command, here is example with my /dev/sdb
.
In python:
print(shutil.disk_usage('/dev/sdb')) usage(total=8324083712, used=0, free=8324083712) print(shutil.disk_usage('/dev')) usage(total=8324083712, used=0, free=8324083712)
In shell:
LANG=C stat -f /dev/sdb File: "/dev/sdb" ID: 0 Namelen: 255 Type: tmpfs Block size: 4096 Fundamental block size: 4096 Blocks: Total: 2032247 Free: 2032247 Available: 2032247 Inodes: Total: 2032247 Free: 2031625 LANG=C stat -f /dev/ File: "/dev/" ID: 0 Namelen: 255 Type: tmpfs Block size: 4096 Fundamental block size: 4096 Blocks: Total: 2032247 Free: 2032247 Available: 2032247 Inodes: Total: 2032247 Free: 2031625 echo $(( 2032247 * 4096 )) 8324083712
You can see that shutil output and block size * blocks total are exactly the same.
Notice the -f flag:
-f, --file-system display file system status instead of file status