# HG changeset patch # User Edho Prima Arief # Date 1310579373 -25200 # Node ID 9790bc126ea6d23777242cb7d700eb4788c09b71 # Parent 4f954c1e2fdcf1d12261fd0485b5de6e797f8373 Epic simplified error handling in true try/except/finally spirit. diff -r 4f954c1e2fdc -r 9790bc126ea6 bin/recompress --- a/bin/recompress Thu Jul 14 00:39:09 2011 +0700 +++ b/bin/recompress Thu Jul 14 00:49:33 2011 +0700 @@ -10,13 +10,11 @@ # 2 = error saving file (no write permission) # 3 = not a png file def repng(filename): - retcode = 0 im = Image.open(filename) if im.format == "PNG": - im.save(filename, optimize=1) + im.save(filename, "PNG", optimize=1) else: - retcode = 1 - return retcode + raise Exception("Not a PNG image file") def hbytes(inbyte): units = ["B", "kB", "MB", "GB", "TB", "PB"] @@ -33,15 +31,14 @@ sys.stdout.flush() try: byte_orig = os.path.getsize(filename) - re = repng(filename) - if re == 0: - byte_new = os.path.getsize(filename) - print "OK (%s => %s, %.2f%% saving)" % (hbytes(byte_orig), hbytes(byte_new), (byte_orig - byte_new)*100/float(byte_orig)), - elif re == 1: - print "Not a PNG image file", + repng(filename) + byte_new = os.path.getsize(filename) + print "OK (%s => %s, %.2f%% saving)" % (hbytes(byte_orig), hbytes(byte_new), (byte_orig - byte_new)*100/float(byte_orig)), + re = 0 except: print "Failed", print "(%s: %s)" % (sys.exc_type, sys.exc_value), re = 1 - print "[%s]" % re + finally: + print "[%s]" % re