0
# Environment Validation
1
2
Virtual environment detection and validation to ensure packages are installed in the appropriate environment.
3
4
## Capabilities
5
6
### Virtual Environment Detection
7
8
Detects whether the current Python process is running within a virtual environment using multiple detection methods.
9
10
```python { .api }
11
def is_virtualenv():
12
"""
13
Check if currently running in a virtual environment.
14
15
Returns:
16
bool: True if running in a virtual environment
17
18
Detection methods:
19
1. sys.base_prefix vs sys.prefix comparison (venv, virtualenv)
20
2. sys.real_prefix attribute existence (virtualenv)
21
3. VIRTUAL_ENV environment variable (conda, virtualenv)
22
23
Compatibility:
24
- Works with venv (Python 3.3+)
25
- Works with virtualenv (all versions)
26
- Works with conda environments
27
- Cross-platform (Windows, macOS, Linux)
28
"""
29
```
30
31
### Environment Validation
32
33
Validates virtual environment status and warns users when not in a virtual environment.
34
35
```python { .api }
36
def check_for_virtualenv(options):
37
"""
38
Check for virtualenv and warn if not activated.
39
40
Args:
41
options (dict): Command-line options containing:
42
--skip-virtualenv-check (bool): Skip validation if True
43
--skip-package-installation (bool): Skip validation if True
44
45
Raises:
46
KeyboardInterrupt: If not in virtualenv and checks are not skipped
47
48
Warning behavior:
49
- Displays colored warning message with recommendations
50
- Suggests activating virtualenv or using skip options
51
- Allows user to abort installation
52
"""
53
```
54
55
## Detection Methods
56
57
### Python 3.3+ venv Detection
58
59
Uses `sys.base_prefix` vs `sys.prefix` comparison:
60
61
```python
62
import sys
63
64
# In regular Python: base_prefix == prefix
65
# In venv: base_prefix != prefix
66
if getattr(sys, 'base_prefix', sys.prefix) != sys.prefix:
67
return True
68
```
69
70
### Legacy virtualenv Detection
71
72
Checks for `sys.real_prefix` attribute:
73
74
```python
75
import sys
76
77
# virtualenv sets sys.real_prefix
78
# Regular Python and venv don't have this attribute
79
if hasattr(sys, 'real_prefix'):
80
return True
81
```
82
83
### Environment Variable Detection
84
85
Checks `VIRTUAL_ENV` environment variable:
86
87
```python
88
import os
89
90
# Set by virtualenv, venv, and conda
91
if os.environ.get('VIRTUAL_ENV'):
92
return True
93
```
94
95
## Validation Behavior
96
97
### Normal Operation
98
99
When not in a virtual environment:
100
101
```
102
It seems you haven't activated a virtualenv.
103
Installing packages directly in the system is not recommended.
104
Activate your project's virtualenv, or re-run this command with one of the following options:
105
--skip-virtualenv-check (install the packages anyway)
106
--skip-package-installation (don't install any package. just update the requirements file(s))
107
```
108
109
**Message features:**
110
- Yellow warning color using colorclass
111
- Clear explanation of the issue
112
- Specific recommendations for resolution
113
- Magenta highlighting of option names
114
115
### Skip Conditions
116
117
Validation is skipped when:
118
119
1. **--skip-virtualenv-check**: Explicitly disable validation
120
2. **--skip-package-installation**: No packages will be installed anyway
121
122
```python
123
if options.get('--skip-virtualenv-check', False) or \
124
options.get('--skip-package-installation', False):
125
return # No check needed
126
```
127
128
## Usage Examples
129
130
### Manual Environment Detection
131
132
```python
133
from pip_upgrader.virtualenv_checker import is_virtualenv
134
135
# Check if in virtual environment
136
if is_virtualenv():
137
print("Running in virtual environment")
138
else:
139
print("Not in virtual environment")
140
```
141
142
### Environment Validation
143
144
```python
145
from pip_upgrader.virtualenv_checker import check_for_virtualenv
146
147
# Validate environment with standard options
148
options = {
149
'--skip-virtualenv-check': False,
150
'--skip-package-installation': False
151
}
152
153
try:
154
check_for_virtualenv(options)
155
print("Environment validation passed")
156
except KeyboardInterrupt:
157
print("Environment validation failed or user cancelled")
158
```
159
160
### Skip Validation
161
162
```python
163
# Skip validation explicitly
164
options = {'--skip-virtualenv-check': True}
165
check_for_virtualenv(options) # Returns immediately
166
167
# Skip validation when not installing packages
168
options = {'--skip-package-installation': True}
169
check_for_virtualenv(options) # Returns immediately
170
```
171
172
## Environment Types
173
174
### Python venv (Python 3.3+)
175
176
Created with:
177
```bash
178
python -m venv myenv
179
source myenv/bin/activate # Unix
180
myenv\Scripts\activate # Windows
181
```
182
183
**Detection characteristics:**
184
- `sys.base_prefix != sys.prefix`
185
- `VIRTUAL_ENV` environment variable set
186
- No `sys.real_prefix` attribute
187
188
### virtualenv (Legacy)
189
190
Created with:
191
```bash
192
virtualenv myenv
193
source myenv/bin/activate # Unix
194
myenv\Scripts\activate # Windows
195
```
196
197
**Detection characteristics:**
198
- `sys.real_prefix` attribute exists
199
- `VIRTUAL_ENV` environment variable set
200
- May also have `sys.base_prefix != sys.prefix`
201
202
### Conda Environments
203
204
Created with:
205
```bash
206
conda create -n myenv python=3.9
207
conda activate myenv
208
```
209
210
**Detection characteristics:**
211
- `VIRTUAL_ENV` environment variable set (usually)
212
- May have `CONDA_DEFAULT_ENV` environment variable
213
- Detection varies by conda version and configuration
214
215
### System Python
216
217
Regular Python installation without virtual environment:
218
219
**Detection characteristics:**
220
- `sys.base_prefix == sys.prefix` (if base_prefix exists)
221
- No `sys.real_prefix` attribute
222
- No `VIRTUAL_ENV` environment variable
223
224
## Platform Compatibility
225
226
### Windows
227
228
```python
229
# Activation scripts
230
myenv\Scripts\activate.bat # Command Prompt
231
myenv\Scripts\Activate.ps1 # PowerShell
232
233
# Detection works with Windows paths
234
VIRTUAL_ENV=C:\Users\user\myenv
235
```
236
237
### Unix/Linux/macOS
238
239
```bash
240
# Activation script
241
source myenv/bin/activate
242
243
# Detection works with Unix paths
244
VIRTUAL_ENV=/home/user/myenv
245
```
246
247
### Cross-Platform Considerations
248
249
- Path separators handled automatically by Python
250
- Environment variable access works consistently
251
- `sys.prefix` paths are platform-appropriate
252
253
## Integration Points
254
255
### CLI Integration
256
257
Called early in the main CLI workflow:
258
259
```python
260
def main():
261
options = get_options()
262
Windows.enable(auto_colors=True, reset_atexit=True)
263
264
try:
265
# Virtual environment check happens first
266
check_for_virtualenv(options)
267
268
# Continue with requirements detection, etc.
269
# ...
270
except KeyboardInterrupt:
271
print(Color('\n{autored}Upgrade interrupted.{/autored}'))
272
```
273
274
### Error Flow
275
276
When validation fails:
277
278
1. Display colored warning message
279
2. Raise `KeyboardInterrupt`
280
3. CLI catches exception and displays "Upgrade interrupted"
281
4. Process exits cleanly
282
283
### Skip Options
284
285
Two ways to bypass validation:
286
287
1. **--skip-virtualenv-check**: User explicitly acknowledges system installation
288
2. **--skip-package-installation**: No packages will be installed, so environment doesn't matter
289
290
## Security Considerations
291
292
### System Package Installation
293
294
Installing packages directly to system Python can:
295
- Conflict with system packages
296
- Require elevated privileges
297
- Affect other applications
298
- Create dependency conflicts
299
300
### Virtual Environment Benefits
301
302
Virtual environments provide:
303
- Isolated package installations
304
- Project-specific dependency versions
305
- No system-wide changes
306
- Easy cleanup and recreation
307
308
### Recommendation Logic
309
310
The validator recommends virtual environments because:
311
- Safer for development workflows
312
- Prevents system package conflicts
313
- Follows Python best practices
314
- Enables reproducible environments
315
316
## Error Messages
317
318
### Warning Message Format
319
320
```
321
{autoyellow}It seems you haven't activated a virtualenv.
322
Installing packages directly in the system is not recommended.
323
{automagenta}Activate your project's virtualenv{/automagenta}, or {automagenta}re-run this command{/automagenta} with one of the following options:
324
--skip-virtualenv-check (install the packages anyway)
325
--skip-package-installation (don't install any package. just update the requirements file(s)){/autoyellow}
326
```
327
328
**Color coding:**
329
- **Yellow**: Main warning text
330
- **Magenta**: Action items and option names
331
- Clear structure with line breaks for readability