Python

Finally, the same thing in Python. This function is a bit more involved than the other examples because it takes advantage of Python’s dynamic typing. You can pass it a string or any object with a read attribute. Note that this function relies on the path.py module, though you can remove that dependency pretty easily.

importhashlib,base64frompathimportpathdefcalc_sha(obj):"""Calculates the base64-encoded SHA hash of a file."""try:pathfile=path(obj)exceptUnicodeDecodeError:pathfile=Nonesha=hashlib.sha256()ifpathfileandpathfile.exists():returnbase64.b64encode(pathfile.read_hash('SHA256'))elifisinstance(obj,basestring):sha.update(obj)elifhasattr(obj,'read'):whileTrue:d=obj.read(8192)ifnotd:breaksha.update(d)else:returnNoner=sha.digest()r=base64.b64encode(r)returnr

This particular implementation can also be found in my propane utility library (in the filetools module).