Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to debug python click cli application?

Tags:

I have built a cli application using the click library in python. There is no documentation on how to debug commands.

Without click, its easy to just debug python files in IDE, but when we use click, the commands need to be run through console_scripts setup in setup.py.

like image 400
vishal Avatar asked Mar 30 '17 10:03

vishal


People also ask

How do you debug Python command line arguments?

Go to your project properties, either by right-clicking on the project and picking "Properties" or by picking Properties from the Project menu. Click on Debug, then enter your arguments into the "Script Arguments" field. Save.

How do you debug a Python application?

If you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File in Terminal.

How do I run Python debug in terminal?

Directly use command python pdg-debug.py without -m pdb to run the code. The program will automatically break at the position of pdb. set_trace() and enter the pdb debugging environment. You can use the command p variable to view the variables or use the command c to continue to run.

Is there a debug mode for Python?

Python has a built-in debugger called pdb . It's a simple utility with a command line interface that does the main job. It has all the debugger features you'll need, but if you're looking to pimp it up a little, you can extend it using ipdb, which will provide the debugger with features from IPython.


2 Answers

This is not well documented, but you can call your command functions directly, and thus can run the code in a debugger:

Sample Code:

import click  @click.command() @click.option('--my_arg', default=1, help='a number') def my_command(my_arg):     click.echo("my_arg='%d'" % my_arg)  if __name__ == '__main__':     my_command(['--my_arg', '3']) 

Result:

my_arg='3' 
like image 176
Stephen Rauch Avatar answered Sep 18 '22 10:09

Stephen Rauch


I'm a couple years late to the party, but in case anyone else comes here looking for an answer like I just did:

Calling your function with CliRunner.invoke() will return a "Result" object with an "exc_info" attribute. You can feed that to traceback.print_exception() like so:

runner = CliRunner() result = runner.invoke(my_command) traceback.print_exception(*result.exc_info) 
like image 37
Jacob Jurmain Avatar answered Sep 18 '22 10:09

Jacob Jurmain