Skip to content

Commit

Permalink
allow titlecase to be a command line utility
Browse files Browse the repository at this point in the history
Try to be pretty forgiving in the implementation so that pretty much
anything folks throw at it works as you'd expect.

Closes #20.
  • Loading branch information
ppannuto committed Feb 28, 2017
1 parent 8cf7a4c commit b095020
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
7 changes: 5 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ def readme():
tests_require=['nose'],
setup_requires=['nose>=1.0'],
test_suite="titlecase.tests",
entry_points = """\
"""
entry_points = {
'console_scripts': [
'titlecase = titlecase.__init__:cmd',
],
},
)

46 changes: 46 additions & 0 deletions titlecase/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
License: http://www.opensource.org/licenses/mit-license.php
"""

import argparse
import re
import sys

__all__ = ['titlecase']
__version__ = '0.8.2'
Expand Down Expand Up @@ -124,3 +126,47 @@ def titlecase(text, callback=None):
processed.append(result)

return "\n".join(processed)


def cmd():
'''Handler for command line invocation'''

# Try to handle any reasonable thing thrown at this.
# Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout
# and treat any subsequent arguments as a space separated string to
# be titlecased (so it still works if people forget quotes)
parser = argparse.ArgumentParser()
in_group = parser.add_mutually_exclusive_group()
in_group.add_argument('string', nargs='*', default=[],
help='String to titlecase')
in_group.add_argument('-f', '--input-file',
help='File to read from to titlecase')
parser.add_argument('-o', '--output-file',
help='File to write titlecased output to)')

args = parser.parse_args()

if args.input_file is not None:
if args.input_file == '-':
ifile = sys.stdin
else:
ifile = open(args.input_file)
else:
ifile = sys.stdin

if args.output_file is not None:
if args.output_file == '-':
ofile = sys.stdout
else:
ofile = open(args.output_file, 'w')
else:
ofile = sys.stdout

if args.string is not None:
in_string = ' '.join(args.string)
else:
with ifile:
in_string = ifile.read()

with ofile:
ofile.write(titlecase(in_string))

1 comment on commit b095020

@Naereen
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good!

Please sign in to comment.