1

I am trying to implement basic command line functionality.

So I need to be able to pass file as argument, read it and pass result further.

But for some reason it doesn't work as expected.

import click


@click.command()
@click.argument('arg', nargs=1, type=click.File('r'))
def touch(arg):
    return len(arg.readlines())


def fill():
    print touch()


if __name__ == '__main__':
    fill()

There is no any output. But seems touch() is executing since in case if I am adding print statement into touch() I can see some stuff in output.

2
  • How can you execute touch() with no arguments if in you definition there is one required? Commented Mar 20, 2016 at 10:21
  • @Ilja click handles that under the hood Commented Mar 20, 2016 at 10:25

1 Answer 1

1

Unfortunately, using click makes it such that your function never returns any value. you can use click.echo to print the values to the front-end, but you cannot return any values as it exits when function execution is finished. In other words, it no longer behaves as a function once you wrap it with click.command but instead becomes a command line program.

You can alternatively use optparse to achieve what you are trying to achieve.

Resources - https://docs.python.org/2/library/optparse.html

Edit:- I found a similar question here, you can also use this as reference - How do I return a value when @click.option is used to pass a command line argument to a 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.