Get unparsed parameters in click application

88 Views Asked by At

In click application from Context we can get command name, its full path and parsed parameters like below. Can we get unparsed parameters from click?

Edit: updated question according to @julaine and @Marco Parola comments

abc script contents:

#!/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()

We get in responce:

❯ 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

Can one get unparsed parameters from click itself, i.e. without sys.argv? In the example above it should return:

CLI args with Click: -o 1
1

There are 1 best solutions below

5
On

In click, you can obtain the unparsed CLI arguments using the args attribute of the click.Context. And it returns you a list.

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()