0
# Package Management
1
2
Comprehensive package management operations including uninstallation, package listing, information queries, and dependency analysis.
3
4
## Capabilities
5
6
### Package Uninstallation
7
8
Remove packages and their dependencies with confirmation and batch operations.
9
10
```bash { .api }
11
# Uninstall single package
12
pip uninstall package_name
13
14
# Uninstall multiple packages
15
pip uninstall package1 package2 package3
16
17
# Uninstall without confirmation
18
pip uninstall -y package_name
19
20
# Uninstall from requirements file
21
pip uninstall -r requirements.txt
22
23
# Uninstall from requirements file without confirmation
24
pip uninstall -y -r requirements.txt
25
```
26
27
### Package Listing
28
29
List installed packages with various filtering and formatting options.
30
31
```bash { .api }
32
# List all installed packages
33
pip list
34
35
# List outdated packages
36
pip list --outdated
37
38
# List up-to-date packages
39
pip list --uptodate
40
41
# List editable packages
42
pip list --editable
43
44
# List local packages (not from PyPI)
45
pip list --local
46
47
# List user-installed packages
48
pip list --user
49
50
# Format output
51
pip list --format=columns # Default format
52
pip list --format=freeze # Requirements format
53
pip list --format=json # JSON format
54
55
# Exclude specific packages
56
pip list --exclude package_name
57
58
# Include pre-release versions
59
pip list --pre
60
```
61
62
Output formats:
63
```bash { .api }
64
# Columns format (default)
65
Package Version
66
---------- -------
67
requests 2.28.1
68
urllib3 1.26.12
69
70
# Freeze format
71
requests==2.28.1
72
urllib3==1.26.12
73
74
# JSON format
75
[{"name": "requests", "version": "2.28.1"}, {"name": "urllib3", "version": "1.26.12"}]
76
```
77
78
### Package Information
79
80
Display detailed information about installed packages.
81
82
```bash { .api }
83
# Show package information
84
pip show package_name
85
86
# Show multiple packages
87
pip show package1 package2
88
89
# Show package files
90
pip show --files package_name
91
92
# Verbose output
93
pip show --verbose package_name
94
```
95
96
Package information includes:
97
- Name and version
98
- Summary and description
99
- Author and maintainer information
100
- License
101
- Location (installation path)
102
- Dependencies (requires)
103
- Reverse dependencies (required-by)
104
- Files (with --files option)
105
106
### Dependency Checking
107
108
Verify package dependencies and identify conflicts.
109
110
```bash { .api }
111
# Check for dependency conflicts
112
pip check
113
114
# Check specific packages
115
pip check package_name
116
```
117
118
Check output shows:
119
- Missing dependencies
120
- Version conflicts
121
- Circular dependencies
122
123
### Environment Inspection
124
125
Inspect the Python environment and pip configuration.
126
127
```bash { .api }
128
# Inspect environment
129
pip inspect
130
131
# Show detailed environment information
132
pip debug
133
```
134
135
Environment inspection provides:
136
- Installed packages with metadata
137
- Python version and executable
138
- Virtual environment information
139
- Platform information
140
- Installation paths
141
142
### Package Search (Deprecated)
143
144
*Note: pip search was disabled due to PyPI limitations. Use alternative methods.*
145
146
```bash { .api }
147
# Search PyPI (deprecated - returns error)
148
pip search search_term
149
```
150
151
Alternative search methods:
152
```bash { .api }
153
# Use PyPI website
154
# Visit https://pypi.org and search
155
156
# Use pip index (limited functionality)
157
pip index versions package_name
158
```
159
160
### Freeze Operations
161
162
Generate requirements files from installed packages.
163
164
```bash { .api }
165
# Generate requirements for all packages
166
pip freeze
167
168
# Save to requirements file
169
pip freeze > requirements.txt
170
171
# Exclude specific packages
172
pip freeze --exclude package_name
173
174
# Local packages only
175
pip freeze --local
176
177
# User packages only
178
pip freeze --user
179
180
# Include all packages (including pip itself)
181
pip freeze --all
182
```
183
184
Freeze output format:
185
```text
186
certifi==2022.9.24
187
charset-normalizer==2.1.1
188
idna==3.4
189
requests==2.28.1
190
urllib3==1.26.12
191
```
192
193
### Programmatic Package Management
194
195
Use subprocess for programmatic package management operations.
196
197
```python { .api }
198
import subprocess
199
import sys
200
import json
201
202
def list_packages(format_type='json'):
203
"""List installed packages."""
204
cmd = [sys.executable, '-m', 'pip', 'list', f'--format={format_type}']
205
206
try:
207
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
208
if format_type == 'json':
209
return json.loads(result.stdout)
210
return result.stdout
211
except subprocess.CalledProcessError as e:
212
print(f"Failed to list packages: {e}")
213
return None
214
215
def get_package_info(package_name):
216
"""Get information about a specific package."""
217
cmd = [sys.executable, '-m', 'pip', 'show', package_name]
218
219
try:
220
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
221
return result.stdout
222
except subprocess.CalledProcessError as e:
223
print(f"Package {package_name} not found: {e}")
224
return None
225
226
def uninstall_package(package_name, confirm=False):
227
"""Uninstall a package."""
228
cmd = [sys.executable, '-m', 'pip', 'uninstall', package_name]
229
if not confirm:
230
cmd.append('-y')
231
232
try:
233
subprocess.check_call(cmd)
234
print(f"Successfully uninstalled {package_name}")
235
except subprocess.CalledProcessError as e:
236
print(f"Failed to uninstall {package_name}: {e}")
237
raise
238
239
def check_dependencies():
240
"""Check for dependency conflicts."""
241
cmd = [sys.executable, '-m', 'pip', 'check']
242
243
try:
244
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
245
print("No dependency conflicts found")
246
return True
247
except subprocess.CalledProcessError as e:
248
print(f"Dependency conflicts found:\n{e.stdout}")
249
return False
250
251
def freeze_requirements(output_file=None):
252
"""Generate requirements from installed packages."""
253
cmd = [sys.executable, '-m', 'pip', 'freeze']
254
255
try:
256
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
257
requirements = result.stdout
258
259
if output_file:
260
with open(output_file, 'w') as f:
261
f.write(requirements)
262
print(f"Requirements saved to {output_file}")
263
264
return requirements
265
except subprocess.CalledProcessError as e:
266
print(f"Failed to freeze requirements: {e}")
267
return None
268
269
# Usage examples
270
packages = list_packages()
271
print(f"Found {len(packages)} installed packages")
272
273
info = get_package_info('requests')
274
if info:
275
print(info)
276
277
check_dependencies()
278
freeze_requirements('requirements.txt')
279
```
280
281
### Batch Operations
282
283
Perform operations on multiple packages efficiently.
284
285
```python { .api }
286
import subprocess
287
import sys
288
289
def batch_uninstall(package_list, confirm=False):
290
"""Uninstall multiple packages."""
291
cmd = [sys.executable, '-m', 'pip', 'uninstall'] + package_list
292
if not confirm:
293
cmd.append('-y')
294
295
try:
296
subprocess.check_call(cmd)
297
print(f"Successfully uninstalled: {', '.join(package_list)}")
298
except subprocess.CalledProcessError as e:
299
print(f"Failed to uninstall packages: {e}")
300
raise
301
302
def get_outdated_packages():
303
"""Get list of outdated packages."""
304
cmd = [sys.executable, '-m', 'pip', 'list', '--outdated', '--format=json']
305
306
try:
307
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
308
return json.loads(result.stdout)
309
except subprocess.CalledProcessError as e:
310
print(f"Failed to get outdated packages: {e}")
311
return []
312
313
def upgrade_all_outdated():
314
"""Upgrade all outdated packages."""
315
outdated = get_outdated_packages()
316
317
for package in outdated:
318
package_name = package['name']
319
cmd = [sys.executable, '-m', 'pip', 'install', '--upgrade', package_name]
320
321
try:
322
subprocess.check_call(cmd)
323
print(f"Upgraded {package_name}")
324
except subprocess.CalledProcessError as e:
325
print(f"Failed to upgrade {package_name}: {e}")
326
327
# Usage
328
outdated = get_outdated_packages()
329
print(f"Found {len(outdated)} outdated packages")
330
331
# Upgrade all (use with caution)
332
# upgrade_all_outdated()
333
```