gpt4 book ai didi

Python argparse 错误

转载 作者:行者123 更新时间:2023-11-28 22:37:32 25 4
gpt4 key购买 nike

这是我第一次使用 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,这是一个已经引用内置函数的名称。

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

关于Python argparse 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com