|
3 | 3 | # vi: set ft=python sts=4 ts=4 sw=4 et:
|
4 | 4 | """Miscellaneous file manipulation functions
|
5 | 5 |
|
| 6 | + .. testsetup:: |
| 7 | + # Change directory to provide relative paths for doctests |
| 8 | + >>> import os |
| 9 | + >>> filepath = os.path.dirname(os.path.realpath( __file__ )) |
| 10 | + >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data')) |
| 11 | + >>> os.chdir(datadir) |
| 12 | +
|
6 | 13 | """
|
7 | 14 | from __future__ import (print_function, division, unicode_literals,
|
8 | 15 | absolute_import)
|
@@ -222,19 +229,38 @@ def check_forhash(filename):
|
222 | 229 | return False, None
|
223 | 230 |
|
224 | 231 |
|
225 |
| -def hash_infile(afile, chunk_len=8192, crypto=hashlib.md5): |
226 |
| - """ Computes hash of a file using 'crypto' module""" |
227 |
| - hex = None |
228 |
| - if op.isfile(afile): |
229 |
| - crypto_obj = crypto() |
230 |
| - with open(afile, 'rb') as fp: |
231 |
| - while True: |
232 |
| - data = fp.read(chunk_len) |
233 |
| - if not data: |
234 |
| - break |
235 |
| - crypto_obj.update(data) |
236 |
| - hex = crypto_obj.hexdigest() |
237 |
| - return hex |
| 232 | +def hash_infile(afile, chunk_len=8192, crypto=hashlib.md5, |
| 233 | + raise_notfound=False): |
| 234 | + """ |
| 235 | + Computes hash of a file using 'crypto' module |
| 236 | +
|
| 237 | + >>> hash_infile('smri_ants_registration_settings.json') |
| 238 | + '49b956387ed8d95a4eb44576fc5103b6' |
| 239 | +
|
| 240 | + >>> hash_infile('surf01.vtk') |
| 241 | + 'fdf1cf359b4e346034372cdeb58f9a88' |
| 242 | +
|
| 243 | + >>> hash_infile('spminfo') |
| 244 | + '0dc55e3888c98a182dab179b976dfffc' |
| 245 | +
|
| 246 | + >>> hash_infile('fsl_motion_outliers_fd.txt') |
| 247 | + 'defd1812c22405b1ee4431aac5bbdd73' |
| 248 | +
|
| 249 | +
|
| 250 | + """ |
| 251 | + if not op.isfile(afile): |
| 252 | + if raise_notfound: |
| 253 | + raise RuntimeError('File "%s" not found.' % afile) |
| 254 | + return None |
| 255 | + |
| 256 | + crypto_obj = crypto() |
| 257 | + with open(afile, 'rb') as fp: |
| 258 | + while True: |
| 259 | + data = fp.read(chunk_len) |
| 260 | + if not data: |
| 261 | + break |
| 262 | + crypto_obj.update(data) |
| 263 | + return crypto_obj.hexdigest() |
238 | 264 |
|
239 | 265 |
|
240 | 266 | def hash_timestamp(afile):
|
|
0 commit comments