3

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)

1 Answer 1

2

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.

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.