簡體   English   中英

從命令行python獲取參數

[英]getting arguments from command line 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”字段中沒有任何內容被解析。 我在做錯了嗎? 謝謝

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)

賽跑

test.py -o foo.txt -k 2 -l 2

產量

Namespace(k='2', l='2', o='foo.txt')

這是因為在你的shortopts參數:'o:v:k:l'中,“l”后面跟一個冒號“:”

既然不是,則將“2”放入余數變量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM