Skip to content

Commit

Permalink
set up basic argparse functionality with sys, see #16
Browse files Browse the repository at this point in the history
  • Loading branch information
tbonza committed Jul 13, 2019
1 parent 5a7d35b commit 473419d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 41 deletions.
47 changes: 6 additions & 41 deletions bin/okra
Original file line number Diff line number Diff line change
@@ -1,53 +1,18 @@
#! /usr/bin/env python

import argparse
import sys
import logging

from okra.cli import print_help, parse_args
from okra.logging_utils import enable_cloud_log

logger = logging.getLogger(__name__)


class _HelpAction(argparse._HelpAction):
""" Reference: https://stackoverflow.com/questions/20094215 """

def __call__(self, parser, namespace, values, option_string=None):
parser.print_help()

# retrieve subparsers from parser
subparsers_actions = [
action for action in parser._actions
if isinstance(action, argparse._SubParsersAction)]

# there will probably only be one subparser_action,
# but better safe than sorry

for subparsers_action in subparsers_actions:

# get all subparsers and print help

for choice, subparser in subparsers_action.choices.items():

print("Subparser '{}'".format(choice))
print(subparser.format_help())

parser.exit()


parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('--help', action=_HelpAction, help='big help')
parser.add_argument('task', action='store_true', help='name of task to perform (compute)')

subparsers = parser.add_subparsers(help='run these tasks, pass the bong')
task_parser = subparsers.add_parser("compute", help="compute the following")
enable_cloud_log(level='INFO')

task_parser.add_argument('-repo', help='git clone url to git repo')
logger = logging.getLogger(__name__)

# Configure logging

enable_cloud_log(level='INFO')
parse_args(sys.argv)

parsed_args = parser.parse_args()

print(parsed_args)
print_help()
43 changes: 43 additions & 0 deletions okra/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
""" Command Line Interface utilities for Okra """
import sys

CLI_HELP = """
okra {task}
{task}
compute Perform the 'compute' task.
{compute}
repo Check cache, clone repo if confirmed; create database and generate report.
Optional Args
-h --help Print this help menu then exit.
"""
TASKS = ["compute"]

def print_help(good=True):
print(CLI_HELP)
if good:
sys.exit(0)
sys.exit(2)

def parse_args(args: list):
""" Parse sys.argv arguments. """

if len(args) < 2:
sys.stderr.write("\nERROR: 'okra {task}' missing from cli\n")
print_help()

if args[1] == "compute":
print("good one")

else:
sys.stderr.write("\nERROR: got {{task}}: {}, want one of {{task}}: {}\n".\
format(args[1], ",".join(TASKS)))



return True

0 comments on commit 473419d

Please sign in to comment.