Tech C**P
14 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Nearly all of you have created a python script throughout your career, in case you are a python programmer! Usually scripts take arguments, provide help, optional arguments and more.

Working with modules like optparse and argparse do the job, but they are not powerful enough in case your are designing a complex script like pip CLI script! click python module is at your service.


NOTE: The biggest difference between optparse and argparse is that optparse is deprecated since Python 3.2 and argparse is considered the standard for implementing CLIs in Python.



click do a similar task akin to optparse and argparse but in a nicer way by using decorators.

Take a look at the below github gist and let's discuss about different parts of it:
- https://gist.github.com/alirezastack/cccb70640c5e5881fa71b23966707f8f

The above gist is a sample weather app using python 3. SAMPLE_API_KEY is used to send requests to openweathermap API. current_weather is a regular method like other python methods.

The important part of script starts from @click.command(). This command defines the main method as a cli app. If you just put this command before your main method and run your script as below, it will prints help instruction of your script:
$ python cli.py --help
Usage: cli.py [OPTIONS]

Options:
--help Show this message and exit.

As you can see it prints some default help for your barebone script. 21st line of script is @click.argument('location') that defines a required parameter for you CLI app called location.

If you want to define an optional argument use @click.option. As you can note we have used --api-key, -a in the same argument. It helps users to use the shortcut version or human readable format of the argument. Both refers to the same argument and it will be mapped to api_key method variable (snake case).

help in click.option is used to give a brief guide for the argument when --help is used.

Finally the docstring inside of main method which is inside of triple quote will be shown when --help is used.

NOTE: snake case is a procedure that removes dashes from the begining of an input argument and turns dash into underscore. So something like --format-type will be converted to format_type.

That was easy right? I know, it was super simple compared to argparse and optparse. Rock on!

#python #python3 #cli #click #argparse #optparse #argument
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly configurable but comes with sensible defaults out of the box.

- http://click.pocoo.org/6/

#python #argparse #click #command_line_interface