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