Program stops when running @click.command
Asked Answered
E

1

6

I am using @click.command to do some things with my code. However, before that, I tried the code:

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

I do not understand why the program stops immediately when done with the veg() function. What do I have to do to keep the program running and run print('End function')?

Expectorate answered 19/4, 2019 at 7:8 Comment(2)
So you're saying "Carrot" etc. does print, but "End function" does not print?Violetavioletta
Yes. Sorry for my expressionExpectorate
W
11

That's because the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. - docs.

Set standalone_mode to False to change it:

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
Whomp answered 19/4, 2019 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.