Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No output from the Python click module?

I tried to follow this tutorial from Dan Bader on click but for some reason the code there doesn't work in the command line with $ python cli.py 'London' and unfortunately it returns no error so it's difficult to investigate what is going on here.

However, the function current_weather() works like a charm in Spyder IDE so first I suspected a compatibility issue between Python Anaconda version and the click module so I completely uninstalled Anaconda and I'm now running on Python 3.6.7 for Ubuntu.

But still I'm unable to make it work in the CLI and it returns no error. What am I doing wrong here?

import click
import requests

SAMPLE_API_KEY = 'b1b15e88fa797225412429c1c50c122a1'

@click.command()
@click.argument('location')
def main(location, api_key):
    weather = current_weather(location)
    print(f"The weather in {location} right now: {weather}.")


def current_weather(location, api_key=SAMPLE_API_KEY):
    url = 'http://samples.openweathermap.org/data/2.5/weather'

    query_params = {
        'q': location,
        'appid': api_key,
    }

    response = requests.get(url, params=query_params)

    return response.json()['weather'][0]['description']

In CLI:

$ python cli.py
$
$ python cli.py 'London'
$

In Spyder IDE:

In [1109]: location = 'London'

In [1110]: current_weather(location)
Out[1110]: 'light intensity drizzle'

When using with pdb source code debugger, pdb automatically enter post-mortem debugging which means the program being exits abnormally. But there is no error...

$ python -m pdb cli.py 'London'
> /home/project/cli.py(2)<module>()
-> import click
(Pdb) 

I have click-7.0 installed and Python 3.6.7 (default, Oct 22 2018, 11:32:17)

like image 322
Florent Avatar asked Jul 08 '26 17:07

Florent


1 Answers

You need to call main():

if __name__ == '__main__':
    main()

Full example:

import click

@click.command()
@click.argument('location')
def main(location):
    weather = current_weather(location)
    print(f"The weather in {location} right now: {weather}.")


def current_weather(location):
    return "Sunny"


if __name__ == '__main__':
    main()

Using setup tools

Alternatively you can use setup tools, and then invoke main that way:

Debugging:

I highly recommend PyCharm as a Python IDE. It can make doing this sort of work much easier.

like image 51
Stephen Rauch Avatar answered Jul 11 '26 08:07

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!