diff textshaper/corename.py @ 44:8addd6e12b29

corename
author Jeff Hammel <k0scist@gmail.com>
date Wed, 11 Mar 2015 10:15:20 -0700
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/textshaper/corename.py	Wed Mar 11 10:15:20 2015 -0700
@@ -0,0 +1,62 @@
+#!/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()
+
+