Power Up Your Python Scripts: Handling Command-Line Arguments (ResizerMate Part 2 Walkthrough)


Welcome back to the ResizerMate project! In Part 1, we laid the groundwork for our image resizing tool. Now, in Part 2, as shown in the “Code With Me” video, it’s time to make our Python script significantly more flexible and user-friendly by learning how to process command-line arguments.

Being able to pass arguments to your script directly from the terminal (or command line) means you don’t have to hardcode values like file paths. This makes your scripts reusable and automatable. This post will guide you step-by-step through the Python code developed in the video, explaining how to use the sys and os modules for this purpose, and how to keep your project tidy with Git and GitHub.

Let’s dive into the code!

The Enhanced Python Script

Here’s an enhanced Python script that’s developed in the video to handle command-line inputs for an input image and an output folder:

import sysimport os

if __name__ == "__main__":
    # Check if the correct number of arguments is provided    
    if len(sys.argv) != 3:
        print("Usage: python script.py <input_image_path> <output_folder>")
        sys.exit(1)  # Exit if arguments are incorrect

    # Assign command-line arguments to variables
    input_image_path = sys.argv[1]
    output_folder_path = sys.argv[2] # Renamed for clarity from video's 'output_path'

    # Define the main function to encapsulate the script's logic
    def main(image_path, out_folder):
        # Ensure the output directory exists, create if not
        if not os.path.exists(out_folder):
            os.makedirs(out_folder)
            print(f"Created output folder: {out_folder}")

        # Extract the base name of the input image (e.g., "image" from "image.jpg")
        base_name = os.path.splitext(os.path.basename(image_path))[0]

        # In the video, the output file name isn't constructed, but 
        # let's assume it's something like this:
        # output_file_name = f"{base_name}_resized.jpg" # Example format
        # full_output_path = os.path.join(out_folder, output_file_name)

        print(f"Processing image: {image_path}")
        print(f"Output will be in: {out_folder}")
        print(f"Base name of image: {base_name}")
        # print(f"Full output path would be: {full_output_path}") # If you build full path

    # Call the main function with the provided arguments
    main(input_image_path, output_folder_path)

Step-by-Step Breakdown

Let’s break down what each part of this script does, as shown in the video.

1. Importing Necessary Modules [Video Timestamp approx. 00:11]

import sys
import os
  • sys: This module provides access to system-specific parameters and functions. Crucially for us, it includes sys.argv, which is a list containing the command-line arguments passed to the script.
  • os: This module provides a way of using operating system dependent functionality like reading or writing to the file system. We’ll use it to check for directory existence and create directories.

2. Checking for Correct Command-Line Arguments [Video Timestamp approx. 00:29]

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py <input_image_path> <output_folder>")
        sys.exit(1)
  • if __name__ == "__main__":: This is a standard Python construct that ensures the code inside this block only runs when the script is executed directly (not when imported as a module into another script).
  • sys.argv: This is a list where sys.argv[0] is the name of the script itself (e.g., script.py), sys.argv[1] is the first argument, sys.argv[2] is the second, and so on.
  • len(sys.argv) != 3: We expect two user-provided arguments (input image path and output folder path) plus the script name, making a total of 3 items in sys.argv. If the count isn’t 3, the script prints a helpful usage message.
  • sys.exit(1): If the arguments are incorrect, the script exits. The 1 typically indicates that an error occurred.

3. Assigning Arguments to Variables [Video Timestamp approx. 03:51]

    input_image_path = sys.argv[1]
    output_folder_path = sys.argv[2]

Here, we assign the first user-supplied argument (sys.argv[1]) to input_image_path and the second (sys.argv[2]) to output_folder_path.

4. Defining the main Function [Video Timestamp approx. 04:14]

    def main(image_path, out_folder):
        # ... logic inside main ...

Encapsulating the core logic of the script within a main function is good practice. It makes the code more organized and readable.

5. Handling File System Operations with os [Video Timestamps approx. 04:44 & 05:21]

Inside the main function:

    if not os.path.exists(out_folder):
        os.makedirs(out_folder)
        print(f"Created output folder: {out_folder}")
  • os.path.exists(out_folder): Checks if the path specified by out_folder already exists in the file system.
  • os.makedirs(out_folder): If the path doesn’t exist, this function creates the directory. makedirs is useful because it will create any necessary parent directories as well.
    base_name = os.path.splitext(os.path.basename(image_path))[0]        
    print(f"Base name of image: {base_name}")
  • os.path.basename(image_path): Extracts the filename from a full path (e.g., “image.jpg” from “/path/to/image.jpg”).
  • os.path.splitext(...): Splits the filename into a pair: (root, extension). For example, (“image”, “.jpg”).
  • [0]: We take the first element of this pair, which is the base name without the extension.
  • While the provided script only prints the base name, in a real scenario, you’d likely use os.path.join() to combine out_folder, base_name, and a new extension/suffix to create the full path for the output file. For example: full_output_path = os.path.join(out_folder, f{base_name}_resized.jpg").

6. Calling the main Function

    main(input_image_path, output_folder_path)

Finally, the main function is called with the arguments captured from the command line.

Running and Testing [Video Timestamp approx. 06:32]

The video demonstrates running the script from the command line, providing different input image paths and output folder locations. This is how you’d typically use such a script:

python your_script_name.py /path/to/your/image.jpg /path/to/your/output_directory

The video also touches upon encountering and fixing errors [Video Timestamps 03:24, 07:12], such as a TypeError or indentation errors. This is a natural part of coding! Using an editor like VS Code with Python support can help catch some of these early.

Version Control with Git and GitHub [Video Timestamp approx. 07:37]

Throughout the development process, especially when adding new features like this, it’s crucial to use version control. The video shows using Git to:

  1. Stage changes: git add <filename> or git add .
  2. Commit changes: git commit -m "Added command-line argument parsing"
  3. Push changes to GitHub: git push

This workflow ensures your changes are tracked, you can revert if something goes wrong, and your code is backed up on GitHub.

Conclusion

By following along with the video and this guide, you’ve learned how to make your Python scripts significantly more versatile by accepting command-line arguments. You’ve seen how to use the sys module to read these arguments and the os module to interact with the file system, all while keeping your code organized and version-controlled. These are foundational skills for any Python developer building command-line tools or automating tasks!