Python Forum
Looping Through Linux Filesystems
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping Through Linux Filesystems
#1
Hello,

I'm new to Python and using 3.6 for this code. I wrote the code below to report on a Linux filesystem called '/u01'. What I'd like to do is loop through the absolute filesystems and print out the size, free space, etc for each of the filesystems such as '/','/backup','/var', etc.

Here is my current piece of code:
import subprocess
import os, sys
from collections import namedtuple

def get_path_usage(path):
	
	space_st = os.statvfs(path)

	# f_bavail: without blocks reserved for super users
	# f_bfree: with blocks reserved for super users

	avail = space_st.f_frsize * space_st.f_bavail

	capa = space_st.f_frsize * space_st.f_blocks
	used = round((capa - avail) / 1024 / 1024)
	percent = float(used) / capa

	# print using str.format(python 3) method for variables
	print ("Path: {}".format(path))
	print ("Total: {}".format(capa))
	print ("Used: {}".format(used))
	print ("Available: {}".format(avail))
	print ("Percent: {}".format(percent))

x = get_path_usage('/u01')
print (x)
I'd like to know how to add another function to loop through directories, or even add the directories to a list, to report on their size. I've been looking around for a while and decided to ask the experts with this post.

Appreciate the help!

Frank
Reply
#2
you need to walk the directories, see os.walk: https://docs.python.org/2/library/os.html
Reply
#3
I went with a list of two filesystems I would like to use but this isn't really what I'm looking for. The os.walk function returns a list of all files and directories, not what's in /etc/fstab (unless i'm missing something).

I added a list with '/u01' and '/backup', but would also like to look at the filesystems displayed when you enter the 'df -h' command in Linux.
Reply
#4
Wouldn't shutil.disk_usage() suits your needs?
Reply
#5
There is one file system in Linux. What you are talking about is mounted points. You can't read a disk partition before mount it. Actual reading not with tools like dd for example.

fstab is a file and you have to open it in order to read its content.

See psutil module.

An example:
import psutil

devs = psutil.disk_partitions()

for dev in devs:
    print(dev.device, psutil.disk_usage(dev.mountpoint).percent, dev.mountpoint)
Output:
/dev/sda7 96.1 / /dev/sda8 96.2 /home /dev/sda5 99.2 /media/storage /dev/sda7 96.1 /var/lib/docker/btrfs
As you can see I have more partitions but they are not mounted.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
Yep, you're right. I needed the mount points not filesystems.

Thanks a bunch for the code, that's what I was looking for!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020