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

2
  • 1
    So you're saying "Carrot" etc. does print, but "End function" does not print? Commented Apr 19, 2019 at 7:29
  • Yes. Sorry for my expression Commented Apr 19, 2019 at 7:34

1 Answer 1

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
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.