0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python標準ライブラリだけでCLIを作る:argparseの実測メモ

0
Posted at

はじめに

ちょっとしたツールにコマンドライン引数を付けるなら、Python標準の argparse で十分です。外部ライブラリを入れずに、サブコマンド・型変換・フラグ・ヘルプを扱えます。

この記事では、サブコマンド付きのCLIを作り、正常系と異常系の挙動を実測します。

環境

  • Windows 11(ビルド 10.0.26200)
  • Python 3.11.5

やったこと

1. サブコマンド付きのパーサー

import argparse

parser = argparse.ArgumentParser(prog="tool.py")
sub = parser.add_subparsers(dest="cmd", required=True)

p_run = sub.add_parser("run", help="サーバーを起動する")
p_run.add_argument("--port", type=int, default=5006, help="待受ポート")
p_run.add_argument("--dry-run", action="store_true", help="変更せず表示だけ")

p_check = sub.add_parser("check", help="設定を検証する")
p_check.add_argument("path", help="設定ファイルのパス")

2. 正常系

args = parser.parse_args(["run", "--port", "5007", "--dry-run"])
print(args)

結果:

Namespace(cmd='run', port=5007, dry_run=True)

--port は type=int で整数に変換され、--dry-run は store_true で真偽値になります。

3. 異常系(型変換の失敗)

python tool.py run --port abc

結果:

usage: tool.py run [-h] [--port PORT] [--dry-run]
tool.py run: error: argument --port: invalid int value: 'abc'

終了コードは 2 です。argparse がエラーメッセージとusageを表示し、SystemExit(2) で終了します。

4. ヘルプ

python tool.py --help
python tool.py run --help

--help は自動で追加され、サブコマンドごとのヘルプも生成されます。

5. 必須のサブコマンド

add_subparsers(required=True) を指定すると、サブコマンドなしの実行はエラーになります。

tool.py: error: the following arguments are required: cmd

6. 実装側の分岐

if args.cmd == "run":
    start_server(port=args.port, dry_run=args.dry_run)
elif args.cmd == "check":
    check_config(args.path)

args.cmd で分岐するか、set_defaults(func=...) で関数を登録します。

p_run.set_defaults(func=start_server)
...
args.func(**vars(args))

ハマった点

type=int を忘れると文字列のまま

--port 5007 は、type=int がないと "5007" という文字列になります。後で + 1 してエラー、という事故が起きます。

store_true の既定値はFalse

action="store_true" のフラグは、指定しなければ False です。default=True にすると「指定しないとTrue」になるため、意味が逆になります。

エラー時の終了コードは2

argparse のエラーは終了コード 2 です。バッチ処理で「引数エラー」と「実行エラー」を区別したい場合は、この値も確認します。

ヘルプ文字列を日本語にする

help="..." は日本語でも表示されます。ただし、コンソールの文字コードによっては化けることがあるため、必要ならUTF-8で出力します。

まとめ

  • argparse だけでサブコマンド・型変換・フラグ・ヘルプを実装できる。
  • add_subparsers(required=True) でサブコマンドを必須にできる。
  • type=int、action="store_true" の意味を確認する。
  • 引数エラーの終了コードは 2。
  • 実装側は args.cmd か set_defaults(func=...) で分岐する。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?