2016-04-06 75 views
2

這是我第一次使用python的​​,我不知道我在哪裏做錯了。這裏是我的代碼:Python argparse錯誤

#!/usr/bin/env python 

import argparse 

parser = argparse.ArgumentParser(description='Example of argparse') 

parser.add_argument('-i','--input', help='Input fasta file', required=True) 
parser.add_argument('-o','--output', help='Output text file', required=True) 
args = parser.parse_args() 

genes = {} # empty list 

with open(input, 'r') as fh_in: 
     for line in fh_in: 
       line = line.strip() 
       if line[0] == ">": 
         gene_names = line[1:] 
         genes[gene_names] = '' 
       else: 
         genes[gene_names]+=line 


for (name,val) in genes.items(): 
     with open(output, "w") as fh_out: 
       val = len(val) 
       fh_out.write('%s %s' % (name,val)) 
       fh_out.write("\n") 

,當我嘗試運行它,我得到這個錯誤

python get_gene_length.py -i test_in.fa -o test_out.txt 
Traceback (most recent call last): 
    File "get_gene_length.py", line 13, in <module> 
    with open(input, 'r') as fh_in: 
TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found 

誰能幫助我明白我應該在哪裏修改腳本,使其工作?

回答

2

參數被解析成命名空間對象args。您需要使用args.input而不是input,這是一個已經引用內置函數的名稱。

類似於稍後打開輸出文件。

+0

它將輸入更改爲args.input並類似地輸出後工作。這非常有幫助! – upendra

2

您從不在任何地方定義變量input,但在代碼中使用它。但是,input是內置python函數的名稱,導致出現此錯誤而不是NameError