Difference between revisions of "ProvaPratica 2013.05.29"

From Sistemi Operativi
Jump to navigation Jump to search
Line 121: Line 121:
 
 
  
res = listsubstr(sys.argv[1])
+
try:
a=list(res.keys())
+
res = listsubstr(sys.argv[1])
while a != []:
+
a=list(res.keys())
b = a.pop()
+
while a != []:
print('{0}:\t{1}'.format(b,res[b]))
+
b = a.pop()
 +
print('{0}:\t{1}'.format(b,res[b]))
 +
except OSError:
 +
print("Could not solve path")
  
 
</syntaxhighlight>
 
</syntaxhighlight>
 
-fede
 
-fede

Revision as of 11:22, 22 November 2013

[Python 3]

'''
Prova Pratica di Laboratorio di Sistemi Operativi
29 maggio 2013
Esercizio 3

URL: http://www.cs.unibo.it/~renzo/so/pratiche/2013.05.29.pdf

@author: Tommaso Ognibene
'''

import os, sys

def Main(argv):
    # Check number of arguments
    if len(argv) != 2:
        print("The function requires one argument to be passed in.")
        return
    
    # Check parameters
    topDir = str(sys.argv[1])
    if not os.path.isdir(topDir):
        print("The parameter should be an existing directory.")
        return
    
    # Build a dictionary with key-value pair {file extension - total size}
    extensionSize = { }
    GetSize(topDir, extensionSize)
    
    # Print results
    PrintResults(extensionSize)

def GetSize(topDir, extensionSize):
    for dirPath, dirNames, files in os.walk(topDir):
        for file in files:
            # 'example.mp3' -> ['example', 'mp3']
            # 'example.tar.gz' -> ['example', 'tar', 'gz']
            parts = file.split('.')
            # ['example', 'mp3'] -> ['mp3']
            # ['example', 'tar', 'gz'] -> ['tar', 'gz']
            parts = parts[1:]
            # ['mp3'] -> '.mp3'
            # ['tar', 'gz'] -> '.tar.gz'
            fileExtension = ".{0}".format(".".join(str(part) for part in parts))
            
            # Compute the size in Bytes and update the dictionary
            filePath = os.path.join(dirPath, file)   
            fileSize = os.path.getsize(filePath)
            extensionSize[fileExtension] = extensionSize.get(fileExtension, 0) + fileSize

# Print results
def PrintResults(extensionSize):
    for key, value in sorted(extensionSize.items()):
        print('{0}: {1} Bytes.'.format(key, value))
        
if __name__ == "__main__":
    sys.exit(Main(sys.argv))

mia versione

import os, sys, copy

def dotsubstr(a):#restituisce la sottostringa .suffisso
	#fcd = os.listdir('{0}'.format(arg1))
	i=0
	try:
		while a[i]!='.':
			i=i+1
		return a[i:]
	except IndexError:
		return -1

def compliarg(li,arg):#restituisce una lista di tutti gli elementi contenenti la sottostringa arg come suffisso
	res=[]
	while li != []:
		a=li.pop()
		if a.endswith(arg): res.append(a)
	return res

def listremintsect(l2,l1):#restituisce una lista res = l1 - intersezione di l1 ed l2
	res=[]
	while l1 != []:
		a=l1.pop()
		if not a in l2: res.append(a)
	return res

def createpathlist(c,path):#restituisce una lista di file c con relativo path.
	res = []
	while c != []:
		res.append('{0}/{1}'.format(path,c.pop()))
	return res

def totsizes(d): #data una lista d di path restituisce la somma di tutti i size di d
	res = 0
	while d != []:
		res = res + os.path.getsize('{0}'.format(d.pop()))
	return res

def listsubstr(arg): #ritorna un dizionario del tipo diz[str(suffisso)] = int(size relativo al suffisso)
	res = {}
	fcd = os.listdir('{0}'.format(arg))
	while fcd != []:
		fcdtmp=copy.deepcopy(fcd) #BUGGONE SENZA COPY!!!!!!
		a = fcd.pop()
		b = dotsubstr(a)
		if b == -1: continue
		else: pass
		c = compliarg(fcdtmp,b)
		s=copy.deepcopy(c) #!!!!!!!!!!!!!!!!!!!!!!!!!
		d = createpathlist(c,arg)
		res[b] = totsizes(d)

		fcd = listremintsect(s,fcd)

	return res
		

try:
	res = listsubstr(sys.argv[1])
	a=list(res.keys())
	while a != []:
		b = a.pop()
		print('{0}:\t{1}'.format(b,res[b]))
except OSError:
	print("Could not solve path")

-fede