blob: 28962d39934d0216c00472d363e22d2b3c164288 [file] [log] [blame]
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001:mod:`venv` --- Creation of virtual environments
2================================================
3
4.. module:: venv
5 :synopsis: Creation of virtual environments.
6.. moduleauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk>
7.. sectionauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk>
8
9
10.. index:: pair: Environments; virtual
11
12.. versionadded:: 3.3
13
Ned Deily38861202013-06-11 14:38:39 -070014**Source code:** :source:`Lib/venv`
Vinay Sajip7ded1f02012-05-26 03:45:29 +010015
16--------------
17
Georg Brandldbab58f2012-06-24 16:37:59 +020018The :mod:`venv` module provides support for creating lightweight "virtual
19environments" with their own site directories, optionally isolated from system
20site directories. Each virtual environment has its own Python binary (allowing
21creation of environments with various Python versions) and can have its own
22independent set of installed Python packages in its site directories.
23
Vinay Sajipa7045822013-09-06 09:50:43 +010024See :pep:`405` for more information about Python virtual environments.
Vinay Sajip7ded1f02012-05-26 03:45:29 +010025
26Creating virtual environments
27-----------------------------
28
Vinay Sajipc4618e32012-07-10 08:21:07 +010029.. include:: /using/venv-create.inc
Vinay Sajip7ded1f02012-05-26 03:45:29 +010030
Vinay Sajipa945ad12012-07-09 09:24:59 +010031
Vinay Sajipcd9b7462012-07-09 10:37:01 +010032.. _venv-def:
33
Vinay Sajipa945ad12012-07-09 09:24:59 +010034.. note:: A virtual environment (also called a ``venv``) is a Python
35 environment such that the Python interpreter, libraries and scripts
36 installed into it are isolated from those installed in other virtual
37 environments, and (by default) any libraries installed in a "system" Python,
38 i.e. one which is installed as part of your operating system.
39
40 A venv is a directory tree which contains Python executable files and
41 other files which indicate that it is a venv.
42
Vinay Sajipc4618e32012-07-10 08:21:07 +010043 Common installation tools such as ``Distribute`` and ``pip`` work as
Vinay Sajipa945ad12012-07-09 09:24:59 +010044 expected with venvs - i.e. when a venv is active, they install Python
45 packages into the venv without needing to be told to do so explicitly.
Vinay Sajipc4618e32012-07-10 08:21:07 +010046 Of course, you need to install them into the venv first: this could be
47 done by running ``distribute_setup.py`` with the venv activated,
48 followed by running ``easy_install pip``. Alternatively, you could download
49 the source tarballs and run ``python setup.py install`` after unpacking,
50 with the venv activated.
Vinay Sajipa945ad12012-07-09 09:24:59 +010051
52 When a venv is active (i.e. the venv's Python interpreter is running), the
53 attributes :attr:`sys.prefix` and :attr:`sys.exec_prefix` point to the base
54 directory of the venv, whereas :attr:`sys.base_prefix` and
55 :attr:`sys.base_exec_prefix` point to the non-venv Python installation
56 which was used to create the venv. If a venv is not active, then
57 :attr:`sys.prefix` is the same as :attr:`sys.base_prefix` and
58 :attr:`sys.exec_prefix` is the same as :attr:`sys.base_exec_prefix` (they
59 all point to a non-venv Python installation).
60
Georg Brandl521ed522013-05-12 12:36:07 +020061 When a venv is active, any options that change the installation path will be
62 ignored from all distutils configuration files to prevent projects being
63 inadvertently installed outside of the virtual environment.
64
Vinay Sajipa7045822013-09-06 09:50:43 +010065 When working in a command shell, users can make a venv active by running an
66 ``activate`` script in the venv's executables directory (the precise filename
67 is shell-dependent), which prepends the venv's directory for executables to
68 the ``PATH`` environment variable for the running shell. There should be no
69 need in other circumstances to activate a venv -- scripts installed into
70 venvs have a shebang line which points to the venv's Python interpreter. This
71 means that the script will run with that interpreter regardless of the value
72 of ``PATH``. On Windows, shebang line processing is supported if you have the
73 Python Launcher for Windows installed (this was added to Python in 3.3 - see
74 :pep:`397` for more details). Thus, double-clicking an installed script in
75 a Windows Explorer window should run the script with the correct interpreter
76 without there needing to be any reference to its venv in ``PATH``.
77
Vinay Sajip7ded1f02012-05-26 03:45:29 +010078
79API
80---
81
Vinay Sajip7ded1f02012-05-26 03:45:29 +010082.. highlight:: python
83
Georg Brandldbab58f2012-06-24 16:37:59 +020084The high-level method described above makes use of a simple API which provides
85mechanisms for third-party virtual environment creators to customize environment
86creation according to their needs, the :class:`EnvBuilder` class.
Vinay Sajip7ded1f02012-05-26 03:45:29 +010087
Georg Brandldbab58f2012-06-24 16:37:59 +020088.. class:: EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010089
Georg Brandldbab58f2012-06-24 16:37:59 +020090 The :class:`EnvBuilder` class accepts the following keyword arguments on
91 instantiation:
Vinay Sajip7ded1f02012-05-26 03:45:29 +010092
Georg Brandldbab58f2012-06-24 16:37:59 +020093 * ``system_site_packages`` -- a Boolean value indicating that the system Python
94 site-packages should be available to the environment (defaults to ``False``).
Vinay Sajip7ded1f02012-05-26 03:45:29 +010095
Georg Brandldbab58f2012-06-24 16:37:59 +020096 * ``clear`` -- a Boolean value which, if True, will delete any existing target
97 directory instead of raising an exception (defaults to ``False``).
Vinay Sajip7ded1f02012-05-26 03:45:29 +010098
Georg Brandldbab58f2012-06-24 16:37:59 +020099 * ``symlinks`` -- a Boolean value indicating whether to attempt to symlink the
100 Python binary (and any necessary DLLs or other binaries,
101 e.g. ``pythonw.exe``), rather than copying. Defaults to ``True`` on Linux and
Vinay Sajip90db6612012-07-17 17:33:46 +0100102 Unix systems, but ``False`` on Windows.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100103
Vinay Sajipa945ad12012-07-09 09:24:59 +0100104 * ``upgrade`` -- a Boolean value which, if True, will upgrade an existing
105 environment with the running Python - for use when that Python has been
106 upgraded in-place (defaults to ``False``).
107
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100108
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100109
Georg Brandldbab58f2012-06-24 16:37:59 +0200110 Creators of third-party virtual environment tools will be free to use the
111 provided ``EnvBuilder`` class as a base class.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100112
Georg Brandldbab58f2012-06-24 16:37:59 +0200113 The returned env-builder is an object which has a method, ``create``:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100114
Georg Brandldbab58f2012-06-24 16:37:59 +0200115 .. method:: create(env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100116
Georg Brandldbab58f2012-06-24 16:37:59 +0200117 This method takes as required argument the path (absolute or relative to
118 the current directory) of the target directory which is to contain the
119 virtual environment. The ``create`` method will either create the
120 environment in the specified directory, or raise an appropriate
121 exception.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100122
Georg Brandldbab58f2012-06-24 16:37:59 +0200123 The ``create`` method of the ``EnvBuilder`` class illustrates the hooks
124 available for subclass customization::
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100125
Georg Brandldbab58f2012-06-24 16:37:59 +0200126 def create(self, env_dir):
127 """
128 Create a virtualized Python environment in a directory.
129 env_dir is the target directory to create an environment in.
130 """
131 env_dir = os.path.abspath(env_dir)
132 context = self.create_directories(env_dir)
133 self.create_configuration(context)
134 self.setup_python(context)
135 self.setup_scripts(context)
136 self.post_setup(context)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100137
Georg Brandldbab58f2012-06-24 16:37:59 +0200138 Each of the methods :meth:`create_directories`,
139 :meth:`create_configuration`, :meth:`setup_python`,
140 :meth:`setup_scripts` and :meth:`post_setup` can be overridden.
141
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100142 .. method:: ensure_directories(env_dir)
Georg Brandldbab58f2012-06-24 16:37:59 +0200143
144 Creates the environment directory and all necessary directories, and
145 returns a context object. This is just a holder for attributes (such as
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100146 paths), for use by the other methods. The directories are allowed to
147 exist already, as long as either ``clear`` or ``upgrade`` were
148 specified to allow operating on an existing environment directory.
Georg Brandldbab58f2012-06-24 16:37:59 +0200149
150 .. method:: create_configuration(context)
151
152 Creates the ``pyvenv.cfg`` configuration file in the environment.
153
154 .. method:: setup_python(context)
155
156 Creates a copy of the Python executable (and, under Windows, DLLs) in
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100157 the environment. On a POSIX system, if a specific executable
158 ``python3.x`` was used, symlinks to ``python`` and ``python3`` will be
159 created pointing to that executable, unless files with those names
160 already exist.
Georg Brandldbab58f2012-06-24 16:37:59 +0200161
162 .. method:: setup_scripts(context)
163
164 Installs activation scripts appropriate to the platform into the virtual
165 environment.
166
167 .. method:: post_setup(context)
168
169 A placeholder method which can be overridden in third party
170 implementations to pre-install packages in the virtual environment or
171 perform other post-creation steps.
172
173 In addition, :class:`EnvBuilder` provides this utility method that can be
174 called from :meth:`setup_scripts` or :meth:`post_setup` in subclasses to
175 assist in installing custom scripts into the virtual environment.
176
177 .. method:: install_scripts(context, path)
178
179 *path* is the path to a directory that should contain subdirectories
180 "common", "posix", "nt", each containing scripts destined for the bin
181 directory in the environment. The contents of "common" and the
182 directory corresponding to :data:`os.name` are copied after some text
183 replacement of placeholders:
184
185 * ``__VENV_DIR__`` is replaced with the absolute path of the environment
186 directory.
187
188 * ``__VENV_NAME__`` is replaced with the environment name (final path
189 segment of environment directory).
190
191 * ``__VENV_BIN_NAME__`` is replaced with the name of the bin directory
192 (either ``bin`` or ``Scripts``).
193
194 * ``__VENV_PYTHON__`` is replaced with the absolute path of the
195 environment's executable.
196
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100197 The directories are allowed to exist (for when an existing environment
198 is being upgraded).
Georg Brandldbab58f2012-06-24 16:37:59 +0200199
200There is also a module-level convenience function:
201
202.. function:: create(env_dir, system_site_packages=False, clear=False, symlinks=False)
203
204 Create an :class:`EnvBuilder` with the given keyword arguments, and call its
205 :meth:`~EnvBuilder.create` method with the *env_dir* argument.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000206
207An example of extending ``EnvBuilder``
208--------------------------------------
209
210The following script shows how to extend :class:`EnvBuilder` by implementing a
Vinay Sajip3c557f22013-07-12 20:54:25 +0100211subclass which installs setuptools and pip into a created venv::
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000212
213 import os
214 import os.path
215 from subprocess import Popen, PIPE
216 import sys
217 from threading import Thread
218 from urllib.parse import urlparse
219 from urllib.request import urlretrieve
220 import venv
221
Vinay Sajip3c557f22013-07-12 20:54:25 +0100222 class ExtendedEnvBuilder(venv.EnvBuilder):
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000223 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100224 This builder installs setuptools and pip so that you can pip or
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000225 easy_install other packages into the created environment.
226
Vinay Sajip3c557f22013-07-12 20:54:25 +0100227 :param nodist: If True, setuptools and pip are not installed into the
228 created environment.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000229 :param nopip: If True, pip is not installed into the created
230 environment.
Vinay Sajip3c557f22013-07-12 20:54:25 +0100231 :param progress: If setuptools or pip are installed, the progress of the
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000232 installation can be monitored by passing a progress
233 callable. If specified, it is called with two
234 arguments: a string indicating some progress, and a
235 context indicating where the string is coming from.
236 The context argument can have one of three values:
237 'main', indicating that it is called from virtualize()
238 itself, and 'stdout' and 'stderr', which are obtained
239 by reading lines from the output streams of a subprocess
240 which is used to install the app.
241
242 If a callable is not specified, default progress
243 information is output to sys.stderr.
244 """
245
246 def __init__(self, *args, **kwargs):
247 self.nodist = kwargs.pop('nodist', False)
248 self.nopip = kwargs.pop('nopip', False)
249 self.progress = kwargs.pop('progress', None)
250 self.verbose = kwargs.pop('verbose', False)
251 super().__init__(*args, **kwargs)
252
253 def post_setup(self, context):
254 """
255 Set up any packages which need to be pre-installed into the
256 environment being created.
257
258 :param context: The information for the environment creation request
259 being processed.
260 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100261 os.environ['VIRTUAL_ENV'] = context.env_dir
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000262 if not self.nodist:
Vinay Sajip3c557f22013-07-12 20:54:25 +0100263 self.install_setuptools(context)
264 # Can't install pip without setuptools
265 if not self.nopip and not self.nodist:
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000266 self.install_pip(context)
267
268 def reader(self, stream, context):
269 """
270 Read lines from a subprocess' output stream and either pass to a progress
271 callable (if specified) or write progress information to sys.stderr.
272 """
273 progress = self.progress
274 while True:
275 s = stream.readline()
276 if not s:
277 break
278 if progress is not None:
279 progress(s, context)
280 else:
281 if not self.verbose:
282 sys.stderr.write('.')
283 else:
284 sys.stderr.write(s.decode('utf-8'))
285 sys.stderr.flush()
Vinay Sajipad6bb032013-07-12 21:44:35 +0100286 stream.close()
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000287
288 def install_script(self, context, name, url):
289 _, _, path, _, _, _ = urlparse(url)
290 fn = os.path.split(path)[-1]
291 binpath = context.bin_path
292 distpath = os.path.join(binpath, fn)
293 # Download script into the env's binaries folder
294 urlretrieve(url, distpath)
295 progress = self.progress
Vinay Sajip3c557f22013-07-12 20:54:25 +0100296 if self.verbose:
297 term = '\n'
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000298 else:
Vinay Sajip3c557f22013-07-12 20:54:25 +0100299 term = ''
300 if progress is not None:
301 progress('Installing %s ...%s' % (name, term), 'main')
302 else:
303 sys.stderr.write('Installing %s ...%s' % (name, term))
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000304 sys.stderr.flush()
305 # Install in the env
306 args = [context.env_exe, fn]
307 p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
308 t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
309 t1.start()
310 t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
311 t2.start()
312 p.wait()
313 t1.join()
314 t2.join()
315 if progress is not None:
316 progress('done.', 'main')
317 else:
318 sys.stderr.write('done.\n')
319 # Clean up - no longer needed
320 os.unlink(distpath)
321
Vinay Sajip3c557f22013-07-12 20:54:25 +0100322 def install_setuptools(self, context):
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000323 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100324 Install setuptools in the environment.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000325
326 :param context: The information for the environment creation request
327 being processed.
328 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100329 url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
330 self.install_script(context, 'setuptools', url)
331 # clear up the setuptools archive which gets downloaded
332 pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000333 files = filter(pred, os.listdir(context.bin_path))
334 for f in files:
335 f = os.path.join(context.bin_path, f)
336 os.unlink(f)
337
338 def install_pip(self, context):
339 """
340 Install pip in the environment.
341
342 :param context: The information for the environment creation request
343 being processed.
344 """
345 url = 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py'
346 self.install_script(context, 'pip', url)
347
348 def main(args=None):
349 compatible = True
350 if sys.version_info < (3, 3):
351 compatible = False
352 elif not hasattr(sys, 'base_prefix'):
353 compatible = False
354 if not compatible:
355 raise ValueError('This script is only for use with '
356 'Python 3.3 or later')
357 else:
358 import argparse
359
360 parser = argparse.ArgumentParser(prog=__name__,
361 description='Creates virtual Python '
362 'environments in one or '
363 'more target '
364 'directories.')
365 parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
366 help='A directory to create the environment in.')
Vinay Sajip3c557f22013-07-12 20:54:25 +0100367 parser.add_argument('--no-setuptools', default=False,
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000368 action='store_true', dest='nodist',
Vinay Sajip3c557f22013-07-12 20:54:25 +0100369 help="Don't install setuptools or pip in the "
370 "virtual environment.")
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000371 parser.add_argument('--no-pip', default=False,
372 action='store_true', dest='nopip',
373 help="Don't install pip in the virtual "
374 "environment.")
375 parser.add_argument('--system-site-packages', default=False,
376 action='store_true', dest='system_site',
377 help='Give the virtual environment access to the '
378 'system site-packages dir.')
379 if os.name == 'nt':
380 use_symlinks = False
381 else:
382 use_symlinks = True
383 parser.add_argument('--symlinks', default=use_symlinks,
384 action='store_true', dest='symlinks',
385 help='Try to use symlinks rather than copies, '
386 'when symlinks are not the default for '
387 'the platform.')
388 parser.add_argument('--clear', default=False, action='store_true',
389 dest='clear', help='Delete the contents of the '
390 'environment directory if it '
391 'already exists, before '
392 'environment creation.')
393 parser.add_argument('--upgrade', default=False, action='store_true',
394 dest='upgrade', help='Upgrade the environment '
395 'directory to use this version '
396 'of Python, assuming Python '
397 'has been upgraded in-place.')
398 parser.add_argument('--verbose', default=False, action='store_true',
399 dest='verbose', help='Display the output '
400 'from the scripts which '
Vinay Sajip3c557f22013-07-12 20:54:25 +0100401 'install setuptools and pip.')
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000402 options = parser.parse_args(args)
403 if options.upgrade and options.clear:
404 raise ValueError('you cannot supply --upgrade and --clear together.')
Vinay Sajip3c557f22013-07-12 20:54:25 +0100405 builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000406 clear=options.clear,
407 symlinks=options.symlinks,
408 upgrade=options.upgrade,
409 nodist=options.nodist,
410 nopip=options.nopip,
411 verbose=options.verbose)
412 for d in options.dirs:
413 builder.create(d)
414
415 if __name__ == '__main__':
416 rc = 1
417 try:
418 main()
419 rc = 0
420 except Exception as e:
421 print('Error: %s' % e, file=sys.stderr)
422 sys.exit(rc)
423
Vinay Sajip3c557f22013-07-12 20:54:25 +0100424
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000425This script is also available for download `online
426<https://gist.github.com/4673395>`_.