Difference between revisions of "ProvaPratica 2013.07.18"

From Sistemi Operativi
Jump to navigation Jump to search
Line 67: Line 67:
 
collectfiles(C,arg2)
 
collectfiles(C,arg2)
 
elif os.path.isfile('{0}'.format(C)):
 
elif os.path.isfile('{0}'.format(C)):
os.symlink('{0}'.format(C), '{0}/{1}'.format(arg2,B))
+
try:
 +
os.symlink('{0}'.format(C), '{0}/{1}'.format(arg2,B))
 +
except OSError:
 +
i=1
 +
while True:
 +
try:
 +
os.symlink('{0}'.format(C), '{0}/{1}{2}'.format(arg2,B,i))
 +
break
 +
except OSError:
 +
i=i+1
  
 
try:
 
try:
 
collectfiles(str(sys.argv[1]),str(sys.argv[2]))
 
collectfiles(str(sys.argv[1]),str(sys.argv[2]))
 
except OSError:
 
except OSError:
print("Invalid Directory!")
+
print("Invalid Directory!")
 
</syntaxhighlight>
 
</syntaxhighlight>
 
-Fede
 
-Fede

Revision as of 09:12, 22 November 2013

[Python 3]

'''
Prova Pratica di Laboratorio di Sistemi Operativi
18 luglio 2013
Esercizio 3

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

@author: Tommaso Ognibene
'''

import os, sys

def Main(argv):
    # Check number of arguments
    if len(argv) != 3:
        print("The function requires two arguments to be passed in.")
        return
    
    # Check parameters
    srcDir = str(argv[1])
    dstDir = str(argv[2])
    if not os.path.isdir(srcDir):
        print("First argument should be an existing directory.")
        return
    if not os.path.isdir(dstDir):
        print("Second argument should be an existing directory.")
        return
    
    # Build a dictionary with key-value pair {file base name - occurrences}
    nameFreq = { }
    for dirPath, dirNames, fileNames in os.walk(srcDir):
        for fileName in fileNames:
            fileBaseName, _ = os.path.splitext(fileName)
            nameFreq[fileBaseName] = nameFreq.get(fileBaseName, -1) + 1
            
            # Create a soft link
            freq = nameFreq[fileBaseName]
            linkName = "{0}{1}".format(fileBaseName, str(freq) if freq > 0 else "")
            srcPath = os.path.join(os.path.abspath(dirPath), fileName)
            dstPath = os.path.join(dstDir, linkName)
            if not os.path.lexists(dstPath):
                os.symlink(srcPath, dstPath)
        
    print("Done!")

if __name__ == "__main__":
    sys.exit(Main(sys.argv))



Questa è la mia versione

import os, sys

def collectfiles(arg1,arg2): #li si passa vuota è una lista vuota
	fcd = os.listdir('{0}'.format(arg1))
	while fcd != []:
		B=str(fcd.pop())
		C='{0}/{1}'.format(arg1,B)
		if os.path.isdir('{0}'.format(C)):
			collectfiles(C,arg2)
		elif os.path.isfile('{0}'.format(C)):
			try:
				os.symlink('{0}'.format(C), '{0}/{1}'.format(arg2,B))
			except OSError:
				i=1
				while True:
					try:
						os.symlink('{0}'.format(C), '{0}/{1}{2}'.format(arg2,B,i))
						break
					except OSError:
						i=i+1

try:
	collectfiles(str(sys.argv[1]),str(sys.argv[2]))
except OSError:
		print("Invalid Directory!")

-Fede