Prints the SHA-256 checksum of a file. Use it to verify a download, compare two files for equality, or fingerprint a build artifact.
#!/usr/bin/env python3
"""Print the SHA-256 checksum of a file."""
import hashlib
import sys
def hash_file(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: hash-file.py <path>")
try:
print(hash_file(sys.argv[1]))
except OSError as e:
sys.exit(f"error: {e}")
| path | string — positional argument, path to a local file to hash, e.g. build/app.tar.gz |
|---|
error: ... message on stderr if the file can't be read.
$ python3 hash-file.py build/app.tar.gz
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08