Last active
January 15, 2020 15:16
-
-
Save EngineerLabShimazu/95c0034e05d64aa1f5afaee254339918 to your computer and use it in GitHub Desktop.
Python argparse.ArgumentParser sample
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 sys | |
import argparse | |
class Command: | |
def __init__(self, args): | |
parser = argparse.ArgumentParser(description='class sample') | |
parser.add_argument('--main', '-m', action='store_true', help='main command from class') | |
self.parser = parser | |
try: | |
self.args = parser.parse_args(args) | |
except argparse.ArgumentError: | |
sys.exit(1) |
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 | |
# usage | |
# $ python sample.py --main | |
# main command | |
parser = argparse.ArgumentParser(description='original command') | |
parser.add_argument('--main', '-m', action='store_true', help='main command') | |
args = parser.parse_args() | |
if args.main: | |
print(f'main command') |
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 | |
parser = argparse.ArgumentParser(description='original command') | |
parser.add_argument('--main', '-m', action='store_true', help='main command') | |
subparsers = parser.add_subparsers() | |
parser_sub = subparsers.add_parser('sub', help='sub command') | |
parser_sub.add_argument('--a', '-a', action='store_true', help='sub command') | |
parser_sub.add_argument('--b', '-b', metavar='msg', help='message') | |
args = parser.parse_args() | |
if args.main: | |
# usage | |
# $ python sample.py --main | |
# main command | |
print(f'main command') | |
if args.a: | |
# usage | |
# $ python sample.py sub -a | |
# sub True | |
print(f'sub command a: {args}') | |
if args.b: | |
# usage | |
# $ python sample.py sub -b sample | |
# sub command b: sample | |
print(f'sub command b: {args.b}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment