LoginSignup
4
5

More than 1 year has passed since last update.

Pythonでリスト型のコマンドライン引数を受け取る

Posted at

リストのコマンドライン引数を受け取る

やり方は色々あるかもしれませんが,今回はArgumentParserを使います.
ArgumentParserの主な使い方については,「ArgumentParserの使い方を簡単にまとめた」をどうぞ.

プログラム例

コマンドライン引数にfloat型のリストとint型のリストを与え,それを表示させるプログラムです.

test.py
import argparse

parser = argparse.ArgumentParser(description='an example program')

parser.add_argument('--flist', required=True, nargs="*", type=float, help='a list of float variables') 
parser.add_argument('--ilist', required=True, nargs="*", type=int, help='a list of int variables')

args = parser.parse_args()

print(args.flist)
print(args.ilist)

実行例

$ python test.py --flist 1 2 3 --ilist 1 2 3
[1.0, 2.0, 3.0]
[1, 2, 3]

注意点やポイント

  • コマンドライン引数にリストを与える時は,[1,2,3]の形ではなく1 2 3のように空白を空けて渡すようにしてください
  • わざわざオプション引数(e.g. --flist)とした上で,required=Trueを付けています
4
5
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
4
5