从命令行获取Python参数
我想从命令行获取三个参数:
-o (for outputfile) -k (number of clusters) -l (data to be clustered)
所以我写了这个。
def get_input():
print 'ARGV :', sys.argv[1:]
options, remainder = getopt.getopt(sys.argv[1:], 'o:v:k:l', ['output=',
'verbose',
'k_clust=',
'limit='])
print "options ",options
file_flag , k_flag, count_flag = False, False,False
for opt, arg in options:
print opt
if opt in ('-o', '--output'):
print "here ", opt, arg
output_filename = arg
o_flag = True
if opt in ('-v', '--verbose'):
verbose = True
if opt == '--version':
version = arg
if opt in ('-k','--k_clust'):
print "here", opt, arg
k_clust = arg
k_flag = True
if opt in ('-l','--limit'):
kcount = arg
assert kcount!=0 and kcount!= ''
print "limit ", arg
count_flag = True
if k_flag == False:
sys.exit(" no cluster specified, will be exiting now")
if o_flag == False:
print "using default outfile name ",output_filename
if count_flag == False:
kcount = 10000000
return output_filename, k_clust,kcount
除了 -l 这个选项,其他都运行得很好。如果我的命令行是这样的:
$python foo.py -o foo.txt -k 2 -l 2
然后打印 argv 的结果是
ARGV : ['-o', 'demo.txt', '-k', '2', '-l', '2']
但是选项是:
options [('-o', 'demo.txt'), ('-k', '2'), ('-l', '')]
注意到“l”这个字段没有被解析到。请问我哪里出错了?谢谢。
2 个回答
4
这是因为在你的短选项参数中:'o:v:k:l',字母 "l" 后面需要加一个冒号 ":"
由于没有加冒号,所以 "2" 被放到了剩余变量里。
9
getopt
是一个比较老的模块。如果你使用的是 Python 2.7,建议使用 argparse 这个模块。
如果你用的是稍微旧一点的 Python 版本(大于等于 2.3),你仍然可以通过 安装 argparse 来使用它:
可以通过
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-o', help = 'outputfile')
parser.add_argument('-k', help = 'number of clusters')
parser.add_argument('-l', help = 'data to be clustered')
args=parser.parse_args()
print(args)
来运行
test.py -o foo.txt -k 2 -l 2
这样会得到
Namespace(k='2', l='2', o='foo.txt')