Python argparse 错误

Python argparse error

这是我第一次使用 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

任何人都可以帮助我了解我应该在哪里更改脚本以使其工作吗?

参数被解析为命名空间对象args。您需要使用 args.input 而不是 input,这是一个已经引用内置函数的名称。

与稍后打开输出文件类似。

您永远不会在任何地方定义变量 input,然后在您的代码中使用它。但是,input 是内置 python 函数的名称,导致此错误而不是 NameError