跳至主要内容

通过反射将对象转换为OptionParser实例

项目描述

通过反射将对象转换为OptionParser实例

概述

命令行界面使用子命令(例如)是一种常见的模式

hg commit -m ‘foo bar’ git push origin master

CommandParser通过给定类的反射来实现这一点。当使用一个类时,CommandParser使用inspect模块提取类中每个方法的必需和可选参数,这些参数被转换为子命令,并从它们中创建一个OptionParser实例。然后,使用%prog help将显示所有子命令,而使用%prog help <subcommand>将提供关于所选子命令的帮助。以下划线(_)开头的方法定义将被忽略。这为将API类转换为命令行程序提供了一种简单的方法

class Foo(object):
  """silly class that does nothing"""
  def __init__(self): pass
  def foo(self, value):
    print "The value is %s" % value
  def bar(self, fleem, verbose=False):
    """
    The good ole `bar` command
    - fleem: you know, that thing fleem
    - verbose: whether to print out more things or not
    """
    if verbose:
      print "You gave fleem=%s" % fleem
    return fleem * 2

import commandparser
parser = commandparser.CommandParser(Foo)
parser.invoke()

(From http://k0s.org/hg/CommandParser/file/tip/tests/simpleexample.py )

示例调用

(paint)│./simpleexample.py help
Usage: simpleexample.py [options] command [command-options]

silly class that does nothing

Options:
  -h, --help  show this help message and exit

Commands:
  bar   The good ole `bar` command
  foo
  help  print help for a given command
(paint)│./simpleexample.py foo
Usage: simpleexample.py foo <value>

simpleexample.py: error: Not enough arguments given
(paint)│./simpleexample.py foo 4
The value is 4
(paint)│./simpleexample.py bar blah
blahblah

对于可选参数,将从函数签名中检查默认值的类型。目前,必需参数都是字符串,这显然是一个缺点。

类的文档字符串用于%prog --help(以及%prog help,两者相同)。方法文档字符串(包括全局选项的__init__方法)用于子命令帮助。如果将参数以上述形式(- <argument> : <something about the argument)列在文档字符串中,则这些将用于提供单个选项的帮助。否则,这些将被保留为空白。

对于简单直接的情况,直接将您的类传递给CommandParser构造函数可能就足够了。对于更复杂的情况,建议创建一个新的类(通过子类化或从头开始,根据需要),使其更适合CommandParser,而不是修改(例如)API类以适应CommandParser的期望。这样可以在不牺牲API类的情况下使用面向对象的子命令接口,并且如果可以子类化,那么实际上不需要编写太多额外的代码。

有关测试和示例,请参阅http://k0s.org/hg/CommandParser/file/tip/tests

参考


Jeff Hammel

http://k0s.org/hg/CommandParser

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

CommandParser-0.3.tar.gz (5.5 kB 查看哈希值)

上传时间

由以下支持