Skip to content

Instantly share code, notes, and snippets.

@mapi68
Last active May 6, 2024 10:27
Show Gist options
  • Save mapi68/cbca560f0ce1b71671f416b56b719af1 to your computer and use it in GitHub Desktop.
Save mapi68/cbca560f0ce1b71671f416b56b719af1 to your computer and use it in GitHub Desktop.
This Python script uses pip and the Python Package Index (PyPI) to identify outdated packages. It also offers the option to update them and cleans the pip cache.
import subprocess
import requests
def get_outdated_packages():
try:
print("Searching for outdated packages...")
# Execute the 'pip list --outdated' command to get the list of packages to update
outdated_packages = (
subprocess.check_output(["pip", "list", "--outdated"])
.decode()
.split("\n")[2:-1]
)
packages_to_update = [
package.split()
for package in outdated_packages
if package.split()[0] != "Package"
]
return packages_to_update
except Exception as e:
print(f"An error occurred while retrieving packages to update: {str(e)}")
return []
def get_latest_version(package_name):
try:
# Make an HTTP request to the PyPI API to get package information
response = requests.get(f"https://pypi.org/pypi/{package_name}/json")
response_json = response.json()
latest_version = response_json["info"]["version"]
return latest_version
except Exception as e:
print(
f"An error occurred while retrieving the latest version of {package_name}: {str(e)}"
)
return None
def update_pip_packages():
packages_to_update = get_outdated_packages()
if packages_to_update:
print("Packages to update:")
for idx, package_info in enumerate(packages_to_update, start=1):
package_name = package_info[0]
current_version = package_info[1]
latest_version = get_latest_version(package_name)
if latest_version:
print(
f"{idx}. {package_name}: from {current_version} to {latest_version}"
)
confirmation = (
input("Do you want to proceed with the update? (y/n): ").strip().lower()
)
if confirmation == "y":
try:
print("Starting the update...")
# Perform the update for each package in the list
for idx, package_info in enumerate(packages_to_update, start=1):
package_name = package_info[0]
current_version = package_info[1]
latest_version = get_latest_version(package_name)
print(
f"{idx}. {package_name}: from {current_version} to {latest_version}"
)
# Perform the update for the current package
subprocess.run(
["pip", "install", "--upgrade", package_name],
capture_output=True,
text=True,
)
print("Update completed.")
except Exception as e:
print(f"An error occurred during the update: {str(e)}")
else:
print("Update canceled.")
else:
print("No packages to update.")
def purge_pip_cache():
# Purges the pip cache
try:
subprocess.run(["pip", "cache", "purge"], check=True)
print("Pip cache purged successfully!")
except subprocess.CalledProcessError as error:
print("Error purging pip cache:", error)
if __name__ == "__main__":
update_pip_packages()
if __name__ == "__main__":
purge_pip_cache()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment