【问题标题】:Program stops when running @click.command运行@click.command 时程序停止
【发布时间】:2019-04-19 07:08:24
【问题描述】:

我正在使用@click.command 来处理我的代码。但是,在此之前,我尝试了代码:

import click
import random

@click.command()
@click.option('--total', default=3, help='Number of vegetables to output.')
def veg(total):
    """ Basic method will return a random vegetable"""
    for number in range(total):
        print(random.choice(['Carrot', 'Potato', 'Turnip', 'Parsnip']))

if __name__ == '__main__':
    veg()
    print('End function')

我不明白为什么在使用veg() 函数后程序会立即停止。我该怎么做才能保持程序运行并运行print('End function')?

【问题讨论】:

  • 所以你说的是“胡萝卜”等。会打印,但“结束功能”不会打印?
  • 是的。对不起我的表情

标签: python python-3.x python-click


【解决方案1】:

这是因为默认行为是以独立模式调用脚本。然后 Click 将处理异常并将它们转换为错误消息,并且该函数将永远不会返回但会关闭解释器。 - docs.

将standalone_mode 设置为 False 以更改它:

import click
import random

@click.command()
@click.option('--total', default=3, help='Number of vegetables to output.')
def veg(total):
    """ Basic method will return a random vegetable"""
    for number in range(total):
        print(random.choice(['Carrot', 'Potato', 'Turnip', 'Parsnip']))

if __name__ == '__main__':
    veg.main(standalone_mode=False)
    print('End function')

Turnip
Carrot
Carrot
End function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2020-01-27
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多