Python click模块没有输出?

3
我尝试按照Dan Bader的教程使用click库,但是在命令行中使用$ python cli.py 'London'时,那里的代码无法运行。不幸的是,它没有返回任何错误信息,因此很难调查原因。
然而,在Spyder IDE中,current_weather()函数完美运行,所以我首先怀疑Python Anaconda版本和click模块之间存在兼容性问题,因此我完全卸载了Anaconda,并切换到Ubuntu上的Python 3.6.7。
但是,我仍然无法在CLI中使其正常工作,并且没有返回任何错误信息。我在这里做错了什么?
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']

在命令行界面:

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

In Spyder IDE:

In [1109]: location = 'London'

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

当使用pdb源代码调试器时,如果程序异常退出,pdb会自动进入事后调试模式。但是没有错误信息... 调试者可以使用这种模式来分析程序的状态并找出问题所在。
$ python -m pdb cli.py 'London'
> /home/project/cli.py(2)<module>()
-> import click
(Pdb) 

我已经安装了click-7.0Python 3.6.7(默认,2018年10月22日,11:32:17)。"Original Answer"翻译成中文是"最初的回答"。
1个回答

3
你需要调用 main()
if __name__ == '__main__':
    main()

完整示例:

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

使用安装工具

或者您可以使用安装工具,然后以这种方式调用main

调试:

我强烈推荐PyCharm作为Python IDE。它可以使这种工作变得更加容易。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接