• <bdo id='DtRel'></bdo><ul id='DtRel'></ul>
    <legend id='DtRel'><style id='DtRel'><dir id='DtRel'><q id='DtRel'></q></dir></style></legend><tfoot id='DtRel'></tfoot>

    1. <i id='DtRel'><tr id='DtRel'><dt id='DtRel'><q id='DtRel'><span id='DtRel'><b id='DtRel'><form id='DtRel'><ins id='DtRel'></ins><ul id='DtRel'></ul><sub id='DtRel'></sub></form><legend id='DtRel'></legend><bdo id='DtRel'><pre id='DtRel'><center id='DtRel'></center></pre></bdo></b><th id='DtRel'></th></span></q></dt></tr></i><div id='DtRel'><tfoot id='DtRel'></tfoot><dl id='DtRel'><fieldset id='DtRel'></fieldset></dl></div>

        <small id='DtRel'></small><noframes id='DtRel'>

      1. python,argparse:在指定另一个输入参数时启用输入参数

        python, argparse: enable input parameter when another one has been specified(python,argparse:在指定另一个输入参数时启用输入参数)
        <legend id='OkHHP'><style id='OkHHP'><dir id='OkHHP'><q id='OkHHP'></q></dir></style></legend>
          <bdo id='OkHHP'></bdo><ul id='OkHHP'></ul>

        • <small id='OkHHP'></small><noframes id='OkHHP'>

          • <i id='OkHHP'><tr id='OkHHP'><dt id='OkHHP'><q id='OkHHP'><span id='OkHHP'><b id='OkHHP'><form id='OkHHP'><ins id='OkHHP'></ins><ul id='OkHHP'></ul><sub id='OkHHP'></sub></form><legend id='OkHHP'></legend><bdo id='OkHHP'><pre id='OkHHP'><center id='OkHHP'></center></pre></bdo></b><th id='OkHHP'></th></span></q></dt></tr></i><div id='OkHHP'><tfoot id='OkHHP'></tfoot><dl id='OkHHP'><fieldset id='OkHHP'></fieldset></dl></div>

                    <tbody id='OkHHP'></tbody>
                1. <tfoot id='OkHHP'></tfoot>

                  本文介绍了python,argparse:在指定另一个输入参数时启用输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  在我的 python 脚本中,我希望能够在指定另一个可选参数时使用可选输入参数.示例:

                  In my python script, I want to be able to use an optional input parameter only when another optional parameter has been specified. Example:

                  $ python myScript.py --parameter1 value1
                  $ python myScript.py --parameter1 value1 --parameter2 value2
                  

                  但不是:

                  $ python myScript.py --parameter2 value2
                  

                  如何使用 argparse 执行此操作?

                  How do I do this with argparse?

                  谢谢!

                  推荐答案

                  使用自定义操作:

                  import argparse
                  
                  foo_default=None    
                  
                  class BarAction(argparse.Action):
                      def __call__(self,parser,namespace,values,option_string=None):
                          didfoo=getattr(namespace,'foo',foo_default)
                          if(didfoo == foo_default):
                              parser.error( "foo before bar!")
                          else:
                              setattr(namespace,self.dest,values)
                  
                  parser=argparse.ArgumentParser()
                  parser.add_argument('--foo',default=foo_default)
                  parser.add_argument('--bar',action=BarAction,help="Only use this if --foo is set")
                  
                  #testing.
                  print parser.parse_args('--foo baz'.split())
                  print parser.parse_args('--foo baz --bar cat'.split())
                  print parser.parse_args('--bar dog'.split())
                  

                  如果您可以依赖 argparse 的一些未记录的行为,这甚至可以以更易于维护的方式完成:

                  This can even be done in a little easier to maintain way if you're OK with relying on some undocumented behavior of argparse:

                  import argparse
                  
                  parser=argparse.ArgumentParser()
                  first_action=parser.add_argument('--foo',dest='cat',default=None)
                  
                  class BarAction(argparse.Action):
                      def __call__(self,parser,namespace,values,option_string=None):
                          didfoo=getattr(namespace,first_action.dest,first_action.default)
                          if(didfoo == first_action.default):
                              parser.error( "foo before bar!")
                          else:
                              setattr(namespace,self.dest,values)
                  
                  parser.add_argument('--bar',action=BarAction,
                                      help="Only use this if --foo is set")
                  
                  #testing.
                  print parser.parse_args('--foo baz'.split())
                  print parser.parse_args('--foo baz --bar cat'.split())
                  print parser.parse_args('--bar dog'.split())
                  

                  在这个例子中,我们得到 foo 的默认值,它的目的地来自 add_argument 返回的动作对象(add_argument 的返回值没有记录在我能找到的任何地方).这仍然有点脆弱(例如,如果您想为 --foo 参数指定 type= 关键字).

                  In this example, we get the default for foo and it's destination from the action object returned by add_argument (add_argument's return value isn't documented anywhere that I can find). This is still a little fragile (If you want to specify a type= keyword to the --foo argument for example).

                  最后,可以在解析前检查sys.argv.

                  Finally, you can check sys.argv before parsing.

                  import sys
                  if ("--parameter2" in sys.argv) and ("--parameter1" not in sys.argv):
                      parser.error("parameter1 must be given if parameter2 is given")
                  

                  如果 --parameter1 也可以由 --p1 触发,这将变得有点棘手,但你明白了.然后你可以使用

                  This gets a little more tricky if --parameter1 could also be triggered by --p1, but you get the idea. Then you could use

                  if (set(sys.argv).intersection(('--p2',...)) and 
                      not set(sys.argv).intersection(('--p1',...)))
                  

                  这里的优点是它不需要任何特定的顺序.(--p2 不需要在命令行上跟随 --p1).而且,和以前一样,您可以通过 parser.add_argument(...) 返回的 option_strings 属性获取将触发特定操作的命令字符串列表.例如

                  The advantage here is that it doesn't require any particular order. (--p2 doesn't need to follow --p1 on the commandline). And, as before, you can get the list of command strings that will trigger your particular action via the option_strings attribute returned by parser.add_argument(...). e.g.

                  import argparse
                  import sys   
                  parser=argparse.ArgumentParser()
                  action1=parser.add_argument('--foo')
                  action2=parser.add_argument('--bar',
                                              help="Only use this if --foo is set")
                  
                  argv=set(sys.argv)
                  if (( argv & set(action2.option_strings) ) and 
                        not ( argv & set(action1.option_strings) )):
                                  #^ set intersection
                       parser.error(' or '.join(action1.option_strings)+
                                    ' must be given with '+
                                    ' or '.join(action2.option_strings))
                  

                  这篇关于python,argparse:在指定另一个输入参数时启用输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Adding config modes to Plotly.Py offline - modebar(将配置模式添加到 Plotly.Py 离线 - 模式栏)
                  Plotly: How to style a plotly figure so that it doesn#39;t display gaps for missing dates?(Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙?)
                  python save plotly plot to local file and insert into html(python将绘图保存到本地文件并插入到html中)
                  Plotly: What color cycle does plotly express follow?(情节:情节表达遵循什么颜色循环?)
                  How to save plotly express plot into a html or static image file?(如何将情节表达图保存到 html 或静态图像文件中?)
                  Plotly: How to make a line plot from a pandas dataframe with a long or wide format?(Plotly:如何使用长格式或宽格式的 pandas 数据框制作线图?)
                  <legend id='Asvso'><style id='Asvso'><dir id='Asvso'><q id='Asvso'></q></dir></style></legend>
                    <tbody id='Asvso'></tbody>

                  • <bdo id='Asvso'></bdo><ul id='Asvso'></ul>
                          <i id='Asvso'><tr id='Asvso'><dt id='Asvso'><q id='Asvso'><span id='Asvso'><b id='Asvso'><form id='Asvso'><ins id='Asvso'></ins><ul id='Asvso'></ul><sub id='Asvso'></sub></form><legend id='Asvso'></legend><bdo id='Asvso'><pre id='Asvso'><center id='Asvso'></center></pre></bdo></b><th id='Asvso'></th></span></q></dt></tr></i><div id='Asvso'><tfoot id='Asvso'></tfoot><dl id='Asvso'><fieldset id='Asvso'></fieldset></dl></div>

                          <small id='Asvso'></small><noframes id='Asvso'>

                          <tfoot id='Asvso'></tfoot>