|
Python:Tips:コマンドライン引数
2026/02/17 | ||||||
|
| ||||||
コマンドライン引数は自動化の強い味方
sys.argv
>python test.py 100 200 ← Pythonインタープリタ経由で実行 3 ['test.py', '100', '200'] argparse
import argparse # argparseライブラリをimport # コマンドライン引数のparserインスタンス取得 args_parser = argparse.ArgumentParser() # --input_name は必須(required)オプション args_parser.add_argument('--input_name', type=str, help='input file name', required=True) # --output_nameは省略可能で、デフォルトは'hoge.txt' args_parser.add_argument('--output_name', type=str, help='output file name', default='hoge.txt') # --over_writeは指定されればTrue args_parser.add_argument('--over_write', action='store_true', help="output overwrite flag") # コマンドライン引数の解析結果取得(Namespaceオブジェクト) namespace_args = args_parser.parse_args() print(namespace_args) # Namespaceオブジェクトをdictに変換 dict_args = vars(namespace_args) print('dict:', dict_args)
>test.py --input_name hoge.txt --output_name fuga.txt
Namespace(input_name='hoge.txt', output_name='fuga.txt', over_write=False)
dict: {'input_name': 'hoge.txt', 'output_name': 'fuga.txt', 'over_write': False}
>test.py usage: test.py [-h] --input_name INPUT_NAME [--output_name OUTPUT_NAME] [--over_write] test.py: error: the following arguments are required: --input_name
>test.py -h
usage: test.py [-h] --input_name INPUT_NAME [--output_name OUTPUT_NAME] [--over_write]
options:
-h, --help show this help message and exit
--input_name INPUT_NAME
input file name
--output_name OUTPUT_NAME
output file name
--over_write output overwrite flag
.add_argument('--input_name', '-in', type=str, help='input file name', required=True)
ワイルドカードの扱い
| ||||||
|
Copyright(C) 2026 Altmo
本HPについて | ||||||
|
|