【问题标题】:getopt not quite working, what am I doing wrong?getopt 不太好用,我做错了什么?
【发布时间】:2017-04-02 15:00:26
【问题描述】:

我不确定为什么下面的代码不起作用 - 我收到错误消息

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))

【问题讨论】:

    标签: python bioinformatics vcf-variant-call-format


    【解决方案1】:

    问题是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 参数检索到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 2011-06-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2021-04-14
      • 2021-04-19
      • 2017-03-13
      相关资源
      最近更新 更多