Last active
June 13, 2017 03:27
-
-
Save Avantol13/871e4047d03c5aaf71431c0a65e3b4ed to your computer and use it in GitHub Desktop.
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
import argparse | |
import sys | |
import os | |
def main(): | |
''' | |
Entry point of script | |
''' | |
# Parse arguments into script | |
args = parse_raw_args(sys.argv[1:]) | |
# If we don't want verbose output, ignore all print statements | |
if not args.verbose: | |
# Redirect print output to null device on operating system | |
print_redirect = open(os.devnull, 'w') | |
sys.stdout = print_redirect | |
def parse_raw_args(args): | |
''' | |
Returns parsed and validated arguments that were passed into the script. | |
:param args: The arguments passed into the script | |
''' | |
# Setup main parser | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--verbose', dest='verbose', default=True, | |
action='store_true', help='Verbose output') | |
# Initialize sub_command called to be None | |
parser.set_defaults(sub_command=None) | |
subparsers = parser.add_subparsers(help='Sub-Command Help (add --help after command for more help)') | |
# Add subparsers | |
subparsers = _add_something_subparser(subparsers) | |
# TODO add more subparsers | |
return parser.parse_args() | |
def _add_something_subparser(subparsers): | |
something_parser = subparsers.add_parser('add_something', help='Adds a something with information') | |
something_parser.add_argument('required', | |
help='required argument') | |
something_parser.add_argument('--opt', dest='optional', default=None, | |
help='optional argument') | |
# Set the sub_command called to be add_something. This happens only if this | |
# parser gets used during parse_args() call below | |
something_parser.set_defaults(sub_command='add_something') | |
return subparsers | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment