LoginSignup
7
6

More than 5 years have passed since last update.

python でコマンドライン引数をパースする

Last updated at Posted at 2016-10-01

Q: python では、コマンドライン引数をパースするには?
A: ArgumentParserを使う選択肢がありました。

下記のコードをみると後でみても説明はほぼ要らないでしょうと。
このパーサーは、引数をパースして辞書にしてくれます。

#!/usr/local/bin/python3

import argparse

parser = argparse.ArgumentParser(description = "description goes here")
parser.add_argument("-i", type=str, help = "help text goes here. This option is required", required=True)
parser.add_argument("-o", type=str, help = "help text goes here. This option is optional", required=False)

#command_arguments is dictinary
command_arguments = parser.parse_args()

ivariable = command_arguments.i
print(ivariable)

実行例もあれば、もっとわかりやすそう。

$ python3 test.py -i www
www

$ python3 test.py -i www -o asd
www

$ python3 test.py -i www -o 
usage: test.py [-h] -i I [-o O]
test.py: error: argument -o: expected one argument

$ python3 test.py
usage: test.py [-h] -i I [-o O]
test.py: error: the following arguments are required: -i

$ python3 test.py -i
usage: test.py [-h] -i I [-o O]
test.py: error: argument -i: expected one argument

$ 

7
6
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
7
6