2017-04-02 33 views
0

我不知道爲什麼下面的代碼不工作 - 我得到的錯誤getopt不太能工作,我做錯了什麼?

NameError: name 'group1' is not defined. 

的代碼能正常工作之前,我試圖用getopt的..我試圖解析命令行輸入,以便例如,如果我把

python -q file1 file2 -r file3 file4 

file1和file2成爲我的第一個循環輸入爲'group1'。

import sys 
import csv 
import vcf 
import getopt 
#set up the args 
try: 
    opts, args = getopt.getopt(sys.argv[1:], 'q:r:h', ['query', 'reference', 'help']) 
except getopt.GetoptError as err: 
    print str(err) 
    sys.exit(2) 

for opt, arg in opts: 
    if opt in ('-h', '--help'): 
     print "Usage python -q [query files] -r [reference files]" 
     print "-h this help message" 
    elif opt in ('-q', '--query'): 
     group1 = arg 
    elif opt in ('-r', '--reference'): 
     group2 = arg 
    else: 
     print"check your args" 

#extract core snps from query file, saving these to the set universal_snps 
snps = [] 
outfile = sys.argv[1] 
for variants in group1: 

    vcf_reader = vcf.Reader(open(variants)) 

回答

0

的問題是,group1 = arg從未運行,因此當它以後到達for variants in group1:,沒有定義的變量。

這是因爲您錯誤地調用了函數來定義選項。當你有行:

opts, args = getopt.getopt(sys.argv[1:], 'q:r:h', ['query', 'reference', 'help']) 

存在與標誌(即-q file1-r file3參數指定之前任何其他參數的要求。因此,如果你要調用該函數爲:

python <scriptName> -q file1 -r file3 file2 file4 

您將有預期的行爲。這是因爲沒有相關的標誌所有參數顯示在通話結束(和將通過args參數可檢索

相關問題