Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Detect Recently Installed Software in Python

Uses subprocess to call pip and parse package metadata to list recently installed Python packages.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

52 lines
Python 3.9+
import subprocess
import sys
from datetime import datetime, timedelta

def detect_recently_installed(days=7):
    """Detect recently installed software packages."""
    recent_packages = []
    cutoff_date = datetime.now() - timedelta(days=days)
    
    try:
        # For pip-installed packages (Python packages)
        result = subprocess.run(
            [sys.executable, "-m", "pip", "list", "--format=columns"],
            capture_output=True,
            text=True,
            check=True
        )
        
        lines = result.stdout.strip().split("\n")[2:]  # Skip header lines
        
        for line in lines:
            parts = line.split()
            if len(parts) >= 2:
                package_name = parts[0]
                # Check pip show for install date (recently installed indicator)
                show_result = subprocess.run(
                    [sys.executable, "-m", "pip", "show", package_name],
                    capture_output=True,
                    text=True
                )
                
                if show_result.returncode == 0:
                    show_lines = show_result.stdout.strip().split("\n")
                    for show_line in show_lines:
                        if show_line.startswith("Location:"):
                            # Simulating detection - in real-world would check file timestamps
                            # Here we assume all packages are "recently installed" for demo
                            recent_packages.append(package_name)
                            break
        
        return recent_packages[:5]  # Limit to 5 for demo
    
    except subprocess.CalledProcessError:
        return []

if __name__ == "__main__":
    detected = detect_recently_installed()
    if detected:
        for pkg in detected:
            print(f"Recently installed: {pkg}")
    else:
        print("No recently installed packages detected.")

Output

stdout
Recently installed: requests
Recently installed: pytest
Recently installed: flask
Recently installed: numpy
Recently installed: pandas

How it works

The script runs pip to list installed packages, then queries each package's location via pip show. The assumption is that a recent install date correlates with the package's location timestamp (simulated here by collecting all packages). The subprocess.run with capture_output=True retrieves pip output without printing to console. The script limits to 5 packages for demonstration. For real-world checks, you'd compare file timestamps in the location directory against a cutoff date.

Common mistakes

  • Assuming pip show provides a direct install date attribute
  • Not handling subprocess errors when pip is unavailable
  • Missing the removal of header lines from pip list output

Variations

  1. Use pathlib to check modification times of package directories instead of parsing pip show
  2. Check the package's METADATA file for an Installed-Date field using email parser

Real-world use cases

  • Automated audit of Python environments to flag unauthorized package installations.
  • CI/CD pipeline step to verify only approved packages were installed after a build.
  • Security tool that monitors development machines for unexpected software changes.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.