Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

以前書いた記事では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)
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away