我正在编写一个程序,对文件内容执行不同的功能。目前文件存储在变量中,然后作为参数传递给每个函数:
file = "path/to/file"
我希望做的是允许用户使用我已设置好的命令行函数输入路径,并将其传递给我的函数。然而,我不确定如何将其实现到这里的命令行文件中。
cli.py
import os, argparse
from . import parse
def validate_file(filename):
if not os.path.exists(filename):
raise argparse.ArgumentTypeError("{0} does not exist".format(filename))
return filename
def dump(filename):
for record in parse.uniprot_records(filename):
print(record)
...
(more function definitions)
...
def cli():
# Create a new parser
parser = argparse.ArgumentParser(description="UniProt Analysis")
# Input file
parser.add_argument("-i", "--input", dest="filename", type=validate_file, required=True, help="enter input file", metavar="FILE")
subparsers = parser.add_subparsers(help="Enter one of the arguments to run function")
# Add subparsers
subparsers.add_parser("dump", help="prints all records").set_defaults(func=dump)
# Parse the command line
args = parser.parse_args()
print(type(args.filename))
# Take the func argument, which points to our function and call it
args.func(args)
我希望能够通过命令行传递文件,并执行想要的功能,例如:
pipenv run python program.py path/to/file dump
编辑:已向解析器添加参数以获取用户的输入文件。该文件随后被传递到dump
函数中,并由此函数传递给以下函数:
parse.py
import gzip
from Bio import SeqIO
def uniprot_records(f):
records = []
handle = gzip.open(f)
for record in SeqIO.parse(handle, "uniprot-xml"):
records.append(record)
return records
我的主函数在一个单独的模块中,它只是调用了cli
函数。当我尝试运行pipenv run python uniplot.py -i path/to/file dump
时,它会给出以下错误:
文件 "/Users/john/workspace/practical-2/uniplot/parse.py",第 24 行,函数 uniprot_records handle = gzip.open(file_location)
文件 "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/gzip.py",第 57 行,函数 open raise TypeError("filename must be a str or bytes object, or a file")
类型错误:文件名必须是字符串或字节对象,或者是文件。
dump
应该在使用 gzip 解压后打印出给定文件的全部内容。
filename
的? - PyPinguvalidate_file(filename)
,因为它需要一个参数。此时我无法传递任何东西。顺便说一下,谢谢你! - Johnboy