Minimize CSS using Python with CLI

In a previous post, I showed you how-to minimize your CSS using Python. Well, the script will help you minimize your CSS but how about if you didn't want to edit the script each time you wanted to minimize a CSS file? This is where this tutorial comes in.

Minimize CSS using Python with CLI
Photo by Maik Jonietz / Unsplash

In a previous post, I showed you how-to minimize your CSS using Python. Well, the script will help you minimize your CSS but how about if you didn't want to edit the script each time you wanted to minimize a CSS file? This is where this tutorial comes in. In this tutorial, I'll show you how-to minimize your CSS file using Python but with command line interface (CLI).

import argparse
import csscompressor

parser = argparse.ArgumentParser(description='Minimize CSS code.')
parser.add_argument('input_file', help='the input CSS file')
parser.add_argument('output_file', help='the output file for the minimized CSS')

args = parser.parse_args()

# Load the CSS file
with open(args.input_file, 'r') as f:
    css_text = f.read()

# Minimize the CSS
minimized_css = csscompressor.compress(css_text)

# Write the minimized CSS to a file
with open(args.output_file, 'w') as f:
    f.write(minimized_css)

print('Successfully minimized CSS code!')

To run this script, you'll need to have the csscompressor library installed. You can install it by running pip install csscompressor.

Run the script using the following command:

python minimize_css.py src.css dist.css

Where src.css is the input file and dist.css is the output file.