0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでオプション付きのコマンドを作成する(argparse)

Last updated at Posted at 2019-03-09

概要

pythonでオプション付きのコマンドを作成する方法。
argparseというモジュールを使います。

関連記事

pythonスクリプトを作成

sampleというファイル名で作成する。

sample
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import argparse

'''
引数の定義
-a, -bは必須
-c, -dは任意
'''
def get_args():
    psr = argparse.ArgumentParser()
    psr.add_argument('-a', '--alpha', required=True, help='A explanation for arg called a')
    psr.add_argument('-b', '--bravo', required=True, help='A explanation for arg called b')
    psr.add_argument('-c', '--charlie', help='A explanation for arg called c')
    psr.add_argument('-d', '--delta', help='A explanation for arg called d')

    return psr.parse_args()

if __name__ == '__main__':
    args = get_args()

    print(args.alpha)
    print(args.bravo)
    print(args.charlie)
    print(args.delta)

help

--helpもしくは-hを指定する。

$ ./sample  --help
usage: sample [-h] -a ALPHA -b BRAVO [-c CHARLIE] [-d DELTA]

optional arguments:
  -h, --help            show this help message and exit
  -a ALPHA, --alpha ALPHA
                        A explanation for arg called a
  -b BRAVO, --bravo BRAVO
                        A explanation for arg called b
  -c CHARLIE, --charlie CHARLIE
                        A explanation for arg called c
  -d DELTA, --delta DELTA
                        A explanation for arg called d

必須オプションである-a, -bを指定しないとエラーとなる。

$ ./sample
usage: sample [-h] -a ALPHA -b BRAVO [-c CHARLIE] [-d DELTA]
sample: error: argument -a/--alpha is required

実行例

オプションを全て付与して実行する。

$ ./sample -a sample001 -b sample002 -c sample003 -d sample004
sample001
sample002
sample003
sample004

オプションは順不同。

$ ./sample -c sample003 -d sample004 -b sample002 -a sample001
sample001
sample002
sample003
sample004

必須オプションのみ指定。

$ ./sample -a sample001 -b sample002
sample001
sample002
None
None

--alpha-a, --bravo-b--charlie-c--delta-dと同義。

$ ./sample --alpha sample001 --bravo sample002 --charlie sample003 --delta sample004
sample001
sample002
sample003
sample004
0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?