Argparse pattern where input filenames are given through a file or a list of filenames on the command line

两盒软妹~` 提交于 2019-12-24 21:42:37

问题


Does argparse support a pattern such as:

foo.py {-f list_of_filenames.txt|file [file ...]}

I achieve this at the moment with the following argparse definition:

parser = argparse.ArgumentParser()
parser.add_argument("--file", "-f")
parser.add_argument("files", nargs="*")

and performing the mutual exclusivity + required check in my code rather than letting argparse do the check.

Can argparse handle a pattern of this sort?


回答1:


argparse takes fromfile-prefix-chars parameter

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'])

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.



来源:https://stackoverflow.com/questions/30491244/argparse-pattern-where-input-filenames-are-given-through-a-file-or-a-list-of-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!