recursive managed deletion of files
Use this script if you want to delete recursively a directory which contains too much files for rm (in case rm takes too long and the load of your machine gets too high)
1 #!/usr/bin/env python
2 #
3 # Script to delete a directory recursively, taking care
4 # of the system load
5 #
6 # Soluciones Informaticas Codigo23 S.L.U. - http://codigo23.net
7
8 import sys, os, time, shutil
9
10 def check_sleep():
11 """
12 Check the load of the server, sleep for 60 seconds
13 if it higher than 3.5
14
15 FIXME: both the sleep time and the load value should
16 be parameters passed to the function (lazy!)
17 """
18
19 while os.getloadavg()[0] >= 3.5:
20 print ' ** Load too high (%s), going to sleep for 60 seconds' % os.getloadavg()[0]
21 time.sleep(60)
22 return True
23
24 def removedirs(parent, dirs):
25 """
26 Remove directories recursively, checking the load
27 after each removal.
28 """
29 for d in dirs:
30 print ' -- removing directory: ', d
31 shutil.rmtree(parent + '/' + d)
32 after_sleep = check_sleep()
33
34 if __name__ == '__main__':
35 """
36 Execute the script, first get a list of the
37 contents of the directory, then pass that list
38 to removedirs(), so the contents get deleted
39 properly.
40 """
41 if len(sys.argv) < 2:
42 print 'Usage: %s dir-to-delete' % (sys.argv[0])
43 sys.exit()
44
45 if not os.path.isdir(sys.argv[1]):
46 print '%s is not a directory' % (sys.argv[1])
47 sys.exit()
48
49 dirs = os.listdir(sys.argv[1])
50 print 'Directories: (%s)' % len(dirs)
51 print ' - deleting directories'
52 removedirs(sys.argv[1], dirs)
Pasted by Codigo23 on
mayo 04, 2010 at 01:05 |
Lang: python |
(52 lines of code)