Argparse模式,其中输入文件名通过命令行上的文件或文件名列表给出 [英] Argparse pattern where input filenames are given through a file or a list of filenames on the command line
问题描述
argparse是否支持以下模式:
Does argparse support a pattern such as:
foo.py {-f list_of_filenames.txt|file [file ...]}
目前,我使用以下argparse定义实现了这一点:
I achieve this at the moment with the following argparse definition:
parser = argparse.ArgumentParser()
parser.add_argument("--file", "-f")
parser.add_argument("files", nargs="*")
并在我的代码中执行互斥+必需的检查,而不是让argparse进行检查.
and performing the mutual exclusivity + required check in my code rather than letting argparse do the check.
argparse可以处理这种模式吗?
Can argparse handle a pattern of this sort?
推荐答案
argparse
采用fromfile-prefix-chars
参数
https://docs.python.org/3.4/library/argparse.html#fromfile-prefix-chars
因此,如果文件名在文件中,则每行一个名称
So if the filenames are in a file, one name per line
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('files', nargs='*')
>>> parser.parse_args(['@filenames.txt'])
将从文件中读取名称.就像您在命令行中输入它们一样,它会将它们置于sys.argv
列表中.
Will read the names from the file. It puts them in the sys.argv
list just as though you had entered them on the command line.
这篇关于Argparse模式,其中输入文件名通过命令行上的文件或文件名列表给出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!