md5.py with syntax coloring

This HTML file was generated with Kalle's syntaxcolor.py


   1"""
   2Calculates the MD5 hash of a string or a file.
   3By Kalle (http://qalle.net)
   4"""
   5
   6import sys
   7import os.path
   8import hashlib
   9
  10FILE_BUFFER_SIZE = 2 ** 20
  11
  12HELP_TEXT = """\
  13Calculates the MD5 hash of a string or a file.
  14Arguments: InputType Input
  15If InputType is "s" or "S", Input is a string (only 7-bit ASCII is allowed).
  16If InputType is "f" or "F", Input is a filename.\
  17"""
  18
  19def hash_string(str_):
  20    try:
  21        bytes_ = str_.encode("ascii")
  22    except UnicodeEncodeError:
  23        exit("Only 7-bit ASCII characters are allowed.")
  24
  25    return hashlib.md5(bytes_).hexdigest()
  26
  27def hash_file(hnd):
  28    hash = hashlib.md5()
  29
  30    bytesLeft = hnd.seek(0, 2)
  31    hnd.seek(0)
  32
  33    while bytesLeft > 0:
  34        chunkSize = min(FILE_BUFFER_SIZE, bytesLeft)
  35        hash.update(hnd.read(chunkSize))
  36        bytesLeft -= chunkSize
  37
  38    return hash.hexdigest()
  39
  40def main():
  41    if len(sys.argv) != 3:
  42        exit(HELP_TEXT)
  43
  44    (inputType, input_) = sys.argv[1:]
  45    inputType = inputType.upper()
  46
  47    if inputType == "S":
  48        # string
  49
  50        print(hash_string(input_))
  51
  52    elif inputType == "F":
  53        # file
  54
  55        try:
  56            with open(input_, "rb") as hnd:
  57                print(hash_file(hnd))
  58        except FileNotFoundError:
  59            exit("File not found.")
  60        except PermissionError:
  61            exit("Permission denied.")
  62        except OSError:
  63            exit("Error reading source file.")
  64
  65    else:
  66        exit(HELP_TEXT)
  67
  68if __name__ == "__main__":
  69    main()