Mercurial > hg > TextShaper
comparison textshaper/corename.py @ 44:8addd6e12b29
corename
| author | Jeff Hammel <k0scist@gmail.com> |
|---|---|
| date | Wed, 11 Mar 2015 10:15:20 -0700 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 43:21b6a9569f21 | 44:8addd6e12b29 |
|---|---|
| 1 #!/usr/bin/env python | |
| 2 # -*- coding: utf-8 -*- | |
| 3 | |
| 4 """ | |
| 5 echo core name of files | |
| 6 """ | |
| 7 | |
| 8 # imports | |
| 9 import argparse | |
| 10 import os | |
| 11 import sys | |
| 12 | |
| 13 # module globals | |
| 14 __all__ = ['main', 'Parser'] | |
| 15 | |
| 16 def ensure_dir(directory): | |
| 17 """ensure a directory exists""" | |
| 18 if os.path.exists(directory): | |
| 19 if not os.path.isdir(directory): | |
| 20 raise OSError("Not a directory: '{}'".format(directory)) | |
| 21 return directory | |
| 22 os.makedirs(directory) | |
| 23 return directory | |
| 24 | |
| 25 | |
| 26 class Parser(argparse.ArgumentParser): | |
| 27 """CLI option parser""" | |
| 28 def __init__(self, **kwargs): | |
| 29 kwargs.setdefault('formatter_class', argparse.RawTextHelpFormatter) | |
| 30 kwargs.setdefault('description', __doc__) | |
| 31 argparse.ArgumentParser.__init__(self, **kwargs) | |
| 32 self.add_argument('files', nargs='*', | |
| 33 help="files, else read from stdin") | |
| 34 self.options = None | |
| 35 | |
| 36 def parse_args(self, *args, **kw): | |
| 37 options = argparse.ArgumentParser.parse_args(self, *args, **kw) | |
| 38 self.validate(options) | |
| 39 self.options = options | |
| 40 return options | |
| 41 | |
| 42 def validate(self, options): | |
| 43 """validate options""" | |
| 44 | |
| 45 def main(args=sys.argv[1:]): | |
| 46 """CLI""" | |
| 47 | |
| 48 # parse command line options | |
| 49 parser = Parser() | |
| 50 options = parser.parse_args(args) | |
| 51 | |
| 52 if not options.files: | |
| 53 options.files = sys.stdin.read().strip().split() | |
| 54 | |
| 55 corenames = [os.path.splitext(os.path.basename(f))[0] | |
| 56 for f in options.files] | |
| 57 print (" ".join(corenames)) | |
| 58 | |
| 59 if __name__ == '__main__': | |
| 60 main() | |
| 61 | |
| 62 |
