Last active
December 12, 2015 03:08
-
-
Save RWJMurphy/4704593 to your computer and use it in GitHub Desktop.
PEP8 compliant stub for building Python CLI tools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# vim: ft=python ts=4 sw=4 expandtab | |
"""A stub for command line applications in Python.""" | |
__version__ = "0.0.0" | |
import argparse | |
import os | |
import sys | |
class CLI: | |
"""Class that implements the application logic for the command line | |
application.""" | |
def __init__(self, args): | |
self.verbose = args.verbose | |
self.files = args.file | |
def main(self): | |
"""Where the application logic runs.""" | |
result = os.EX_OK | |
for in_file in self.files: | |
for line in in_file: | |
print(line.strip()) | |
return result | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'-v', '--verbose', | |
help="be more verbose", | |
action='store_true') | |
parser.add_argument( | |
'-V', '--version', | |
help="display version information and exit", | |
action='store_true') | |
parser.add_argument( | |
'file', | |
help="read from this file. defaults to STDIN", | |
type=argparse.FileType('r'), | |
nargs='*', | |
default=[sys.stdin, ]) | |
arguments = parser.parse_args() | |
exit_code = os.EX_SOFTWARE | |
if arguments.version: | |
print("{program} {version}".format( | |
program=os.path.basename(__file__), | |
version=__version__)) | |
else: | |
try: | |
cli = CLI(arguments) | |
exit_code = cli.main() | |
except KeyboardInterrupt: | |
exit_code = os.EX_OK | |
except IOError as ioe: | |
if ioe.errno == 32: # Broken pipe | |
exit_code = os.EX_OK | |
else: | |
raise | |
sys.exit(exit_code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment