为了方便在Windows环境计算文件MD5值。
使用Python完成一个脚本,实现md5sum功能。
代码:
import os import sys import hashlib def md5sum(file): if not os.path.exists(file): return "md5sum: {}: No such file or directory".format(file) elif os.path.isdir(file): return "md5sum: {}: Is a directory".format(file) elif os.path.isfile(file): with open(file, 'rb') as fd: data = fd.read() return "{} {}".format(hashlib.md5(data).hexdigest(), file) else: return "md5sum: {}: Unexpected error".format(file) if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: md5sum.py filename") sys.exit() file_name = sys.argv[1] if file_name.endswith("*"): if file_name == "*": file_path = os.path.dirname(os.path.realpath(__file__)) else: file_path = file_name[:-1] if os.path.exists(file_path): files = os.listdir(file_path) for f in files: print(md5sum(os.path.join(file_path, f))) else: print("md5sum: {}: No such file or directory".format(file_path)) else: print(md5sum(file_name))
运行截图: