从命令行python获取参数

Moh*_*hit 2 python

我试图从命令行获取三个参数:

-o (for outputfile) -k (number of clusters) -l (data to be clustered)
Run Code Online (Sandbox Code Playgroud)

所以我写了这个.

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
Run Code Online (Sandbox Code Playgroud)

一切正常,除了-l标志,所以如果我的命令行命令是这样的:

$python foo.py -o foo.txt -k 2 -l 2
Run Code Online (Sandbox Code Playgroud)

和打印argv打印

ARGV      : ['-o', 'demo.txt', '-k', '2', '-l', '2']
Run Code Online (Sandbox Code Playgroud)

但选项是:

options  [('-o', 'demo.txt'), ('-k', '2'), ('-l', '')]
Run Code Online (Sandbox Code Playgroud)

请注意,"l"字段中没有任何内容被解析.我在做错了吗?谢谢

unu*_*tbu 9

getopt是一个相当古老的模块.如果你有Python2.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)
Run Code Online (Sandbox Code Playgroud)

赛跑

test.py -o foo.txt -k 2 -l 2
Run Code Online (Sandbox Code Playgroud)

产量

Namespace(k='2', l='2', o='foo.txt')
Run Code Online (Sandbox Code Playgroud)