How to Create Practical Command-Line Applications in Python: Image Resizer, Password Generator, and Currency Converter
How to Create Practical Command-Line Applications in Python: Image Resizer, Password Generator, and Currency Converter

How to Create Practical Command-Line Applications in Python: Image Resizer, Password Generator, and Currency Converter

Command line applications (CLIs) are a time-honored and versatile method of interacting with applications, providing a robust and efficient interface for users.

They offer a unique blend of power, speed, and flexibility, making them an indispensable tool in a developer's arsenal.

In this tutorial, we will delve into the creation of three highly useful command-line applications using Python, a popular and versatile programming language.

Our journey will begin with the development of an image resizer. Next, we will turn our attention to creating a password generator. Finally, we will round out our tutorial with the creation of a currency converter.

Whether you're a seasoned developer or a beginner just starting your coding journey, this tutorial offers valuable insights and practical skills for everyone.

Get the Source Code


Prerequisites

To follow along, you'll need Python 3.x installed on your system, along with the click library, which you can install with:

pip install click        

Additionally, for each of the applications, additional libraries will be needed, but you will install them as we go through the applications and their code.


Image Resizer

We will get started with a simple script that resizes images using the Python Imaging Library (PIL) and the Click library.

You need to have the Python Imaging Library (PIL) installed in your Python environment. If it's not installed, you can install it using pip:

pip install pillow        

Here's a basic example (you can create a file called image_resizer.py):

from PIL import Image
import click


@click.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.argument('output_file', type=click.Path())
@click.option('--width', default=None, help='New width of the image.')
@click.option('--height', default=None, help='New height of the image.')
def resize_image(input_file, output_file, width, height):
    image = Image.open(input_file)

    if width and height:
        new_size = (int(width), int(height))
    elif width:
        width = float(width)
        new_size = (int(width), int(image.size[1] * width / image.size[0]))
    elif height:
        height = float(height)
        new_size = (int(image.size[0] * height / image.size[1]), int(height))
    else:
        raise click.BadOptionUsage(message='Either --width or --height must be specified.', option_name='')

    image = image.resize(new_size, Image.BICUBIC)
    image.save(output_file)
    click.echo(f'Image resized and saved as {output_file}')


if __name__ == '__main__':
    resize_image()
        

This code defines a command-line interface (CLI) for resizing images using the Python Imaging Library (PIL) and the click library.

Here's a breakdown of the code:

  • The?resize_image?function is defined and decorated [email protected](), which indicates that this function is the main command of the script.
  • [email protected]?decorators are used to define command line arguments. The?input_file?argument is the path to the image file to be resized, and it must be an existing file. The?output_file?argument is the path where the resized image will be saved.
  • [email protected]?decorators are used to define command line options. The?--width?and?--height?options allow the user to specify the new width and height of the image, respectively. By default, these options are set to?None, meaning they are not required.
  • Inside the?resize_image?function, the image is opened using?Image.open(input_file). Then, the new size of the image is calculated based on the provided width and height.
  • If both width and height are provided, they are converted to float values and then to integers to avoid the?TypeError?that was mentioned earlier. If only one of them is provided, the aspect ratio of the image is maintained by calculating the other dimension using the original image size. If neither is provided, an error is raised using?click.BadOptionUsage.
  • The image is then resized using the?Image.resize?method with the calculated new size and the?Image.BICUBIC?filter. The resized image is saved using the?Image.save?method.
  • Finally, a message is printed to the console using?click.echo?to confirm that the image has been resized and saved.

You can run this script with different options to resize images. For example, you can resize an image to 200x200 pixels by running the following command:

python image_resizer.py input.png output.png --width 200 --height 200        

You can also specify either the width or the height:

python image_resizer.py input.png output.png --width 200

python image_resizer.py input.png output.png --height 200        

Password Generator

Now let's focus on creating a password generator command line application. You don't need any additional library other than the Click library.



Full article at: https://developer-service.blog/how-to-create-practical-command-line-applications-in-python-image-resizer-password-generator-and-currency-converter/

要查看或添加评论,请登录

Nuno Bispo的更多文章

社区洞察

其他会员也浏览了