在单击应用程序中获取 CLI 参数

问题描述 投票:0回答:1

click
Context
应用程序中,我们可以获取命令名称、其完整路径和解析的参数,如下所示

编辑:根据@julaine和@Marco Parola评论更新代码

abc脚本内容:

#!/home/user/.bin/python-tools/venv/bin/python3

import sys
import click

@click.group("abc")
def abc():
    """ABC Help"""
    pass

@abc.command("test")
@click.option("-o", "--option")
@click.option("-o2", "--option2", default="two")
def test(option, option2):
    """Get command CLI info"""
    ctx = click.get_current_context()
    print("Command name:", ctx.info_name)
    print("Command path:", ctx.command_path)
    print("Command params:", ctx.params)
    print("CLI args with Click:", "???")
    
    print("\nCommand leftover args:", ctx.args)
    cmd_path = click.get_current_context().command_path.split()
    cli_args = sys.argv[len(cmd_path):]
    print("CLI args with sys.argv:", " ".join(cli_args))

if __name__ == "__main__":
    abc()

我们得到回复:

❯ abc test -o 1
Command name: test
Command path: abc test
Command params: {'option': '1', 'option2': 'two'}
CLI args with Click: ???

Command leftover args: []
CLI args with sys.argv: -o 1

可以在没有

click
的情况下从
sys.argv
获取未解析的 CLI 参数吗?在上面的示例中,它应该返回:

CLI args with Click: -o 1
python command-line-interface python-click
1个回答
0
投票

click
中,您可以使用
click.Context
的args属性获取未解析的CLI参数。它会返回给你一个列表。

import click

@click.group("abc")
def abc():
    """ABC Help"""
    pass

@abc.command("test")
@click.option("-o", "--option")
@click.option("-o2", "--option2", default="two")
def test(option, option2):
    """Get command CLI info"""
    ctx = click.get_current_context()
    print("Command name:", ctx.info_name)
    print("Command path:", ctx.command_path)
    print("Command params:", ctx.params)
    print("CLI args:", ' '.join(ctx.args))

if __name__ == "__main__":
    abc()
© www.soinside.com 2019 - 2024. All rights reserved.