#!/usr/bin/env python
#
# Name: getopt-template.py
#
import sys
import getopt
def usage_exit():
sys.stderr.write("Usage: getopt-template.py [-a] [-d dir] item1 item2 ...\n")
sys.exit(1)
#
# Options
#
print sys.argv ####DEBUG
try:
opts, argv = getopt.getopt(sys.argv[1:], "ad:h")
except getopt.GetoptError:
usage_exit()
(opt_a, opt_d) = (0, None)
for (opt, optarg) in opts:
if opt == "-a":
opt_a = opt_a + 1
elif opt == "-d":
opt_d = optarg
elif opt == "-h":
usage_exit()
else:
usage_exit()
argc = len(argv)
print "argc =", argc ####DEBUG
print argv ####DEBUG
print "opt_a =", opt_a ####DEBUG
print "opt_d =", opt_d ####DEBUG
# ./getopt-template.py -aa -d dir item1 item2 ['./getopt-template.py', '-aa', '-d', 'dir', 'item1', 'item2'] argc = 2 ['item1', 'item2'] opt_a = 2 opt_d = dir # ./getopt-template.py item1 -d dir ['./getopt-template.py', 'item1', '-d', 'dir'] argc = 3 ['item1', '-d', 'dir'] opt_a = 0 opt_d = Nonegetopt.getopt の場合、上記のように -d dir を後置すると、期待したように解釈されません。
getopt.gnu_getopt を使えば後置が可能なのですが、Python 2.x 系で追加されたもののようで、古い Python 1.x 系では使えないようです。
参考
perl でオプション解析(getoptコマンド編)
0 件のコメント:
コメントを投稿