<p><code>usage</code>行显示错误:</p>
<pre><code>usage: jsh.py [-h] {install,call,list,log,restore} ... [md_script]
</code></pre>
<p>你需要使用类似</p>
<pre><code>jsh.py install md_script
</code></pre>
<p>你指定了subparser,所以你必须给它一个subparser名称。你知道吗</p>
<hr/>
<p>从<code>usage</code>看起来还创建了代码中没有显示的其他子parser、<code>call</code>、<code>list</code>等。你知道吗</p>
<p>在创建子parser之后,还可以定义位置参数。这就是<code>[md_script]</code>的来源。在创建大量<code>nargs='?'</code>位置(包括<code>install</code>子parser的参数)时要小心。这可能会让你的用户感到困惑。事实上,这似乎让你困惑。记住<code>subparser</code>实际上是一个位置参数(需要一个字符串)。你知道吗</p>
<p>我建议在创建一个如此复杂的解析器之前,先试用一个更简单的解析器。你知道吗</p>
<hr/>
<p>因此,从您的注释和示例中,我看到您的目标是让用户命名一个模块,这样您的脚本就可以以某种方式调用它。因为用这些名字填充子帕瑟是有意义的。你知道吗</p>
<p>我想知道为什么还要创建一个同名的可选位置参数:</p>
<pre><code>module_pars = subparsers.add_parser(element, help = 'Modules from tools')
module_pars.add_argument(element, nargs='?', help=element+' description')
</code></pre>
<p>这是因为您使用属性的存在作为调用此子parser的证据吗?你知道吗</p>
<pre><code>elif element in args:
do_some_md_script_stuff
</code></pre>
<p><code>argparse</code>文档还有一些其他的想法。你知道吗</p>
<blockquote>
<p>One particularly effective way of handling sub-commands is to combine the use of the add_subparsers() method with calls to set_defaults() so that each subparser knows which Python function it should execute. </p>
</blockquote>
<p>以及</p>
<blockquote>
<p>However, if it is necessary to check the name of the subparser that was invoked, the dest keyword argument to the add_subparsers() call will work:</p>
</blockquote>
<p>这些避免了一个“?”的混乱位置参数,使您可以使用子参数获取真实信息。你知道吗</p>
<pre><code>subparsers = parser.add_subparsers(dest='module')
....
for element in name_arg:
# module_pars = 'parser_'+element # this does nothing
module_pars = subparsers.add_parser(element, help = 'Modules from tools')
module_pars.set_defaults(func = do_some_md_script_stuff)
# or module_pars.set_default(element='I am here')
module_pars.add_argument('real_argument')
</code></pre>
<p>现在您可以检查:</p>
<pre><code>if args.module='md_script':
do_some_md_script_stuff(args)
</code></pre>
<p>或者</p>
<pre><code>if hasattr(args, 'func'):
func(args)
</code></pre>
<p>使用替代方法<code>set_defaults</code>,您的原始测试应该仍然有效:</p>
<pre><code>if element in args:
do_some_md_script_stuff
</code></pre>