ファイルの md5sum 値を取得する

呼称: ファイルの md5sum 値の取得
目的: md5sum 値の算出
特徴: ファイル操作の例外処理の方がやや煩雑(- -#
用例: ?
備考: ファイルは md5sum コマンドを使った方がてっとり早い?

#!/bin/env python

import md5

def get_md5sum(filename, buff=4096):
    def _open(filename):
        try:
            fd = open(filename, 'r')
        except IOError, e:
            print ("cannot open file : %s, %s" % (filename, e))
            return None
        return fd
    
    fd = _open(filename)
    if fd:
        m = md5.new()
        try:
            while True:
                data = fd.read(buff)
                if not data:
                    break
                m.update(data)
        except Exception, e:
            print ("cannot read file : %s, %s" % (filename, e))
         
        fd.close()
        return m.hexdigest()
    
    return None

if __name__ == '__main__':
    print get_md5sum(raw_input("Enter path2file : "))

実行結果。

Enter path2file : /etc/passwd
6a5388cfe23cc8bd0e5c8678cb8b7811

Enter path2file : /etc
cannot open file : /etc, [Errno 21] Is a directory
None

Enter path2file : /var/log/messages
cannot open file : /var/log/messages, [Errno 13] Permission denied: '/var/log/messages'
None

リファレンス:
15.2 md5 -- MD5 メッセージダイジェストアルゴリズム