在
click
的 Context
应用程序中,我们可以获取命令名称、其完整路径和解析的参数,如下所示。我们可以从 click
获取未解析的参数吗?
编辑:根据@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:", "???")
# Try it with click.Context.args
print("\nCommand leftover args:", ctx.args)
# Try it with sys.argv
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 args with Click: -o 1
在
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()