8

This question is about the Python Click library.

I want click to gather my commandline arguments. When gathered, I want to reuse these values. I dont want any crazy chaining of callbacks, just use the return value. By default, click disables using the return value and calls sys.exit().

I was wondering how to correctly invoke standalone_mode (http://click.pocoo.org/5/exceptions/#what-if-i-don-t-want-that) in case I want to use the decorator style. The above linked doc only shows the usage when (manually) creating Commands using click. Is it even possible? A minimal example is shown below. It illustrates how click calls sys.exit() directly after returning from gatherarguments

import click

@click.command()
@click.option('--name', help='Enter Name')
@click.pass_context
def gatherarguments(ctx, name):
    return ctx

def usectx(ctx):
    print("Name is %s" % ctx.params.name)

if __name__ == '__main__':
    ctx = gatherarguments()
    print(ctx) # is never called
    usectx(ctx) # is never called 

$ python test.py --name Your_Name

I would love this to be stateless, meaning, without any click.group functionality - I just want the results, without my application exiting.

1 Answer 1

11

Just sending standalone_mode as a keyword argument worked for me:

from __future__ import print_function
import click

@click.command()
@click.option('--name', help='Enter Name')
@click.pass_context
def gatherarguments(ctx, name):
    return ctx

def usectx(ctx):
    print("Name is %s" % ctx.params['name'])

if __name__ == '__main__':
    ctx = gatherarguments(standalone_mode=False)
    print(ctx)
    usectx(ctx)

Output:

./clickme.py --name something
<click.core.Context object at 0x7fb671a51690>
Name is something
Sign up to request clarification or add additional context in comments.

4 Comments

oww you are kidding me, did you just try this or was there any logic involved in finding out? Is this working because the kwarg is passed to click.Command on creation? Somehow it is passed down to click.Command.main(..)
also if one does something like ./clickme.py asd this errors out quite bad, because you loose all the error handling from click it seems :(
I looked at the source, in particular github.com/mitsuhiko/click/blob/master/click/core.py#L714, and saw that they pass the kwargs to main. Regarding the error handling, you do get click.exceptions.UsageError: Got unexpected extra argument (asd). So I assume that you could catch it and print a nicer error message. But yes, you don't get their error handling. Wonder if you could call their error handler... It will always be a hack.
Well thats true, anyways I'll mark your answer as correct, as it answers my question.

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.