问题
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