[PYTHON] argparse note

A note about argparse, the Python command line parsing tool

reference

Manual, Tutorial

Typical use case

import argparse

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="Concatenates a person's files",
        epilog='''Notices:
    1. You need an account first.
    2. Files should exist.
'''
    )
    parser.add_argument(
        '-o', '--outfile', default='foo.txt', help='Output file name')
    parser.add_argument(
        '-q', '--quiet', action='store_true', dest='qFlag',
        help='No messages to console')
    parser.add_argument(
        '-r', '--repeat', type=int, default=1, help='Repeat count')
    parser.add_argument(
        '-m', '--mode', required=True, choices=['t', 'b'], help='Mode')
    parser.add_argument('person', help='Person name')
        # mandatory positional argument
    parser.add_argument('infile', nargs='*', help='Input file name')
        # '+' can also be used for nargs
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--private', action='store_true')
    group.add_argument('--public',  action='store_true')
    args = parser.parse_args()

    print(f'outfile = {args.outfile}')            # long name is prefered
    print(f'quiet = {args.qFlag}')                # dest='qFlag'
    print(f'repeat count = {args.repeat * 100}')  # type=int
    print(f'# of infiles = {len(args.infile)}')   # stored as a list

main()

Execution example

$ ./a.py -m t --private uid a b c
outfile = foo.txt
quiet = False
repeat count = 100
# of infiles = 3

point

Recommended Posts

argparse note
Note
argparse
Note
Note
Django note 4
pyenv note
argparse part 1
(Note) Be careful with python argparse
Django Note 5
Note: Python
Ansible Note
Python note
Django Note 1
direnv note
Django note 3
Django note 2
[Note] RepresenterError
[Note] Image resizing
Python study note_002
Note: Python Decorator
Python programming note
[Python] Learning Note 1
Kinesis Firehose Note
Python study note_004
[Note] Regarding Tensorflow
Note: confusing nonlocal
Markdown Beginner's Note
PyData.Osaka Meetup # 2 Note
Python study note_003
Completely personal note
Flask's personal note # 2
python argparse template
Jupyter Study Note_002
TensFlow Preferences Note
[Note] openCV + python
Note about awk
Just a note
PyCharm Preferences Note
Note: List comprehension
Python beginner's note
Flask's personal note # 1
Jupyter Study Note_003
Jupyter Study Note_007
[Note] pandas unstack
Jupyter Study Note_005