cbfd519b044241ebb3356ce70495a1d0b54dccc3
[igor.git] / igor / script.py
1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
2 #
3 # This file is part of igor.
4 #
5 # igor is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
8 # later version.
9 #
10 # igor is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
13 # details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with igor.  If not, see <http://www.gnu.org/licenses/>.
17
18 "Common code for scripts distributed with the `igor` package."
19
20 from __future__ import absolute_import
21 import argparse as _argparse
22 import logging as _logging
23 import sys as _sys
24
25 from . import __version__
26 from . import LOG as _LOG
27
28
29 class Script (object):
30     log_levels = [_logging.ERROR, _logging.WARNING, _logging.INFO, _logging.DEBUG]
31
32     def __init__(self, description=None, filetype='IGOR Binary Wave (.ibw) file'):
33         self.parser = _argparse.ArgumentParser(
34             description=description, version=__version__)
35         self.parser.add_argument(
36             '-f', '--infile', metavar='FILE', default='-',
37             help='input {}'.format(filetype))
38         self.parser.add_argument(
39             '-o', '--outfile', metavar='FILE', default='-',
40             help='file for ASCII output')
41         self.parser.add_argument(
42             '-V', '--verbose', action='count', default=0,
43             help='increment verbosity')
44
45     def run(self, *args, **kwargs):
46         args = self.parser.parse_args(*args, **kwargs)
47         if args.infile == '-':
48             args.infile = _sys.stdin
49         if args.outfile == '-':
50             args.outfile = _sys.stdout
51         if args.verbose > 1:
52             log_level = self.log_levels[min(args.verbose-1, len(self.log_levels)-1)]
53             _LOG.setLevel(log_level)
54         self._run(args)
55
56     def _run(self, args):
57         raise NotImplementedError()