0

I have the following code:

import click

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)

At the command line I want to be able to do something like the following:

python clicktest.py cli initdb

and have the following happen echo at the terminal:

Initialized the database

Or to enter into the terminal:

python clicktest.py cli dropdb

and have the following happen on the terminal:

Dropped the database

My problem is currently when I do this at the terminal:

 python clicktest.py cli initdb

Nothing happens at the terminal, nothing prints when I think something should, namely the 'Initialized Database' echo. What am i doing wrong??

1 Answer 1

1

First, you should use it in command line like:

python clicktest.py initdb
python clicktest.py dropdb

And in your clicktest.py file, place these lines at the bottom of your code:

if __name__ == '__main__':
    cli()

Unless, your code won't get work.

EDIT:

If you really want to use it in a way python clicktest.py cli initdb, then you have another choice:

@click.group()
def main():
    pass

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)
main.add_command(cli)

if __name__ == '__main__':
    main()

Or even better (Using decorators instead):

@click.group()
def main():
    pass

@main.group()
def cli():
    pass

@cli.command()
def initdb():
    click.echo('Initialized the database')

@cli.command()
def dropdb():
    click.echo('Dropped the database')

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.