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プログラムで引数を受け取る方法(argparse)

Posted at
# 実行例:Alice 25がひきす
python main.py Alice 25 --verbose
import argparse

# ArgumentParser の作成
parser = argparse.ArgumentParser(description="引数を処理するスクリプト")

# 引数の定義
parser.add_argument("name", type=str, help="名前を入力してください")
parser.add_argument("age", type=int, help="年齢を入力してください")

# オプション引数(-- を付けるとオプションになる)
parser.add_argument("--verbose", action="store_true", help="詳細出力を有効にする")

# 引数を解析
args = parser.parse_args()

# 取得した引数を表示
print(f"名前: {args.name}")
print(f"年齢: {args.age}")

if args.verbose:
    print("詳細モードが有効です")
# ヘルプ呼び出し
python main.py --help

usage: main.py [-h] [--verbose] name age

引数を処理するスクリプト

positional arguments:
  name        名前を入力してください
  age         年齢を入力してください

options:
  -h, --help  show this help message and exit
  --verbose   詳細出力を有効にする
  
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?