【问题标题】:Rename python click argument重命名python点击参数
【发布时间】:2022-01-26 05:29:48
【问题描述】:

我有这段代码:

import click

@click.option('--delete_thing', help="Delete some things columns.", default=False)
def cmd_do_this(delete_thing=False):
    print "I deleted the thing."

我想重命名--delete-thing 中的选项变量。但是 python 不允许在变量名中使用破折号。有没有办法编写这种代码?

import click

@click.option('--delete-thing', help="Delete some things columns.", default=False, store_variable=delete_thing)
    def cmd_do_this(delete_thing=False):
        print "I deleted the thing."

所以delete_thing 将被设置为delete-thing 的值

【问题讨论】:

    标签: python command-line-arguments python-click


    【解决方案1】:

    默认情况下,click 会智能地将选项内命令行连字符映射到下划线,因此您的代码应该按原样运行。这在点击文档中使用,例如,在Choice example 中。如果 --delete-thing 旨在作为布尔选项,您可能还希望将其设为 boolean argument

    【讨论】:

    • 这是真的!虽然我理解了带回家的信息,但您的第二个链接可能指向错误的页面。
    【解决方案2】:

    正如gbe的回答所说,click会自动将cli参数中的-转换为python函数参数的_

    但您也可以将 python 变量显式命名为您想要的任何名称。在本例中,它将--delete-thing 转换为new_var_name

    import click
    
    @click.command()
    @click.option('--delete-thing', 'new_var_name')
    
    def cmd_do_this(new_var_name):
        print(f"I deleted the thing: {new_var_name}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      相关资源
      最近更新 更多