Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: update_packages.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- This script checks for outdated Python packages using pip and upgrades them if necessary.
- It logs the upgrade results to a file named 'upgrade_log.txt' in the current working directory.
- Requirements:
- - Python 3.x
- - pip
- Usage:
- - Run the script using Python 3.x from the command line.
- - Navigate to the current working directory and use the terminal command:
- 'python upgrade_packages.py'
- - The script will automatically upgrade outdated packages if any are found.
- Additional Notes:
- - The script will create a log file named 'upgrade_log.txt' in the current working directory.
- """
- import subprocess
- import datetime
- import os
- # Function to run pip list command and check for outdated packages
- def check_outdated_packages():
- result = subprocess.run(['pip', 'list', '--outdated'], capture_output=True, text=True)
- outdated_packages = result.stdout.strip().split('\n')[2:] # Extract outdated packages, skipping header
- return outdated_packages
- # Function to upgrade outdated packages and log the results
- def upgrade_packages(outdated_packages):
- log_path = os.path.join(os.getcwd(), 'upgrade_log.txt')
- if not outdated_packages:
- print("All packages are already up to date.")
- with open(log_path, 'a', encoding='utf-8') as log_file:
- log_file.write(f'{datetime.datetime.now()}: All packages are already up to date\n')
- print(f"Log file saved to: {log_path}")
- else:
- print("Updating outdated packages...")
- for package in outdated_packages:
- subprocess.run(['pip', 'install', '--upgrade', package.split()[0]])
- with open(log_path, 'a', encoding='utf-8') as log_file:
- log_file.write(f'{datetime.datetime.now()}: Upgraded packages: {", ".join(outdated_packages)}\n')
- print(f"Log file saved to: {log_path}")
- # Main function
- def main():
- outdated_packages = check_outdated_packages()
- upgrade_packages(outdated_packages)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement