Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Argparse setup #2

Merged
merged 3 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 71 additions & 2 deletions src/pyMetricCli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

import sys
import logging
import argparse

from pyMetricCli.version import __version__, __author__, __email__, __repository__, __license__
from pyMetricCli.ret import Ret
Expand All @@ -45,6 +46,12 @@

LOG: logging.Logger = logging.getLogger(__name__)

PROG_NAME = "pyMetricCli"
PROG_DESC = "Collection of scripts and API implementations for generating and playing with metrics."
PROG_COPYRIGHT = f"Copyright (c) 2024 NewTec GmbH - {__license__}"
PROG_GITHUB = f"Find the project on GitHub: {__repository__}"
PROG_EPILOG = f"{PROG_COPYRIGHT} - {PROG_GITHUB}"

################################################################################
# Classes
################################################################################
Expand All @@ -54,15 +61,77 @@
################################################################################


def add_parser() -> argparse.ArgumentParser:
""" Add parser for command line arguments and
set the execute function of each
cmd module as callback for the subparser command.
Return the parser after all the modules have been registered
and added their subparsers.


Returns:
argparse.ArgumentParser: The parser object for commandline arguments.
"""
parser = argparse.ArgumentParser(prog=PROG_NAME,
description=PROG_DESC,
epilog=PROG_EPILOG)

required_arguments = parser.add_argument_group('required arguments')

required_arguments.add_argument('-c',
'--config_file',
type=str,
metavar='<config_file>',
required=True,
help="Configuration file to be used.")

parser.add_argument("--version",
action="version",
version="%(prog)s " + __version__)

parser.add_argument("-v",
"--verbose",
action="store_true",
help="Print full command details before executing the command.\
Enables logs of type INFO and WARNING.")

return parser


def main() -> Ret:
""" The program entry point function.

Returns:
int: System exit status.
"""
ret_status = Ret.OK
logging.basicConfig(level=logging.INFO)
LOG.info("Hello World!")

# Create the main parser and add the subparsers.
parser = add_parser()

# Parse the command line arguments.
args = parser.parse_args()

# Check if the command line arguments are valid.
if args is None:
ret_status = Ret.ERROR_ARGPARSE
parser.print_help()
else:
# If the verbose flag is set, change the default logging level.
if args.verbose:
gabryelreyes marked this conversation as resolved.
Show resolved Hide resolved
logging.basicConfig(level=logging.INFO)
LOG.info("Program arguments: ")
for arg in vars(args):
LOG.info("* %s = %s", arg, vars(args)[arg])

try:
if args.config_file.endswith(".json") is False:
raise ValueError(
"Invalid config_file format. Please provide a JSON file.")
except Exception as e: # pylint: disable=broad-except
LOG.error("An error occurred: %s", e)
ret_status = Ret.ERROR

return ret_status

################################################################################
Expand Down
1 change: 1 addition & 0 deletions src/pyMetricCli/ret.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class Ret(IntEnum):
"""
OK = 0
ERROR = 1
ERROR_ARGPARSE = 2 # Must be 2 to match the argparse error code.

################################################################################
# Functions
Expand Down