Advertisement
Python253

update_packages

Apr 19th, 2024
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: update_packages.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script checks for outdated Python packages using pip and upgrades them if necessary.
  9. It logs the upgrade results to a file named 'upgrade_log.txt' in the current working directory.
  10.  
  11. Requirements:
  12.    - Python 3.x
  13.    - pip
  14.  
  15. Usage:
  16.    - Run the script using Python 3.x from the command line.
  17.    - Navigate to the current working directory and use the terminal command:
  18.            
  19.            'python upgrade_packages.py'
  20.            
  21.    - The script will automatically upgrade outdated packages if any are found.
  22.  
  23. Additional Notes:
  24.    - The script will create a log file named 'upgrade_log.txt' in the current working directory.
  25. """
  26.  
  27. import subprocess
  28. import datetime
  29. import os
  30.  
  31. # Function to run pip list command and check for outdated packages
  32. def check_outdated_packages():
  33.     result = subprocess.run(['pip', 'list', '--outdated'], capture_output=True, text=True)
  34.     outdated_packages = result.stdout.strip().split('\n')[2:]  # Extract outdated packages, skipping header
  35.     return outdated_packages
  36.  
  37. # Function to upgrade outdated packages and log the results
  38. def upgrade_packages(outdated_packages):
  39.     log_path = os.path.join(os.getcwd(), 'upgrade_log.txt')
  40.     if not outdated_packages:
  41.         print("All packages are already up to date.")
  42.         with open(log_path, 'a', encoding='utf-8') as log_file:
  43.             log_file.write(f'{datetime.datetime.now()}: All packages are already up to date\n')
  44.         print(f"Log file saved to: {log_path}")
  45.     else:
  46.         print("Updating outdated packages...")
  47.         for package in outdated_packages:
  48.             subprocess.run(['pip', 'install', '--upgrade', package.split()[0]])
  49.         with open(log_path, 'a', encoding='utf-8') as log_file:
  50.             log_file.write(f'{datetime.datetime.now()}: Upgraded packages: {", ".join(outdated_packages)}\n')
  51.         print(f"Log file saved to: {log_path}")
  52.  
  53. # Main function
  54. def main():
  55.     outdated_packages = check_outdated_packages()
  56.     upgrade_packages(outdated_packages)
  57.  
  58. if __name__ == "__main__":
  59.     main()
  60.  
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement