Improved some error messages for command line processing.
[python/dscho.git] / Tools / scripts / byteyears.py
blobbada5a538abbd5d095f362e2e986d49707ba3249
1 #! /usr/bin/env python
3 # Print the product of age and size of each file, in suitable units.
5 # Usage: byteyears [ -a | -m | -c ] file ...
7 # Options -[amc] select atime, mtime (default) or ctime as age.
9 import sys, os, time
10 import string
11 from stat import *
13 # Use lstat() to stat files if it exists, else stat()
14 try:
15 statfunc = os.lstat
16 except AttributeError:
17 statfunc = os.stat
19 # Parse options
20 if sys.argv[1] == '-m':
21 itime = ST_MTIME
22 del sys.argv[1]
23 elif sys.argv[1] == '-c':
24 itime = ST_CTIME
25 del sys.argv[1]
26 elif sys.argv[1] == '-a':
27 itime = ST_CTIME
28 del sys.argv[1]
29 else:
30 itime = ST_MTIME
32 secs_per_year = 365.0 * 24.0 * 3600.0 # Scale factor
33 now = time.time() # Current time, for age computations
34 status = 0 # Exit status, set to 1 on errors
36 # Compute max file name length
37 maxlen = 1
38 for file in sys.argv[1:]:
39 if len(file) > maxlen: maxlen = len(file)
41 # Process each argument in turn
42 for file in sys.argv[1:]:
43 try:
44 st = statfunc(file)
45 except os.error, msg:
46 sys.stderr.write('can\'t stat ' + `file` + ': ' + `msg` + '\n')
47 status = 1
48 st = ()
49 if st:
50 anytime = st[itime]
51 size = st[ST_SIZE]
52 age = now - anytime
53 byteyears = float(size) * float(age) / secs_per_year
54 print string.ljust(file, maxlen),
55 print string.rjust(`int(byteyears)`, 8)
57 sys.exit(status)