带有cemen的多个非标记参数

2024-06-15 02:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在cement上编写一个python命令行界面工具。 水泥对于标准参数的解析非常有效。但是,我希望能够添加特定数量的未标记参数。让我解释一下。在

典型的命令行工具:

cmd subcmd -flag -stored=flag

现在,假设我想添加一些不带标志的参数,例如cd是如何工作的

^{pr2}$

my/dir是没有标志的参数。在

有没有用水泥做这个?在

我的应用程序示例:

# define application controllers
class MyAppBaseController(controller.CementBaseController):
    class Meta:
        label = 'base'
        interface = controller.IController
        description = "My Application Does Amazing Things"
        arguments = [
            (['--base-opt'], dict(help="option under base controller")),
            ]

    @controller.expose(help="base controller default command", hide=True)
    def default(self):
        self.app.args.parse_args(['--help'])
        print "Inside MyAppBaseController.default()"

    @controller.expose(help="another base controller command")
    def command1(self):
        print "Inside MyAppBaseController.command1()"

所以假设我想做myapp command1 some/dir some_string

有没有办法来分析这些论点?在


Tags: 工具命令行selfdefaultbase参数标志dir
2条回答

正如在Cementdoc中所说:“Cement定义了一个名为IArgument的参数接口,以及实现该接口的默认ArgParseArgumentHandler。此处理程序构建在Python标准库中包含的ArgParse模块之上。”

您可以通过告诉argparse模块使用参数列表中的一个参数并将其存储在pargs列表的name属性中来实现这一点。在

# define application controllers
class MyAppBaseController(controller.CementBaseController):
    class Meta:
        label = 'base'
        interface = controller.IController
        description = "My Application Does Amazing Things"
        arguments = [
            ([' base-opt'], dict(help="option under base controller")),
        ]

    @controller.expose(help="base controller default command", hide=True)
    def default(self):
        self.app.args.parse_args([' help'])
        print "Inside MyAppBaseController.default()"

    @controller.expose(
        help="another base controller command",
        arguments=[
            (['path'],
             dict(type=str, metavar='PATH', nargs='?', action='store', default='.')),
            (['string'],
             dict(type=str, metavar='STRING', nargs='?', action='store', default='')),
        ]
    )
    def command1(self):
        print "Inside MyAppBaseController.command1() path: %s string: %s" % (self.app.pargs.name, self.app.pargs.string)

您可以在ArgParse中使用可选的位置参数来执行此操作。实际上,GitHub中有一个问题有待进一步研究:

https://github.com/datafolklabs/cement/issues/256

基本上,如果您希望“command1”来处理操作,那么“some/dir some\u string”将是位置参数。您可以将以下内容添加到MyAppBaseController.Meta.arguments公司名称:

( ['extra_arguments'], dict(action='store', nargs='*') ),

然后在command函数中访问这些参数:

if self.app.pargs.extra_arguments: print "Extra Argument 0: %s" % self.app.pargs.extra_arguments[0] print "Extra Argument 1: %s" % self.app.pargs.extra_arguments[1]

相关问题 更多 >