<p>来自<a href="https://hg.python.org/cpython/file/v3.5.2/Lib/argparse.py#l34">the source documentation</a>:</p>
<blockquote>
<p>ArgumentError: The exception raised by ArgumentParser objects when there are errors with the parser's actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.</p>
</blockquote>
<p>构造函数的<code>argument</code>参数是引发异常的<code>Action</code>对象。通常不需要在<code>Action</code>子类之外提升它,并且在对其进行子类化时,不需要显式地提升它;您通常改为提升<code>ValueError</code>(或任何适当的)。</p>
<h3>介于0和1之间的浮点值</h3>
<p>关于您的注释,您只希望接受介于0和1之间的浮点值。为此,您应该使用定义自定义类型的能力。例如,您可以这样做:</p>
<pre><code>def percentFloat (string):
value = float(string)
if value < 0 or value > 1:
raise argparse.ArgumentTypeError('Value has to be between 0 and 1')
return value
parser = argparse.ArgumentParser()
parser.add_argument('test', type=percentFloat)
parser.parse_args()
</code></pre>
<p>注意,这对于非浮点数也是安全的,因为<code>float(string)</code>将为非浮点数引发<code>ValueError</code>,这也会触发<code>argparse</code>模块的无效类型错误。<a href="https://hg.python.org/cpython/file/v3.5.2/Lib/argparse.py#l725">^{<cd8>}</a>只是一种指定自定义错误消息的方法。</p>
<h3>互斥参数</h3>
<p>对于互斥参数,应该使用<a href="http://docs.python.org/3/library/argparse.html#mutual-exclusion">^{<cd9>}</a>。</p>
<h3>参数依赖性</h3>
<p>参数依赖性并不是真正应该由参数<em>解析器</em>来完成的。对于语义细节,您应该自己做:</p>
<pre><code>args = parser.parse_args()
if args.w and not args.p:
parser.error('-p is required when -w is set.')
</code></pre>
<p>您可以使用<a href="https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.error">^{<cd10>}</a>发出自定义错误消息,该消息将中断程序并打印到控制台。</p>
<p>当然,在这种基本情况下,如果可能的话,隐式猜测<code>-p</code>会更有意义。</p>