• <legend id='68uCM'><style id='68uCM'><dir id='68uCM'><q id='68uCM'></q></dir></style></legend>

    <small id='68uCM'></small><noframes id='68uCM'>

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

        • <bdo id='68uCM'></bdo><ul id='68uCM'></ul>
      1. <tfoot id='68uCM'></tfoot>

        使用Python单击命令调用带有可变参数的类方法

        Use Python click command to invoke a class method with variadic arguments(使用Python单击命令调用带有可变参数的类方法)
        <i id='rEab8'><tr id='rEab8'><dt id='rEab8'><q id='rEab8'><span id='rEab8'><b id='rEab8'><form id='rEab8'><ins id='rEab8'></ins><ul id='rEab8'></ul><sub id='rEab8'></sub></form><legend id='rEab8'></legend><bdo id='rEab8'><pre id='rEab8'><center id='rEab8'></center></pre></bdo></b><th id='rEab8'></th></span></q></dt></tr></i><div id='rEab8'><tfoot id='rEab8'></tfoot><dl id='rEab8'><fieldset id='rEab8'></fieldset></dl></div>
        <tfoot id='rEab8'></tfoot>
            • <legend id='rEab8'><style id='rEab8'><dir id='rEab8'><q id='rEab8'></q></dir></style></legend>

              1. <small id='rEab8'></small><noframes id='rEab8'>

                  <tbody id='rEab8'></tbody>
                  <bdo id='rEab8'></bdo><ul id='rEab8'></ul>

                  本文介绍了使用Python单击命令调用带有可变参数的类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我有一个使用以前未知数量的参数进行初始化的类,我希望使用Python的click包在CLI上完成初始化。我的问题是我无法将其初始化并运行click命令:

                  $ python mycode.py arg1 arg2 ... argN click_command
                  
                  设置定义数量的参数(如nargs=5)可以解决缺少命令的问题,但我必须在命令之前输入5个参数。使用像nargs=-1这样的可变参数,click不会将click_command识别为命令。

                  如何输入n个参数,然后使用click运行该命令?

                  import click
                  
                  class Foo(object):
                      def __init__(self, *args):
                          self.args = args
                  
                      def log(self):
                          print('self.args:', self.args)
                  
                  pass_foo = click.make_pass_decorator(Foo)
                  
                  @click.group()
                  @click.argument('myargs', nargs=-1)
                  @click.pass_context
                  def main(ctx, myargs):
                      ctx.obj = Foo(myargs)
                      print("arguments: ", myargs)
                  
                  @main.command()
                  @pass_foo
                  def log(foo):
                      foo.log()
                  
                  main()
                  

                  我希望在将n个参数传递给我的Foo()类之后能够运行click命令,这样我就可以初始化它并将其log()方法作为CLI命令运行,但是输出是:

                  错误:缺少命令

                  推荐答案

                  我不完全确定您尝试做的事情是否是解决此问题的最佳方法。我认为将变量参数放在命令后面会更符合逻辑,而且肯定更符合单击的工作方式。但是,您可以使用以下命令执行您想要的操作:

                  自定义类:

                  class CommandAfterArgs(click.Group):
                  
                      def parse_args(self, ctx, args):
                          parsed_args = super(CommandAfterArgs, self).parse_args(ctx, args)
                          possible_command = ctx.params['myargs'][-1]
                          if possible_command in self.commands:
                              ctx.protected_args = [possible_command]
                              ctx.params['myargs'] = ctx.params['myargs'][:-1]
                  
                          elif possible_command in ('-h', '--help'):
                              if len(ctx.params['myargs']) > 1 and 
                                      ctx.params['myargs'][-2] in self.commands:
                                  ctx.protected_args = [ctx.params['myargs'][-2]]
                                  parsed_args = ['--help']
                                  ctx.params['myargs'] = ctx.params['myargs'][:-2]
                                  ctx.args = [possible_command]
                  
                          return parsed_args
                  

                  使用自定义类:

                  然后要使用自定义类,请将其作为cls参数传递给组装饰器,如下所示:

                  @click.group(cls=CommandAfterArgs)
                  @click.argument('myargs', nargs=-1)
                  def main(myargs):
                      ...
                  

                  测试代码:

                  import click
                  
                  class Foo(object):
                      def __init__(self, *args):
                          self.args = args
                  
                      def log(self):
                          print('self.args:', self.args)
                  
                  
                  pass_foo = click.make_pass_decorator(Foo)
                  
                  
                  @click.group(cls=CommandAfterArgs)
                  @click.argument('myargs', nargs=-1)
                  @click.pass_context
                  def main(ctx, myargs):
                      ctx.obj = Foo(*myargs)
                      print("arguments: ", myargs)
                  
                  
                  @main.command()
                  @pass_foo
                  def log(foo):
                      foo.log()
                  
                  
                  if __name__ == "__main__":
                      commands = (
                          'arg1 arg2 log',
                          'log --help',
                          '--help',
                      )
                  
                      import sys, time
                  
                      time.sleep(1)
                      print('Click Version: {}'.format(click.__version__))
                      print('Python Version: {}'.format(sys.version))
                      for cmd in commands:
                          try:
                              time.sleep(0.1)
                              print('-----------')
                              print('> ' + cmd)
                              time.sleep(0.1)
                              main(cmd.split())
                  
                          except BaseException as exc:
                              if str(exc) != '0' and 
                                      not isinstance(exc, (click.ClickException, SystemExit)):
                                  raise
                  

                  结果:

                  Click Version: 6.7
                  Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
                  -----------
                  > arg1 arg2 log
                  arguments:  ('arg1', 'arg2')
                  self.args: ('arg1', 'arg2')
                  -----------
                  > log --help
                  arguments:  ()
                  Usage: test.py log [OPTIONS]
                  
                  Options:
                    --help  Show this message and exit.
                  -----------
                  > --help
                  Usage: test.py [OPTIONS] [MYARGS]... COMMAND [ARGS]...
                  
                  Options:
                    --help  Show this message and exit.
                  
                  Commands:
                    log
                  

                  这篇关于使用Python单击命令调用带有可变参数的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

                  相关文档推荐

                  groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
                  Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
                  Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
                  Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
                  Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
                  Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)

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

                    <tbody id='muFWf'></tbody>

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

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