LoginSignup
1
2

More than 5 years have passed since last update.

Pythonにコマンドライン引数を渡す② docopt編

Last updated at Posted at 2018-11-29

以前書いた記事ではsys.argvを用いたがdocoptなら変数順やヘルプを表示できるので良さそうな気がする。

docopt練習

デフォルトでは入っていないのでpipで入れる必要があるのが難点。

前と同じ,指定したファイルに適当な配列を保存するtest.pyを考える。
使用例は,以下の様となる。

test.py -f hoge2.txt -s 10

この-fや-sの修飾子を用いてファイル名sizeであることを指定できる。

test.py -s 9 -f hoge3.txt 

従って順番を変えても良い。

"""Matrix Saving Program

usage:
    test.py [-h] [-f <filename>] [-s <msize>]

options:
    -h, --help  show this help message and exit
    -f <filename>    txt filename for saving
    -s <msize>    matrix size
"""


# named as test.py
import numpy as np
from docopt import docopt

if __name__=='__main__':
    args = docopt(__doc__) 
    print(args)

    if args["-f"]:
        savefile = args["-f"]
    else:
        savefile = 'hoge.txt'

    if args["-s"]:
        size = int(args["-s"])
    else:
        size = 5

    ## create random array
    array = np.random.rand(size,size)
    np.savetxt(savefile,array)

もうちょっと手間多めに書いた別バージョン

少し丁寧目に書くと以下のようになる。
指定の仕方のバリエーションが増えるだけなので特に気にしなくても良いかも。

"""Matrix Saving Program

usage:
    test.py [-h] [--filename <filename>] [--size <msize>]

options:
    -h, --help  show this help message and exit
    -f, --filename <filename>    txt filename for saving
    -s, --size <msize>    matrix size
"""


# named as test.py
import numpy as np
from docopt import docopt

if __name__=='__main__':
    args = docopt(__doc__) 
    print(args)

    if args["--filename"]:
        savefile = args["--filename"]
    else:
        savefile = 'hoge.txt'

    if args["--size"]:
        size = int(args["--size"])
    else:
        size = 5

    ## create random array
    array = np.random.rand(size,size)
    np.savetxt(savefile,array)
1
2
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
1
2