How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
Python code
52 linesimport 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
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
- Use pathlib to check modification times of package directories instead of parsing pip show
- 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
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.