Commit 19219b54 authored by Cristiano Urban's avatar Cristiano Urban
Browse files

Added 'getSize()' and 'getFileSystemSize()' methods.

parent 8a2f1c93
Loading
Loading
Loading
Loading
+37 −2
Original line number Diff line number Diff line
#!/usr/bin/env python

import os
import shutil
import sys


@@ -20,8 +21,8 @@ class SystemUtils(object):

    def userInfo(self, username):
        """
        Parses '/etc/passwd' and get returns user, uid and gid associated to
        a username.
        Parses '/etc/passwd' and returns user, uid and gid associated to
        a given username.
        """
        fp = open("/etc/passwd", 'r')
        for line in fp:
@@ -68,6 +69,36 @@ class SystemUtils(object):
                sys.exit("FATAL: invalid file/dir.")
        return [ dirList, fileList ]
    
    def getSize(self, path):
        """
        If 'path' is a file returns the file size in bytes,
        if 'path' is a directory it returns the total size of the dir,
        in all the other cases it returns -1
        """
        size = 0
        if os.path.isfile(path):
            size = os.path.getsize(path)    
        elif os.path.isdir(path):            
            for folder, subfolders, files in os.walk(path, topdown = True):
                cwd = os.path.basename(folder)
                parent = os.path.dirname(folder)
                size += os.path.getsize(folder)
                for file in files:
                    size += os.path.getsize(parent + '/' + cwd + '/' + file)
        else:
            size = -1
        return size

    def getFileSystemSize(self, path):
        """
        Returns a named tuple with usage statistcs in the format
        (total, used, free):
        - total: total space available in bytes
        - used: used space in bytes
        - free: free space in bytes
        """
        return shutil.disk_usage(path)

    def convertSizeToBytes(self, sizeStr):
        size = int(sizeStr.split()[0])
        unit = sizeStr.split()[1]
@@ -82,3 +113,7 @@ class SystemUtils(object):
#info = sysUtils.userInfo("cristiano")
#print(sysUtils.convertSizeInBytes(" 10  MB  "))
#print(info)
#size = sysUtils.getSize("/home/cristiano/EDC/Books/")
#print(f"size: {size / (2**20)}")
#[total, used, free] = sysUtils.getFileSystemSize("/")
#print(f"total: {total}, used: {used}, free: {free}")