Skip to content

Instantly share code, notes, and snippets.

@uogbuji
Created January 30, 2025 23:28
Show Gist options
  • Save uogbuji/a21cc3f296f79fbba5c33d53191aa9e8 to your computer and use it in GitHub Desktop.
Save uogbuji/a21cc3f296f79fbba5c33d53191aa9e8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
'''
update_constraints.py
Helps manage Python package version constraints by updating based on currently installed versions.
Features:
- Caution - creates a temporary file rather than overwriting your original constraints
- Preserves only packages that were in the original constraints file—doesn't add new ones
- Error handling for packages that might be missing
# Usage
```sh
chmod +x update_constraints.py # One time, after download
pip install fire # Required, if not already installed
./update_constraints.py path/to/your/constraints.txt
'''
import subprocess
import tempfile
import fire
def update_constraints(constraints_file):
# Read existing constraints
with open(constraints_file, 'r') as f:
existing_packages = [line.split('==')[0] for line in f if '==' in line]
# Get current versions of installed packages
result = subprocess.run(['pip', 'freeze'], capture_output=True, text=True)
current_versions = dict(line.split('==') for line in result.stdout.splitlines() if '==' in line)
# Create updated constraints
updated_constraints = []
for package in existing_packages:
if package in current_versions:
updated_constraints.append(f'{package}=={current_versions[package]}')
else:
print(f'Warning: {package} not found in current environment')
# Write updated constraints to a temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='-constraints.txt') as temp_file:
for line in updated_constraints:
temp_file.write(line + '\n')
temp_file_name = temp_file.name
print(f'Updated constraints written to {temp_file_name}')
print('Review the file and replace your original constraints.txt if satisfied')
if __name__ == '__main__':
fire.Fire(update_constraints)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment