1

Often I want to profile a CLI program built with Click, but I can't figure out how to parse both the Python command line options and the click command line options/arguments. For example, if my script took a single option and two arguments, I can run it fine like:

python add.py --verbose 1 2

Similarly, when I profile a simple (non-Click) script, I can do this:

python -m cProfile -o stats.txt add_no_click.py 1 2

but when I want to profile the Click script, I get this:

python -m cProfile -o stats.txt add.py --verbose 1 2
Error: no such option: -o

I know I must be missing some documentation out there. For what it's worth, I'm using Python 2.7 on Windows 10 64-bit, although I doubt it has a bearing on the answer.

2
  • python 2 does not recognize the '-o' option. Why are you surprised? Commented Jan 24, 2018 at 18:24
  • @DYZ, when '-o' is used in conjunction with the cProfile module, it specifies the output file to write the profile results, .e.g python -m cProfile [-o output_file] [-s sort_order] myscript.py cProfile docs Commented Jan 24, 2018 at 19:14

1 Answer 1

1

Sorry for the self-answer, but hope this might help others. The stupid thing I did (and that I didn't show in the question above) was forgetting to call main with just sys.argv[1:].

Sample program:

import click

@click.command()
@click.option('-v', '--verbose', is_flag=True)
@click.argument('a', type=click.INT, required=True)
@click.argument('b', type=click.INT, required=True)
def main(verbose, a, b):
    if verbose:
        print('The answer is {}'.format(a + b))
    else:
        print(a + b)

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

Running it:

> python -m cProfile -o foo.stats add.py --verbose 1 2
The answer is 3

and the profile information is written to foo.stats.

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.