source: hdf5_examine/src/Hdf5Examine/cli.py @ 1251

Last change on this file since 1251 was 1251, checked in by jemian, 9 years ago

initial checkin, refactored h5toText.py() to not print from method but return [str] instead

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision Url
File size: 4.3 KB
Line 
1#!/usr/local/bin/python2.7
2# encoding: utf-8
3'''
4Hdf5Examine.cli -- examine HDF5 data files
5
6Hdf5Examine.cli is a command-line interface original built for the NeXus documentation
7
8It defines :meth:`main`
9
10@author:     Pete Jemian
11       
12@copyright:  2013 Pete Jemian. All rights reserved.
13       
14@license:    license
15
16@contact:    prjemian@gmail.com
17@deffield    updated: Updated
18'''
19
20import sys
21import os
22
23from argparse import ArgumentParser
24from argparse import RawDescriptionHelpFormatter
25
26__all__ = []
27__version__ = 0.1
28__date__ = '2013-03-16'
29__updated__ = '2013-03-16'
30
31
32DEBUG = 1
33TESTRUN = 0
34PROFILE = 0
35
36
37class CLIError(Exception):
38    '''Generic exception to raise and log different fatal errors.'''
39    def __init__(self, msg):
40        super(CLIError).__init__(type(self))
41        self.msg = "E: %s" % msg
42    def __str__(self):
43        return self.msg
44    def __unicode__(self):
45        return self.msg
46
47
48def main(argv=None): # IGNORE:C0111
49    '''Command line options.'''
50   
51    if argv is None:
52        argv = sys.argv
53    else:
54        sys.argv.extend(argv)
55
56    program_name = os.path.basename(sys.argv[0])
57    program_version = "v%s" % __version__
58    program_build_date = str(__updated__)
59    program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
60    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
61    program_license = '''%s
62
63  Created by Pete Jemian on %s.
64  Copyright 2013 Pete Jemian. All rights reserved.
65 
66  Licensed under the Apache License 2.0
67  http://www.apache.org/licenses/LICENSE-2.0
68 
69  Distributed on an "AS IS" basis without warranties
70  or conditions of any kind, either express or implied.
71
72USAGE
73''' % (program_shortdesc, str(__date__))
74
75    try:
76        # Setup argument parser
77        parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)
78        parser.add_argument("-r", "--recursive", dest="recurse", action="store_true", help="recurse into subfolders [default: %(default)s]")
79        parser.add_argument("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %(default)s]")
80        parser.add_argument("-i", "--include", dest="include", help="only include paths matching this regex pattern. Note: exclude is given preference over include. [default: %(default)s]", metavar="RE" )
81        parser.add_argument("-e", "--exclude", dest="exclude", help="exclude paths matching this regex pattern. [default: %(default)s]", metavar="RE" )
82        parser.add_argument('-V', '--version', action='version', version=program_version_message)
83        parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]", metavar="path", nargs='+')
84       
85        # Process arguments
86        args = parser.parse_args()
87       
88        paths = args.paths
89        verbose = args.verbose
90        recurse = args.recurse
91        inpat = args.include
92        expat = args.exclude
93       
94        if verbose > 0:
95            print("Verbose mode on")
96            if recurse:
97                print("Recursive mode on")
98            else:
99                print("Recursive mode off")
100       
101        if inpat and expat and inpat == expat:
102            raise CLIError("include and exclude pattern are equal! Nothing will be processed.")
103       
104        for inpath in paths:
105            ### do something with inpath ###
106            print(inpath)
107        return 0
108    except KeyboardInterrupt:
109        ### handle keyboard interrupt ###
110        return 0
111    except Exception, e:
112        if DEBUG or TESTRUN:
113            raise(e)
114        indent = len(program_name) * " "
115        sys.stderr.write(program_name + ": " + repr(e) + "\n")
116        sys.stderr.write(indent + "  for help use --help")
117        return 2
118
119if __name__ == "__main__":
120    if DEBUG:
121        sys.argv.append("-h")
122        sys.argv.append("-v")
123        sys.argv.append("-r")
124    if TESTRUN:
125        import doctest
126        doctest.testmod()
127    if PROFILE:
128        import cProfile
129        import pstats
130        profile_filename = 'Hdf5Examine.h5toText_profile.txt'
131        cProfile.run('main()', profile_filename)
132        statsfile = open("profile_stats.txt", "wb")
133        p = pstats.Stats(profile_filename, stream=statsfile)
134        stats = p.strip_dirs().sort_stats('cumulative')
135        stats.print_stats()
136        statsfile.close()
137        sys.exit(0)
138    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.