I recently have been using the click package to build command line interfaces which has worked perfectly, so far.
Now I got into some trouble when using chained commands in combination with the context object. The problem is that I somehow get an error when I want to call the function of another command from within another command.
It is probably somehow related to the usage of decorators within click but I don't see the error right now.
This is a minimal example of my code:
import click
@click.group(chain=True)
@click.option('--some_common_option', type=float, default=1e-10)
@click.pass_context
def cli(ctx, some_common_option):
# save shared params within context object for different commands
for k, v in locals().items():
if 'ctx' not in k:
ctx.obj[k] = v
return True
@cli.command()
@click.argument('some_argument', type=str)
@click.pass_context
def say_something(ctx, some_argument):
print(some_argument)
return True
@cli.command()
@click.argument('some_other_argument', type=str)
@click.pass_context
def say_more(ctx, some_other_argument):
ctx.obj['text'] = some_other_argument
say_something(ctx, ctx.obj['text'])
return True
if __name__ == '__main__':
cli(obj={})
And this is the error that is provided on the terminal:
$ python test.py say_something 'Hello!'
Hello!
$ python test.py say_more 'How are you?'
Traceback (most recent call last):
File "test.py", line 36, in <module>
cli(obj={})
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 1092, in invoke
rv.append(sub_ctx.command.invoke(sub_ctx))
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "test.py", line 30, in say_more
say_something(ctx, ctx.obj['text'])
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/user/.anaconda3/lib/python3.6/site-packages/click/core.py", line 683, in main
args = list(args)
TypeError: 'Context' object is not iterable
$
I am wondering why and where the iteration over the context object takes place.
Any hints how I can fix this and use the function from within another command?