My favorites | Sign in
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
#
# Library: pyflowctrl
# Module: hashfile1
# Dependency: core2
# Examples: examples/example14.py
#
# links: Cryptographic hash function, http://en.wikipedia.org/wiki/Cryptographic_hash_function
#

import os
import hashlib
from core2 import Stream, Process, EmptyStream
from streams.stdiostreams1 import StandardErrorStream

class UnknownAlgorithm(Exception): pass

class FileHash(Process):
''' File hash calculation '''

def __init__(self, algorithm='md5'):
super(FileHash, self).__init__()
self.io = {
'input': Stream(data_type='path'),
'output': Stream(data_type=('path', 'hash')),
'error': StandardErrorStream()
}
self.hashfunc = None
if algorithm in hashlib.algorithms:
# 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'
if algorithm == 'md5':
self.hashfunc = hashlib.md5
elif algorithm == 'sha1':
self.hashfunc = hashlib.sha1
elif algorithm == 'sha224':
self.hashfunc = hashlib.sha224
elif algorithm == 'sha256':
self.hashfunc = hashlib.sha256
elif algorithm == 'sha384':
self.hashfunc = hashlib.sha384
elif algorithm == 'sha512':
self.hashfunc = hashlib.sha512
else:
raise UnknowAlgorithm(algorithm)

def hashcalc(self, path):
''' calculation of file hash '''
try:
data = open(path, 'rb')
handler = self.hashfunc()
chunk_size = 2**16 # chunk size of file
while 1:
chunk = data.read(chunk_size)
if not chunk: break
handler.update(chunk)
data.close()
except IOError:
return None
return handler.hexdigest()

def main(self):
while True:
path = self.io['input'].get()
if os.path.isfile(path):
self.io['output'].put((path, self.hashcalc(path)))
else:
self.io['error'].put("%s is not a file\n" % path)
continue
yield

Change log

0e3e43912849 by ownport <ownport> on Jul 22, 2011   Diff
pyflowctrl: filehash1.py added for
calculating hash of file(s)
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 2244 bytes, 70 lines
Powered by Google Project Hosting