view textshaper/corename.py @ 54:1d755747e67a

almost there
author Jeff Hammel <k0scist@gmail.com>
date Sun, 17 May 2015 09:11:30 -0700
parents 8addd6e12b29
children
line wrap: on
line source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
echo core name of files
"""

# imports
import argparse
import os
import sys

# module globals
__all__ = ['main', 'Parser']

def ensure_dir(directory):
    """ensure a directory exists"""
    if os.path.exists(directory):
        if not os.path.isdir(directory):
            raise OSError("Not a directory: '{}'".format(directory))
        return directory
    os.makedirs(directory)
    return directory


class Parser(argparse.ArgumentParser):
    """CLI option parser"""
    def __init__(self, **kwargs):
        kwargs.setdefault('formatter_class', argparse.RawTextHelpFormatter)
        kwargs.setdefault('description', __doc__)
        argparse.ArgumentParser.__init__(self, **kwargs)
        self.add_argument('files', nargs='*',
                          help="files, else read from stdin")
        self.options = None

    def parse_args(self, *args, **kw):
        options = argparse.ArgumentParser.parse_args(self, *args, **kw)
        self.validate(options)
        self.options = options
        return options

    def validate(self, options):
        """validate options"""

def main(args=sys.argv[1:]):
    """CLI"""

    # parse command line options
    parser = Parser()
    options = parser.parse_args(args)

    if not options.files:
        options.files = sys.stdin.read().strip().split()

    corenames = [os.path.splitext(os.path.basename(f))[0]
                 for f in options.files]
    print (" ".join(corenames))

if __name__ == '__main__':
    main()