0
# Configuration and Environment
1
2
Comprehensive configuration management, environment inspection, caching control, and package index operations for customized pip workflows.
3
4
## Capabilities
5
6
### Help and Completion Utilities
7
8
Get help information and enable shell command completion for pip commands.
9
10
```bash { .api }
11
# Show general help
12
pip help
13
14
# Show help for specific command
15
pip help install
16
pip help uninstall
17
18
# Generate completion script for bash
19
pip completion --bash
20
21
# Generate completion script for zsh
22
pip completion --zsh
23
24
# Generate completion script for fish
25
pip completion --fish
26
```
27
28
### Configuration Management
29
30
Manage pip configuration at global, user, and site levels with hierarchical settings.
31
32
```bash { .api }
33
# List all configuration
34
pip config list
35
36
# List configuration for specific scope
37
pip config --global list
38
pip config --user list
39
pip config --site list
40
41
# Get specific configuration value
42
pip config get global.index-url
43
pip config get install.user
44
45
# Set configuration values
46
pip config set global.index-url https://pypi.org/simple/
47
pip config set install.user true
48
pip config set global.timeout 60
49
50
# Unset configuration values
51
pip config unset global.index-url
52
pip config unset install.user
53
54
# Edit configuration file directly
55
pip config edit --global
56
pip config edit --user
57
pip config edit --site
58
```
59
60
Configuration hierarchy (highest to lowest priority):
61
1. Command-line options (`--index-url`)
62
2. Environment variables (`PIP_INDEX_URL`)
63
3. User configuration file
64
4. Global configuration file
65
5. Site configuration file
66
67
Configuration file locations:
68
```bash { .api }
69
# Global configuration
70
# Unix: /etc/pip.conf
71
# Windows: C:\ProgramData\pip\pip.ini
72
73
# User configuration
74
# Unix: ~/.config/pip/pip.conf or ~/.pip/pip.conf
75
# Windows: %APPDATA%\pip\pip.ini
76
77
# Site configuration
78
# Unix: $VIRTUAL_ENV/pip.conf
79
# Windows: %VIRTUAL_ENV%\pip.ini
80
```
81
82
### Environment Variables
83
84
Control pip behavior through comprehensive environment variable configuration.
85
86
```bash { .api }
87
# Index and repository configuration
88
export PIP_INDEX_URL=https://pypi.org/simple/
89
export PIP_EXTRA_INDEX_URL=https://test.pypi.org/simple/
90
export PIP_TRUSTED_HOST="pypi.org test.pypi.org"
91
export PIP_FIND_LINKS=/path/to/local/packages
92
93
# Installation behavior
94
export PIP_USER=1 # User installation
95
export PIP_REQUIRE_VIRTUALENV=1 # Require virtual environment
96
export PIP_NO_DEPS=1 # Skip dependencies
97
export PIP_UPGRADE=1 # Always upgrade
98
export PIP_FORCE_REINSTALL=1 # Force reinstall
99
100
# Build and binary options
101
export PIP_NO_BINARY=":all:" # Build from source
102
export PIP_ONLY_BINARY=":all:" # Only use wheels
103
export PIP_PREFER_BINARY=1 # Prefer binary packages
104
export PIP_NO_BUILD_ISOLATION=1 # Disable build isolation
105
106
# Caching and storage
107
export PIP_NO_CACHE_DIR=1 # Disable cache
108
export PIP_CACHE_DIR=/path/to/cache # Custom cache directory
109
110
# Network and timeouts
111
export PIP_TIMEOUT=60 # Connection timeout
112
export PIP_RETRIES=3 # Retry attempts
113
export PIP_PROXY=http://proxy:8080 # HTTP proxy
114
export PIP_CERT=/path/to/cert.pem # SSL certificate
115
116
# Output and logging
117
export PIP_QUIET=1 # Minimal output
118
export PIP_VERBOSE=1 # Verbose output
119
export PIP_LOG_FILE=/path/to/pip.log # Log file
120
export PIP_NO_COLOR=1 # Disable colored output
121
```
122
123
### Configuration File Format
124
125
Configuration files use INI format with section-based organization.
126
127
```ini
128
# Global pip configuration file
129
[global]
130
index-url = https://pypi.org/simple/
131
extra-index-url = https://test.pypi.org/simple/
132
trusted-host = pypi.org
133
test.pypi.org
134
timeout = 60
135
retries = 3
136
137
[install]
138
user = true
139
upgrade = true
140
find-links = /path/to/local/packages
141
142
[freeze]
143
exclude = pip
144
setuptools
145
wheel
146
147
[list]
148
format = columns
149
150
[wheel]
151
wheel-dir = /path/to/wheels
152
153
[hash]
154
algorithm = sha256
155
```
156
157
### Environment Inspection
158
159
Inspect Python environment, pip installation, and system information.
160
161
```bash { .api }
162
# Comprehensive environment inspection
163
pip inspect
164
165
# Debug information
166
pip debug
167
168
# Show pip version and location
169
pip --version
170
171
# Show configuration locations
172
pip config debug
173
```
174
175
Environment inspection provides:
176
- Python interpreter information
177
- Virtual environment details
178
- Installation paths and prefix
179
- Site packages directories
180
- Platform and architecture information
181
- Pip version and location
182
- Configuration file locations
183
- Installed packages with metadata
184
185
### Cache Management
186
187
Control pip's wheel cache for improved performance and storage management.
188
189
```bash { .api }
190
# Show cache information
191
pip cache info
192
193
# List cached packages
194
pip cache list
195
196
# List cache for specific package
197
pip cache list package_name
198
199
# Remove all cached files
200
pip cache purge
201
202
# Remove cache for specific package
203
pip cache remove package_name
204
205
# Remove cache with pattern matching
206
pip cache remove "django*"
207
208
# Show cache directory
209
pip cache dir
210
```
211
212
Cache operations:
213
```bash { .api }
214
# Custom cache directory
215
pip install --cache-dir /custom/cache package_name
216
217
# Disable cache for specific operation
218
pip install --no-cache-dir package_name
219
220
# Environment variable for cache directory
221
export PIP_CACHE_DIR=/custom/cache
222
```
223
224
### Index Operations
225
226
Inspect package information from package indexes without installation.
227
228
```bash { .api }
229
# Show available versions
230
pip index versions package_name
231
232
# Show versions from all configured indexes
233
pip index versions --pre package_name
234
235
# Show versions with extra index
236
pip index --extra-index-url https://test.pypi.org/simple/ versions package_name
237
```
238
239
### Authentication and Security
240
241
Configure authentication for private repositories and security settings.
242
243
```bash { .api }
244
# Using netrc for authentication
245
# Create ~/.netrc (Unix) or ~/_netrc (Windows)
246
# machine pypi.org
247
# login username
248
# password token
249
250
# Using keyring for password storage
251
pip install keyring
252
keyring set https://pypi.org/simple/ username
253
254
# Basic authentication in URL
255
pip install --index-url https://username:password@private.pypi.org/simple/ package_name
256
257
# Token authentication
258
pip install --index-url https://token@private.pypi.org/simple/ package_name
259
260
# Client certificates
261
pip install --cert /path/to/client.pem --client-cert /path/to/client.key package_name
262
263
# Trusted hosts (disable SSL verification)
264
pip install --trusted-host private.pypi.org package_name
265
```
266
267
### Proxy Configuration
268
269
Configure proxy settings for network environments.
270
271
```bash { .api }
272
# HTTP proxy
273
pip install --proxy http://proxy.company.com:8080 package_name
274
275
# HTTPS proxy
276
pip install --proxy https://proxy.company.com:8080 package_name
277
278
# Proxy with authentication
279
pip install --proxy http://user:password@proxy.company.com:8080 package_name
280
281
# No proxy for specific hosts
282
export NO_PROXY="localhost,127.0.0.1,.company.com"
283
284
# System proxy detection
285
# Pip automatically detects system proxy settings
286
```
287
288
### Virtual Environment Integration
289
290
Configure pip behavior in virtual environments.
291
292
```bash { .api }
293
# Require virtual environment
294
pip config set global.require-virtualenv true
295
export PIP_REQUIRE_VIRTUALENV=1
296
297
# Detect virtual environment
298
python -c "import sys; print(hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))"
299
300
# Virtual environment specific configuration
301
# Located at $VIRTUAL_ENV/pip.conf (Unix) or %VIRTUAL_ENV%\pip.ini (Windows)
302
```
303
304
### Programmatic Configuration
305
306
Manage pip configuration programmatically through subprocess calls.
307
308
```python { .api }
309
import subprocess
310
import sys
311
import os
312
from pathlib import Path
313
314
def get_config(key, scope='global'):
315
"""Get pip configuration value."""
316
cmd = [sys.executable, '-m', 'pip', 'config', f'--{scope}', 'get', key]
317
318
try:
319
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
320
return result.stdout.strip()
321
except subprocess.CalledProcessError:
322
return None
323
324
def set_config(key, value, scope='global'):
325
"""Set pip configuration value."""
326
cmd = [sys.executable, '-m', 'pip', 'config', f'--{scope}', 'set', key, value]
327
328
try:
329
subprocess.check_call(cmd)
330
print(f"Set {scope} config {key} = {value}")
331
except subprocess.CalledProcessError as e:
332
print(f"Failed to set config: {e}")
333
raise
334
335
def list_config(scope=None):
336
"""List pip configuration."""
337
cmd = [sys.executable, '-m', 'pip', 'config']
338
if scope:
339
cmd.append(f'--{scope}')
340
cmd.append('list')
341
342
try:
343
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
344
return result.stdout
345
except subprocess.CalledProcessError as e:
346
print(f"Failed to list config: {e}")
347
return None
348
349
def get_cache_info():
350
"""Get pip cache information."""
351
cmd = [sys.executable, '-m', 'pip', 'cache', 'info']
352
353
try:
354
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
355
return result.stdout
356
except subprocess.CalledProcessError as e:
357
print(f"Failed to get cache info: {e}")
358
return None
359
360
def purge_cache():
361
"""Purge pip cache."""
362
cmd = [sys.executable, '-m', 'pip', 'cache', 'purge']
363
364
try:
365
subprocess.check_call(cmd)
366
print("Cache purged successfully")
367
except subprocess.CalledProcessError as e:
368
print(f"Failed to purge cache: {e}")
369
raise
370
371
def setup_environment_config():
372
"""Set up comprehensive pip environment configuration."""
373
# Index configuration
374
os.environ['PIP_INDEX_URL'] = 'https://pypi.org/simple/'
375
os.environ['PIP_TIMEOUT'] = '60'
376
os.environ['PIP_RETRIES'] = '3'
377
378
# Installation preferences
379
os.environ['PIP_PREFER_BINARY'] = '1'
380
os.environ['PIP_UPGRADE_STRATEGY'] = 'eager'
381
382
# Cache configuration
383
cache_dir = Path.home() / '.pip_cache'
384
cache_dir.mkdir(exist_ok=True)
385
os.environ['PIP_CACHE_DIR'] = str(cache_dir)
386
387
print("Environment configuration set up")
388
389
def create_config_file(config_path, config_dict):
390
"""Create pip configuration file."""
391
from configparser import ConfigParser
392
393
config_path = Path(config_path)
394
config_path.parent.mkdir(parents=True, exist_ok=True)
395
396
config = ConfigParser()
397
398
for section, values in config_dict.items():
399
config.add_section(section)
400
for key, value in values.items():
401
config.set(section, key, str(value))
402
403
with open(config_path, 'w') as f:
404
config.write(f)
405
406
print(f"Configuration file created at {config_path}")
407
408
# Usage examples
409
index_url = get_config('global.index-url')
410
print(f"Current index URL: {index_url}")
411
412
set_config('global.timeout', '60')
413
set_config('install.user', 'true', scope='user')
414
415
config_output = list_config()
416
print("Current configuration:")
417
print(config_output)
418
419
cache_info = get_cache_info()
420
print("Cache information:")
421
print(cache_info)
422
423
# Set up environment
424
setup_environment_config()
425
426
# Create custom configuration file
427
config_data = {
428
'global': {
429
'index-url': 'https://pypi.org/simple/',
430
'timeout': 60,
431
'retries': 3
432
},
433
'install': {
434
'user': True,
435
'upgrade': True
436
}
437
}
438
create_config_file('~/.pip/pip.conf', config_data)
439
```
440
441
### Advanced Configuration Patterns
442
443
Complex configuration scenarios and best practices.
444
445
```python { .api }
446
import os
447
import subprocess
448
import sys
449
from pathlib import Path
450
451
class PipConfigManager:
452
"""Advanced pip configuration management."""
453
454
def __init__(self):
455
self.config_locations = self._get_config_locations()
456
457
def _get_config_locations(self):
458
"""Get pip configuration file locations."""
459
locations = {}
460
461
if os.name == 'nt': # Windows
462
locations['global'] = Path(os.environ.get('PROGRAMDATA', '')) / 'pip' / 'pip.ini'
463
locations['user'] = Path(os.environ['APPDATA']) / 'pip' / 'pip.ini'
464
else: # Unix-like
465
locations['global'] = Path('/etc/pip.conf')
466
locations['user'] = Path.home() / '.config' / 'pip' / 'pip.conf'
467
# Also check legacy location
468
legacy_user = Path.home() / '.pip' / 'pip.conf'
469
if legacy_user.exists():
470
locations['user'] = legacy_user
471
472
# Virtual environment configuration
473
venv_prefix = os.environ.get('VIRTUAL_ENV')
474
if venv_prefix:
475
if os.name == 'nt':
476
locations['site'] = Path(venv_prefix) / 'pip.ini'
477
else:
478
locations['site'] = Path(venv_prefix) / 'pip.conf'
479
480
return locations
481
482
def setup_development_environment(self):
483
"""Set up pip configuration for development."""
484
config = {
485
'global': {
486
'timeout': '60',
487
'retries': '3',
488
'prefer-binary': 'true'
489
},
490
'install': {
491
'upgrade': 'true',
492
'upgrade-strategy': 'eager'
493
},
494
'freeze': {
495
'exclude': 'pip setuptools wheel'
496
}
497
}
498
499
self._write_config('user', config)
500
501
# Set environment variables
502
os.environ.update({
503
'PIP_CACHE_DIR': str(Path.home() / '.pip_cache'),
504
'PIP_LOG_FILE': str(Path.home() / '.pip' / 'pip.log')
505
})
506
507
def setup_production_environment(self):
508
"""Set up pip configuration for production."""
509
config = {
510
'global': {
511
'timeout': '30',
512
'retries': '5',
513
'only-binary': ':all:',
514
'no-compile': 'true'
515
},
516
'install': {
517
'require-hashes': 'true',
518
'no-deps': 'false'
519
}
520
}
521
522
self._write_config('site', config)
523
524
def _write_config(self, scope, config_dict):
525
"""Write configuration to file."""
526
from configparser import ConfigParser
527
528
config_path = self.config_locations.get(scope)
529
if not config_path:
530
raise ValueError(f"Unknown scope: {scope}")
531
532
config_path.parent.mkdir(parents=True, exist_ok=True)
533
534
config = ConfigParser()
535
for section, values in config_dict.items():
536
config.add_section(section)
537
for key, value in values.items():
538
config.set(section, key, str(value))
539
540
with open(config_path, 'w') as f:
541
config.write(f)
542
543
# Usage
544
manager = PipConfigManager()
545
manager.setup_development_environment()
546
```