Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

標準ライブラリのargparseでCLIパーサ

$ python -m serial.tools.list_ports --help
usage: list_ports.py [-h] [-v] [-q] [-n N] [regexp]

Serial port enumeration

positional arguments:
  regexp         only show ports that match this regex

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  show more messages
  -q, --quiet    suppress all messages
  -n N           only output the N-th entry

これを実現しているスクリプトは以下の通り

def main():
    import argparse

    parser = argparse.ArgumentParser(description='Serial port enumeration')

    parser.add_argument(
        'regexp',
        nargs='?',
        help='only show ports that match this regex')

    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='show more messages')

    parser.add_argument(
        '-q', '--quiet',
        action='store_true',
        help='suppress all messages')

    parser.add_argument(
        '-n',
        type=int,
        help='only output the N-th entry')

    args = parser.parse_args()

    hits = 0
    # get iteraror w/ or w/o filter
    if args.regexp:
        if not args.quiet:
            sys.stderr.write("Filtered list with regexp: {!r}\n".format(args.regexp))
        iterator = sorted(grep(args.regexp))
    else:
        iterator = sorted(comports())
    # list them
    for n, (port, desc, hwid) in enumerate(iterator, 1):
        if args.n is None or args.n == n:
            sys.stdout.write("{:20}\n".format(port))
            if args.verbose:
                sys.stdout.write("    desc: {}\n".format(desc))
                sys.stdout.write("    hwid: {}\n".format(hwid))
        hits += 1
    if not args.quiet:
        if hits:
            sys.stderr.write("{} ports found\n".format(hits))
        else:
            sys.stderr.write("no ports found\n")