imtest.py 1.6 KB
Newer Older
Paul McCarthy's avatar
Paul McCarthy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
#
# imtest.py - Test whether an image file exists or not.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""The ``imtest`` script can be used to test whether an image file exists or
not, without having to know the file suffix (.nii, .nii.gz, etc).
"""


import os.path        as op
import                   sys
import fsl.utils.path as fslpath


17
18
19
20
21
22
23
24
25
26
# The lists below are defined in the
# fsl.data.image class, but are duplicated
# here for performance (to avoid import of
# nibabel/numpy/etc).
exts = ['.nii.gz', '.nii',
        '.img',    '.hdr',
        '.img.gz', '.hdr.gz',
        '.mnc',    '.mnc.gz']
"""List of file extensions that are supported by ``imtest``.
"""
Paul McCarthy's avatar
Paul McCarthy committed
27

28
29
groups = [('.hdr', '.img'), ('.hdr.gz', '.img.gz')]
"""List of known image file groups (image/header file pairs). """
Paul McCarthy's avatar
Paul McCarthy committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44


def main(argv=None):
    """Test if an image path exists, and prints ``'1'`` if it does or ``'0'``
    if it doesn't.
    """

    if argv is None:
        argv = sys.argv[1:]

    # emulate old fslio/imtest - always return 0
    if len(argv) != 1:
        print('0')
        return 0

45
    path = fslpath.removeExt(argv[0], exts)
Paul McCarthy's avatar
Paul McCarthy committed
46
47
48
49
50
51
52
53
    path = op.realpath(path)

    # getFileGroup will raise an error
    # if the image (including all
    # components - i.e. header and
    # image) does not exist
    try:
        fslpath.getFileGroup(path,
54
55
                             allowedExts=exts,
                             fileGroups=groups,
Paul McCarthy's avatar
Paul McCarthy committed
56
57
58
59
60
61
62
63
64
65
                             unambiguous=True)
        print('1')
    except fslpath.PathError:
        print('0')

    return 0


if __name__ == '__main__':
    sys.exit(main())