<p>你说的</p>
<blockquote>
<p>I need to be able to write my own function to read that file and return the arguments (it's not in a one-argument-per-line format) – </p>
</blockquote>
<p>现有前缀文件处理程序中有一个设置,用于更改读取文件的方式。文件由“private”方法<code>parser._read_args_from_files</code>读取,但它调用一个简单的公共方法,该方法将一行转换为字符串,默认情况下,每行操作一个参数:</p>
<pre><code>def convert_arg_line_to_args(self, arg_line):
return [arg_line]
</code></pre>
<p>它是这样写的,所以你可以很容易地定制它。
<a href="https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.convert_arg_line_to_args" rel="nofollow">https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.convert_arg_line_to_args</a></p>
<blockquote>
<p>A useful override of this method is one that treats each space-separated word as an argument:</p>
</blockquote>
<pre><code>def convert_arg_line_to_args(self, arg_line):
for arg in arg_line.split():
if not arg.strip():
continue
yield arg
</code></pre>
<p>在<code>test_argparse.py</code>unittesting文件中,有一个可供选择的测试用例。</p>
<hr/>
<p>但是如果您仍然希望用参数选项而不是前缀字符触发此读取,那么自定义操作方法是一个好方法。</p>
<p>您可以编写自己的函数,在传递给<code>parser</code>之前处理<code>argv</code>。它可以建立在<code>parser._read_args_from_files</code>上。</p>
<p>所以你可以编写这样的函数:</p>
<pre><code>def read_my_file(argv):
# if there is a '-A' string in argv, replace it, and the following filename
# with the contents of the file (as strings)
# you can adapt code from _read_args_from_files
new_argv = []
for a in argv:
....
# details left to user
return new_argv
</code></pre>
<p>然后使用以下命令调用解析器:</p>
<pre><code>parser.parse_args(read_my_file(sys.argv[1:]))
</code></pre>
<p>是的,这可以包装在一个<code>ArgumentParser</code>子类中。</p>