Repository navigation
Expand file tree
/
Copy pathautovenv.py
More file actions
294 lines (252 loc) · 12.2 KB
/
Copy pathautovenv.py
File metadata and controls
294 lines (252 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
'''
Support for rerunning the current python program in a venv.
This allows a python program to make use of packages from pypi.org without the
user having to manually create a venv, or install tools such as pipx or uv.
Example usage:
import autovenv
autovenv.enter(packages=['pytest', 'numpy'])
import numpy
...
'''
import shutil
import os
import platform
import subprocess
import sys
import sysconfig
import tempfile
import time
import venv
def _freethreads():
'''
Returns true if python is free-threads.
'''
Py_GIL_DISABLED = sysconfig.get_config_var('Py_GIL_DISABLED')
if Py_GIL_DISABLED == 1:
# Free threads build.
if not sys._is_gil_enabled(): # pylint:disable=protected-access,no-member
return True
def _bits():
return int.bit_length(sys.maxsize+1)
# When rerunning the current program we need to reset AUTOVENV_N back to its
# initial value; it can be defined if our parent process itself used autovenv.
#
_g_initial_AUTOVENV_N = os.environ.get('AUTOVENV_N', '0')
_g_t0 = time.time()
def enter(*,
create=2,
create_kwargs=None,
packages=None,
setupfn=None,
use_existing_venv=True,
venv_path=None,
verbose=False,
):
'''
Rerun current python program in a venv.
Args:
create:
Controls venv creation if <venv_path> is set:
1: If <venv_path> already exists then assume it is up to date:
* Don't call `venv.create()` to update the venv.
* Don't call <setupfn>.
* Don't install <packages> in the venv.
Behaviour is undefined if <venv_path> exists but is not a valid
venv.
2: Always create/update the venv.
Behaviour may be undefined if an existing venv is invalid.
3: Delete the venv if it exists, then create a new venv.
Example timings:
Create new venv: 3.5s.
Update existing venv: 2.0s.
Install single package lxml: 1.5s
Install single package lxml when already up to date: 1.1s.
create_kwargs:
None or kwargs to pass to `venv.create()` when we create/update the
venv - i.e. `venv.create(venv_path, **create_kwargs)`. If None we
use `dict(symlinks=(os.name!='nt'), with_pip=True)`.
packages:
List of packages to install in the venv before we rerun in it.
setupfn:
Optional function called after we create/update the venv and before
we rerun in the venv. Passed a `types.SimpleNamespace` as returned by
`venv.EnvBuilder.ensure_directories()`.
For example can be used instead of <packages> if more control is
required.
use_existing_venv:
If true (the default), we use any venv that we are already in even
if <venv_path> is set to a different venv. In this case we just
install packages and return.
venv_path:
Path of venv directory. If None (the default) we use a new and
unique venv directory which is deleted afterwards.
Otherwise we use `venv_path.format()` with these values:
python_version: platform.python_version(),
freethreads: 't' if python is freethreads else '' .
wordsize: e.g. 64 or 32.
verbose:
.
If environment has AUTOVENV_DOIT=0, we do nothing.
'''
def log(text):
if verbose:
t = time.time() - _g_t0
print(f'[+{t:.1f}] {text}', flush=1)
if AUTOVENV_DOIT := os.environ.get('AUTOVENV_DOIT') == '0':
log(f'autovenv.enter() doing nothing because {AUTOVENV_DOIT=}.')
return
# AUTOVENV_N and AUTOVENV_N_CURRENT are used to ensure correct behaviour
# if a a parent process and a child processes both use autovenv. They also
# ensure predictable behaviour if we are called multiple times by the same
# program.
#
if verbose >= 2:
log(f'{os.environ.get("AUTOVENV_N")=}')
log(f'{os.environ.get("AUTOVENV_N_CURRENT")=}')
AUTOVENV_N = int(os.environ.get('AUTOVENV_N', '0'))
AUTOVENV_N_CURRENT = int(os.environ.get('AUTOVENV_N_CURRENT', '0'))
AUTOVENV_VENV_PATH = os.environ.get('AUTOVENV_VENV_PATH', None)
AUTOVENV_N += 1
os.environ['AUTOVENV_N'] = str(AUTOVENV_N)
if venv_path:
venv_path = venv_path.format(
python_version = platform.python_version(),
freethreads = 't' if _freethreads() else '',
wordsize = _bits(),
)
if verbose >= 2:
log(f'autovenv.enter(): Starting:')
log(f'autovenv.enter(): {AUTOVENV_N=}')
log(f'autovenv.enter(): {AUTOVENV_N_CURRENT=}')
log(f'autovenv.enter(): {AUTOVENV_VENV_PATH=}')
log(f'autovenv.enter(): {sys.prefix=}')
log(f'autovenv.enter(): {venv_path=}')
log(f'autovenv.enter(): {packages=}')
if AUTOVENV_N < AUTOVENV_N_CURRENT:
log(f'autovenv.enter(): skipping earlier call.')
return
elif AUTOVENV_N == AUTOVENV_N_CURRENT:
log(f'autovenv.enter(): Have entered autovenv venv {AUTOVENV_VENV_PATH!r}.')
assert AUTOVENV_VENV_PATH
assert os.path.realpath(sys.prefix) == os.path.realpath(AUTOVENV_VENV_PATH)
return
elif venv_path and os.path.realpath(venv_path) == os.path.realpath(sys.prefix):
log(f'autovenv.enter(): already in requested venv - sys.prefix is same as venv_path (with os.path.realpath()).')
return
else:
assert AUTOVENV_N == AUTOVENV_N_CURRENT + 1, f'{AUTOVENV_N=} {AUTOVENV_N_CURRENT=}'
# We are not in an autovenv venv so create/update it and rerun
# ourselves in it.
if sys.prefix == sys.base_prefix:
log(f'autovenv.enter(): Not in a venv.')
else:
log(f'autovenv.enter(): In unrelated venv, {sys.prefix=}.')
def setup(venv_path, packages, create):
'''
Create/update venv, modify os.environ so that any subprocesses
still run inside the venv, and return the types.SimpleNamespace
from venv.EnvBuilder.ensure_directories().
'''
venv_path = os.path.abspath(venv_path)
do_setup_venv = True
# Create/update venv.
if create == 3:
# Delete any existing venv.
shutil.rmtree(venv_path, ignore_errors=1)
assert not os.path.exists(venv_path)
if create == 1 and os.path.isdir(venv_path):
# Don't update existing venv, don't call <setupfn>, don't
# install <packages>.
do_setup_venv = False
log(f'autovenv.enter(): Will not updating existing venv or call setupfn or install packages, because {create=}.')
else:
if create_kwargs is None:
# Need to set symlinks to mimic what `python -m venv` does,
# otherwise we fail to update an existing venv on linux
# because of `shutil.SameFileError`.
symlinks = os.name != 'nt'
kwargs = dict(symlinks=symlinks, with_pip=True)
else:
kwargs = create_kwargs
log(f'autovenv.enter(): {venv_path=}: Create/update venv with venv.create(), {kwargs=}.')
venv.create(venv_path, **kwargs)
# We need a builder context even if we haven't
# called venv.create(), so make a dummy call of
# `builder.ensure_directories()` here.
builder = venv.EnvBuilder()
builder_context = builder.ensure_directories(venv_path)
# Enter the venv by adding to the environment.
log(f'autovenv.enter(): {venv_path=}: Updating environ to enter venv.')
os.environ['PATH'] = builder_context.bin_path + os.pathsep + os.environ['PATH']
os.environ['VIRTUAL_ENV'] = venv_path
# Also set AUTOVENV_VENV_PATH so we know later on if we are
# rerunning in the autovenv venv
os.environ['AUTOVENV_VENV_PATH'] = venv_path
# Setup/install packages.
if do_setup_venv:
#log(f'autovenv.enter(): {do_setup_venv=} {setupfn=} {packages=}.')
if setupfn:
log(f'Calling venv setupfn().')
setupfn(builder_context)
if packages:
if isinstance(packages, str):
packages = [packages]
log(f'autovenv.enter(): {venv_path=}: Installing packages: {packages}.')
subprocess.run(
[builder_context.env_exe, '-m', 'pip', 'install', '--quiet', '--upgrade']
+ packages,
check=1,
)
else:
log(f'autovenv.enter(): {venv_path=}: No packages to install.')
# We are about to rerun the current process.
#
# Set AUTOVENV_N_CURRENT to current AUTOVENV_N so that we know what
# to do when we are called again.
#
# We also need to reset AUTOVENV_N back to its initial value.
#
AUTOVENV_N_CURRENT = AUTOVENV_N
os.environ['AUTOVENV_N_CURRENT'] = str(AUTOVENV_N_CURRENT)
os.environ['AUTOVENV_N'] = _g_initial_AUTOVENV_N
return builder_context
if use_existing_venv and sys.prefix != sys.base_prefix:
# Just install packages into the current venv.
log(f'autovenv.enter(): Using existing venv because {use_existing_venv=}. {sys.prefix=}.')
if packages:
if isinstance(packages, str):
packages = [packages]
log(f'autovenv.enter(): Installing packages into current venv: {packages}.')
subprocess.run(
[sys.executable, '-m', 'pip', 'install', '--quiet', '--upgrade']
+ packages,
check=1,
)
AUTOVENV_N_CURRENT = AUTOVENV_N
os.environ['AUTOVENV_N_CURRENT'] = str(AUTOVENV_N_CURRENT)
elif venv_path:
builder_context = setup(venv_path, packages, create=create)
# Rerun the current python program in the venv.
if platform.system() == 'Windows':
# Have seen odd behaviour with os.execve() where empty string
# args appear to be removed. So we use a child process
# instead.
log(f'autovenv.enter(): Rerunning with subprocess.run(), {builder_context.env_exe=}.')
cp = subprocess.run([builder_context.env_exe] + sys.argv, check=0)
sys.exit(cp.returncode)
else:
log(f'autovenv.enter(): Rerunning with os.execv(), {builder_context.env_exe=}.')
os.execv(builder_context.env_exe, [builder_context.env_exe] + sys.argv)
else:
# Use tempfile.TemporaryDirectory() to create venv directory that
# will be automatically removed after use.
with tempfile.TemporaryDirectory(prefix='autovenv-') as venv_path: # pylint: disable=redefined-argument-from-local.
log(f'autovenv.enter(): Using unique venv directory: {venv_path}')
builder_context = setup(venv_path, packages, create=2)
# Rerun the current program in the venv. We need to use
# a child process instead of os.execve(), so that our
# tempfile.TemporaryDirectory gets to delete the venv
# directory.
log(f'autovenv.enter(): Rerunning with subprocess.run(), {builder_context.env_exe=}.')
cp = subprocess.run([builder_context.env_exe] + sys.argv, check=0)
sys.exit(cp.returncode)