アットウィキロゴ
okoba0119 @ ウィキ
掲示板 掲示板 ページ検索 ページ検索 メニュー メニュー

[python]コマンドライン引数の処理

最終更新:

okoba0119

- view
だれでも歓迎! 編集

getopt

  • 引数はsys.argvにリストで入ってくる
  • オプション引数の解析はgetopt
  • getoptの第二引数で、「:」が付くのは値をとるとき。


getopt(args, shortopts, longopts=[])
  • argsには引数
  • shortoptsは、引数が1文字の時
  • longoptsは長い引数の時
    • ex. --help --width 10のような時. ["help","width="])


sample code

import getopt
import sys

try:
	optlist.args = getopt.getopt(sys.args[1:],"f:")
except getopt.GetoptError,pe:
	print pe.msg
	sys.exit(0)
	
for opt,args in optlist:
	if opt in ("-f"):
		print("ok")



optparse

  • getoptより処理が楽.

sample code

  • infileには読み込むファイル
  • outfileには何か処理をして吐き出すファイル
  • よくあるパターンのスクリプト
    #! /bin/env python
    import outparse
    
    # getfile
    def getfiles():
        usage = u'%prog [-f:infile] [-o:outfile]
        parser = optparse.OptionParser(usage=usage)
        parser.add_option(
              '-f','--infile',
               action='store',
               type='string',
              help=u'input text file',
              metavar='infile'
        )
        
        parser.add_option(
             '-o','--outfile',
             action='store',
             type='string',
             help=u'output text file',
             metavar='outfile'
        )
        options.args = parser.parse_args()
    
     # main
     if __name__ = '__main__'
         getfiles()
    

実行結果1.

  • -hの引数でヘルプが出るのだ.
    [$/home/python] ./unko.py -h
    Usage: unko.py [-f:infile] [-o:outfile]
    
    Options:
      -h, --help           show this help message and exit
      -f infile,  --infile=infile
                                infile text file
      -o outfile, --outfile=outfile
                                outfile text file
    

実行結果2.

  • -f optionにちゃんと引数をつけるといけるみたいだ
    [$/home/python] ./unko.py -f unko
    []
    {'outfile': None, 'infie': 'unko'}
    

実行結果3.

  • -o optionもちゃんとつけて完成
    [$/home/python] ./unko.py -f unko -o test
    []
    {'outfile':'test','infile':'unko'}
    
    

その他のoption

  • add_optionで書いてあるように、オプションを設定できる。
  • 引数を取らないオプション
    • action引数に、'store_true' 、 'store_false' を指定することにより作成
  • オプションが設定されると 'store_true' は True を、 'store_false' は False をオプションの属性に格納
最近更新されたスレッド
ウィキ募集バナー