Advertisement
nitestryker

Generate requirements.txt with latest packages

Feb 21st, 2025 (edited)
579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.72 KB | None | 0 0
  1. import os
  2. import re
  3. import importlib.metadata
  4. import subprocess
  5. import requests
  6. import sys
  7. import time
  8. import random
  9.  
  10. PYPI_URL = "https://pypi.org/pypi/{}/json"
  11.  
  12.  
  13. def __():
  14.     _0, _1 = ["\033[91m", "\033[92m", "\033[93m", "\033[94m", "\033[95m", "\033[96m"], "\033[0m"
  15.     _2 = [99, 114, 101, 97, 116, 101, 100, 32, 98, 121, 32, 110, 105, 116, 101, 115, 116, 114, 121, 107, 101, 114]
  16.     _3 = ''.join(map(chr, _2))
  17.    
  18.     for _4 in range(len(_3) + 1):
  19.         sys.stdout.write("\r" + random.choice(_0) + _3[:_4] + _1)
  20.         sys.stdout.flush()
  21.         time.sleep(0.1)
  22.    
  23.     print()
  24.    
  25.     for _5 in range(10):
  26.         sys.stdout.write("\r" + random.choice(_0) + _3 + _1)
  27.         sys.stdout.flush()
  28.         time.sleep(0.2)
  29.    
  30.     print("\n")
  31.  
  32. def get_installed_packages():
  33.     """Returns a dictionary of installed packages with their versions."""
  34.     return {pkg.metadata["Name"].lower(): pkg.version for pkg in importlib.metadata.distributions()}
  35.  
  36. def get_latest_version(package_name):
  37.     """Fetch the latest version of a package from PyPI."""
  38.     try:
  39.         response = requests.get(PYPI_URL.format(package_name))
  40.         if response.status_code == 200:
  41.             return response.json()["info"]["version"]
  42.     except Exception as e:
  43.         print(f"Error fetching version for {package_name}: {e}")
  44.     return None
  45.  
  46. def extract_imports_from_file(file_path):
  47.     """Extracts imported modules from a given Python file."""
  48.     imports = set()
  49.     import_pattern = re.compile(r'^\s*(?:import|from)\s+([\w\.]+)')
  50.    
  51.     try:
  52.         with open(file_path, 'rb') as f:
  53.             for line in f:
  54.                 try:
  55.                     line = line.decode('utf-8', errors='ignore')  # Decode safely
  56.                 except UnicodeDecodeError:
  57.                     continue
  58.                 match = import_pattern.match(line)
  59.                 if match:
  60.                     module = match.group(1).split('.')[0]  # Get the base module name
  61.                     imports.add(module)
  62.     except Exception as e:
  63.         print(f"Error reading {file_path}: {e}")
  64.    
  65.     return imports
  66.  
  67. def find_all_imports(directory):
  68.     """Finds all imported modules in Python files within the specified directory."""
  69.     all_imports = set()
  70.     for root, _, files in os.walk(directory):
  71.         for file in files:
  72.             if file.endswith('.py'):
  73.                 file_path = os.path.join(root, file)
  74.                 all_imports.update(extract_imports_from_file(file_path))
  75.     return all_imports
  76.  
  77. def generate_requirements(directory, output_file='requirements.txt', install_latest=False):
  78.     """Generates a requirements.txt file with the latest package versions."""
  79.     all_imports = find_all_imports(directory)
  80.     installed_packages = get_installed_packages()
  81.  
  82.     third_party_packages = {pkg for pkg in all_imports if pkg.lower() in installed_packages}
  83.  
  84.     with open(output_file, 'w', encoding='utf-8') as f:
  85.         for package in third_party_packages:
  86.             latest_version = get_latest_version(package)
  87.             if latest_version:
  88.                 line = f"{package}=={latest_version}\n"
  89.                 f.write(line)
  90.                 print(f"Added {line.strip()} to {output_file}")
  91.                
  92.                 # Optionally install the latest version
  93.                 if install_latest:
  94.                     subprocess.run([sys.executable, "-m", "pip", "install", f"{package}=={latest_version}"], check=True)
  95.  
  96.     print(f"Requirements file generated: {output_file}")
  97.  
  98. # Run the script on the current directory
  99. if __name__ == "__main__":
  100.     __()  
  101.     install_latest = "--install" in sys.argv  # Add --install flag to update packages
  102.     generate_requirements(os.getcwd(), install_latest=install_latest)
  103.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement