Mercurial > ec-dotfiles
comparison bin/recompress @ 94:9790bc126ea6
Epic simplified error handling in true try/except/finally spirit.
author | Edho Prima Arief <edho@myconan.net> |
---|---|
date | Thu, 14 Jul 2011 00:49:33 +0700 |
parents | 4f954c1e2fdc |
children | a5324d2cc0eb |
comparison
equal
deleted
inserted
replaced
93:4f954c1e2fdc | 94:9790bc126ea6 |
---|---|
8 # 0 = ok | 8 # 0 = ok |
9 # 1 = error opening file (not an image, not a file, unreadable or whatever) | 9 # 1 = error opening file (not an image, not a file, unreadable or whatever) |
10 # 2 = error saving file (no write permission) | 10 # 2 = error saving file (no write permission) |
11 # 3 = not a png file | 11 # 3 = not a png file |
12 def repng(filename): | 12 def repng(filename): |
13 retcode = 0 | |
14 im = Image.open(filename) | 13 im = Image.open(filename) |
15 if im.format == "PNG": | 14 if im.format == "PNG": |
16 im.save(filename, optimize=1) | 15 im.save(filename, "PNG", optimize=1) |
17 else: | 16 else: |
18 retcode = 1 | 17 raise Exception("Not a PNG image file") |
19 return retcode | |
20 | 18 |
21 def hbytes(inbyte): | 19 def hbytes(inbyte): |
22 units = ["B", "kB", "MB", "GB", "TB", "PB"] | 20 units = ["B", "kB", "MB", "GB", "TB", "PB"] |
23 outbyte = float(inbyte) | 21 outbyte = float(inbyte) |
24 current_unit = 0 | 22 current_unit = 0 |
31 for filename in sys.argv[1:]: | 29 for filename in sys.argv[1:]: |
32 print "Recompressing %s:" % filename, | 30 print "Recompressing %s:" % filename, |
33 sys.stdout.flush() | 31 sys.stdout.flush() |
34 try: | 32 try: |
35 byte_orig = os.path.getsize(filename) | 33 byte_orig = os.path.getsize(filename) |
36 re = repng(filename) | 34 repng(filename) |
37 if re == 0: | 35 byte_new = os.path.getsize(filename) |
38 byte_new = os.path.getsize(filename) | 36 print "OK (%s => %s, %.2f%% saving)" % (hbytes(byte_orig), hbytes(byte_new), (byte_orig - byte_new)*100/float(byte_orig)), |
39 print "OK (%s => %s, %.2f%% saving)" % (hbytes(byte_orig), hbytes(byte_new), (byte_orig - byte_new)*100/float(byte_orig)), | 37 re = 0 |
40 elif re == 1: | |
41 print "Not a PNG image file", | |
42 except: | 38 except: |
43 print "Failed", | 39 print "Failed", |
44 print "(%s: %s)" % (sys.exc_type, sys.exc_value), | 40 print "(%s: %s)" % (sys.exc_type, sys.exc_value), |
45 re = 1 | 41 re = 1 |
46 print "[%s]" % re | 42 finally: |
43 print "[%s]" % re | |
47 | 44 |