Search code examples
pythoncommandpython-click

Using click.command to make a function as a command


I am trying to make the function log into a command using the following code inside simple.py:

import click

@click.command()
@click.option('-v', '--verbose', count=True)
def log(verbose):
    click.echo(f"Verbosity: {verbose}")

When I type the following on the command terminal:log -vvv , I get an error as : Command 'log' not found, but there are 16 similar ones.

@click.command should have converted the function log into a command? But, it doesn't work here. Could someone explain,please? Thanks!

I have tried the following commands:


log -vvv
Command 'log' not found, but there are 16 similar ones.

python3 simple.py log
Usage: simple.py [OPTIONS]
Try 'simple.py --help' for help.

Error: Got unexpected extra argument (log)

Could someone please explain what does @click.command() actually do and how's it different from running simple.py. The documentation does not make it very clear to me as well. Thanks!


Solution

  • import click
    
    @click.command()
    @click.option('-v', '--verbose', count=True)
    def log(verbose):
        click.echo(f"Verbosity: {verbose}")
    
    if __name__ == '__main__':
        log()
    

    Then calling it like

    $ python simple.py    
    Verbosity: 0
    
    $ python simple.py -v
    Verbosity: 1
    

    The way you try to run it, suggest you think about command group, i.e. nesting commands

    import click
    
    @click.group()
    def cli():
        pass
    
    @cli.command('log')
    @click.option('-v', '--verbose', count=True)
    def log(verbose):
        click.echo(f"Verbosity: {verbose}")
    
    @cli.command('greet')
    def greet():
        click.echo("Hello")
    
    if __name__ == '__main__':
        cli()
    

    Then

    $ python simple.py greet
    Hello
    
    $ python simple.py log -v -v # or just -vv
    Verbosity: 2
    

    Next step would be setuptools integration, etc.