èµ·åæã®å¼æ°(args)解æ
optparse
ã¢ã¸ã¥ã¼ã«ã使ã£ã¦èµ·åæã®å¼æ°ã®è§£æãè¡ãåºæ¬ã
[argsOp.py]
#!/bin/env python # -*- coding: shift_jis -*- import sys from optparse import OptionParser #å¼æ°ã®è¨å® parser = OptionParser() parser.add_option("-f", "--file", dest="fileName",help="ãã¡ã¤ã«åæå®", metavar="FILE") parser.add_option("-v", action="store_true", dest="ver" ) parser.add_option("-q", action="store_false", dest="ver" ) #å¼æ°ã®åå¾ (options, args) = parser.parse_args() #åå¾ããå¼æ°ã®è¡¨ç¤º print "fileName:" , options.fileName print "ver :" , options.ver print "args :" , args
è²ã ãªå¼æ°ãä¸ãªããèµ·åãã¦è©¦ãã¦ã¿ã
:\Python23jp>argsOp.py fileName: None ver : None args : C:\Python23jp>argsOp.py -h usage: argsOp.py [options] options: -h, --help show this help message and exit -fFILE, --file=FILE ãã¡ã¤ã«åæå® -v -q C:\Python23jp>argsOp.py -f test.txt fileName: test.txt ver : None args : C:\Python23jp>argsOp.py -q -ftest.txt fileName: test.txt ver : False args : C:\Python23jp>argsOp.py -ftest.txt -v fileName: test.txt ver : True args : C:\Python23jp>argsOp.py -ftest.txt -v aaa fileName: test.txt ver : None args : ['aaa'] C:\Python23jp>argsOp.py -v aaa -ftest.txt ccc bbb fileName: test.txt ver : True args : ['aaa', 'ccc', 'bbb']
å¼æ°ãè¨å®ããæã®ãã¼ã¿ããã¨ã«-h,-helpã¯èªåçã«ä½ã£ã¦ãããããã