]> gitweb.pimeys.fr Git - scripts-20-100.git/blob - md5sum.py
doublon moins bien commenté
[scripts-20-100.git] / md5sum.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3
4 ## trouvé sur http://code.activestate.com/recipes/266486/
5
6 ## md5hash
7 ##
8 ## 2004-01-30
9 ##
10 ## Nick Vargish
11 ##
12 ## Simple md5 hash utility for generating md5 checksums of files.
13 ##
14 ## usage: md5hash <filename> [..]
15 ##
16 ## Use '-' as filename to sum standard input.
17
18 import hashlib
19 import sys
20
21 def sumfile(fobj):
22 '''Returns an md5 hash for an object with read() method.'''
23 m = hashlib.md5()
24 while True:
25 d = fobj.read(8096)
26 if not d:
27 break
28 m.update(d)
29 return m.hexdigest()
30
31
32 def md5sum(fname):
33 '''Returns an md5 hash for file fname, or stdin if fname is "-".'''
34 if fname == '-':
35 ret = sumfile(sys.stdin)
36 else:
37 try:
38 f = file(fname, 'rb')
39 except:
40 return 'Failed to open file'
41 ret = sumfile(f)
42 f.close()
43 return ret
44
45
46 # if invoked on command line, print md5 hashes of specified files.
47 if __name__ == '__main__':
48 for fname in sys.argv[1:]:
49 print '%32s %s' % (md5sum(fname), fname)
50
51
52