blob: 5494c0c878bc523d338794de047ec089bacf4908 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Vinay Sajip7ded1f02012-05-26 03:45:29 +01007.. moduleauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk>
8.. sectionauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk>
9
Vinay Sajip7ded1f02012-05-26 03:45:29 +010010.. versionadded:: 3.3
11
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040012**Source code:** :source:`Lib/venv/`
13
14.. index:: pair: Environments; virtual
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
Elena Oat50326922018-07-28 05:58:05 -070020site directories. Each virtual environment has its own Python binary (which
21matches the version of the binary that was used to create this environment) and
22can have its own independent set of installed Python packages in its site
23directories.
Georg Brandldbab58f2012-06-24 16:37:59 +020024
Vinay Sajipa7045822013-09-06 09:50:43 +010025See :pep:`405` for more information about Python virtual environments.
Vinay Sajip7ded1f02012-05-26 03:45:29 +010026
Elena Oat50326922018-07-28 05:58:05 -070027.. seealso::
28
29 `Python Packaging User Guide: Creating and using virtual environments
30 <https://packaging.python.org/installing/#creating-virtual-environments>`__
Brett Cannonf8c15052016-10-21 12:53:40 -070031
32
Vinay Sajip7ded1f02012-05-26 03:45:29 +010033Creating virtual environments
34-----------------------------
35
Vinay Sajipc4618e32012-07-10 08:21:07 +010036.. include:: /using/venv-create.inc
Vinay Sajip7ded1f02012-05-26 03:45:29 +010037
Vinay Sajipa945ad12012-07-09 09:24:59 +010038
Vinay Sajipcd9b7462012-07-09 10:37:01 +010039.. _venv-def:
40
Brett Cannon15552c32016-07-08 10:46:21 -070041.. note:: A virtual environment is a Python environment such that the Python
42 interpreter, libraries and scripts installed into it are isolated from those
43 installed in other virtual environments, and (by default) any libraries
44 installed in a "system" Python, i.e., one which is installed as part of your
45 operating system.
Vinay Sajipa945ad12012-07-09 09:24:59 +010046
Brett Cannon15552c32016-07-08 10:46:21 -070047 A virtual environment is a directory tree which contains Python executable
48 files and other files which indicate that it is a virtual environment.
Vinay Sajipa945ad12012-07-09 09:24:59 +010049
Brett Cannon2f224a02019-07-23 14:34:32 -070050 Common installation tools such as setuptools_ and pip_ work as
Brett Cannon15552c32016-07-08 10:46:21 -070051 expected with virtual environments. In other words, when a virtual
52 environment is active, they install Python packages into the virtual
53 environment without needing to be told to do so explicitly.
Vinay Sajipa945ad12012-07-09 09:24:59 +010054
Brett Cannon15552c32016-07-08 10:46:21 -070055 When a virtual environment is active (i.e., the virtual environment's Python
56 interpreter is running), the attributes :attr:`sys.prefix` and
57 :attr:`sys.exec_prefix` point to the base directory of the virtual
58 environment, whereas :attr:`sys.base_prefix` and
59 :attr:`sys.base_exec_prefix` point to the non-virtual environment Python
60 installation which was used to create the virtual environment. If a virtual
61 environment is not active, then :attr:`sys.prefix` is the same as
62 :attr:`sys.base_prefix` and :attr:`sys.exec_prefix` is the same as
63 :attr:`sys.base_exec_prefix` (they all point to a non-virtual environment
64 Python installation).
Vinay Sajipa945ad12012-07-09 09:24:59 +010065
Brett Cannon15552c32016-07-08 10:46:21 -070066 When a virtual environment is active, any options that change the
Brett Cannon2f224a02019-07-23 14:34:32 -070067 installation path will be ignored from all :mod:`distutils` configuration
68 files to prevent projects being inadvertently installed outside of the
69 virtual environment.
Georg Brandl521ed522013-05-12 12:36:07 +020070
Brett Cannon15552c32016-07-08 10:46:21 -070071 When working in a command shell, users can make a virtual environment active
72 by running an ``activate`` script in the virtual environment's executables
Brett Cannon2f224a02019-07-23 14:34:32 -070073 directory (the precise filename and command to use the file is
74 shell-dependent), which prepends the virtual environment's directory for
75 executables to the ``PATH`` environment variable for the running shell. There
76 should be no need in other circumstances to activate a virtual
77 environment; scripts installed into virtual environments have a "shebang"
78 line which points to the virtual environment's Python interpreter. This means
79 that the script will run with that interpreter regardless of the value of
80 ``PATH``. On Windows, "shebang" line processing is supported if you have the
81 Python Launcher for Windows installed (this was added to Python in 3.3 - see
82 :pep:`397` for more details). Thus, double-clicking an installed script in a
83 Windows Explorer window should run the script with the correct interpreter
84 without there needing to be any reference to its virtual environment in
85 ``PATH``.
Vinay Sajipa7045822013-09-06 09:50:43 +010086
Vinay Sajip7ded1f02012-05-26 03:45:29 +010087
Larry Hastings3732ed22014-03-15 21:13:56 -070088.. _venv-api:
89
Vinay Sajip7ded1f02012-05-26 03:45:29 +010090API
91---
92
Vinay Sajip7ded1f02012-05-26 03:45:29 +010093.. highlight:: python
94
Georg Brandldbab58f2012-06-24 16:37:59 +020095The high-level method described above makes use of a simple API which provides
96mechanisms for third-party virtual environment creators to customize environment
97creation according to their needs, the :class:`EnvBuilder` class.
Vinay Sajip7ded1f02012-05-26 03:45:29 +010098
Nick Coghlan8fbdb092013-11-23 00:30:34 +100099.. class:: EnvBuilder(system_site_packages=False, clear=False, \
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100100 symlinks=False, upgrade=False, with_pip=False, \
Cooper Lees4acdbf12019-06-17 11:18:14 -0700101 prompt=None, upgrade_deps=False)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100102
Georg Brandldbab58f2012-06-24 16:37:59 +0200103 The :class:`EnvBuilder` class accepts the following keyword arguments on
104 instantiation:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100105
Georg Brandldbab58f2012-06-24 16:37:59 +0200106 * ``system_site_packages`` -- a Boolean value indicating that the system Python
107 site-packages should be available to the environment (defaults to ``False``).
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100108
Serhiy Storchaka0e90e992013-11-29 12:19:53 +0200109 * ``clear`` -- a Boolean value which, if true, will delete the contents of
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100110 any existing target directory, before creating the environment.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100111
Georg Brandldbab58f2012-06-24 16:37:59 +0200112 * ``symlinks`` -- a Boolean value indicating whether to attempt to symlink the
Steve Dowera1f9a332019-01-30 13:49:14 -0800113 Python binary rather than copying.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100114
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200115 * ``upgrade`` -- a Boolean value which, if true, will upgrade an existing
Vinay Sajipa945ad12012-07-09 09:24:59 +0100116 environment with the running Python - for use when that Python has been
117 upgraded in-place (defaults to ``False``).
118
Serhiy Storchaka0e90e992013-11-29 12:19:53 +0200119 * ``with_pip`` -- a Boolean value which, if true, ensures pip is
Nick Coghlanaa029da2014-02-09 10:10:24 +1000120 installed in the virtual environment. This uses :mod:`ensurepip` with
121 the ``--default-pip`` option.
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000122
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100123 * ``prompt`` -- a String to be used after virtual environment is activated
124 (defaults to ``None`` which means directory name of the environment would
125 be used).
126
Cooper Lees4acdbf12019-06-17 11:18:14 -0700127 * ``upgrade_deps`` -- Update the base venv modules to the latest on PyPI
128
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000129 .. versionchanged:: 3.4
130 Added the ``with_pip`` parameter
131
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100132 .. versionadded:: 3.6
133 Added the ``prompt`` parameter
134
Tzu-ping Chung045d4e22019-11-28 04:21:48 +0800135 .. versionadded:: 3.9
Cooper Lees4acdbf12019-06-17 11:18:14 -0700136 Added the ``upgrade_deps`` parameter
137
Georg Brandldbab58f2012-06-24 16:37:59 +0200138 Creators of third-party virtual environment tools will be free to use the
Brett Cannon2f224a02019-07-23 14:34:32 -0700139 provided :class:`EnvBuilder` class as a base class.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100140
Georg Brandldbab58f2012-06-24 16:37:59 +0200141 The returned env-builder is an object which has a method, ``create``:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100142
Georg Brandldbab58f2012-06-24 16:37:59 +0200143 .. method:: create(env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100144
Brett Cannon2f224a02019-07-23 14:34:32 -0700145 Create a virtual environment by specifying the target directory
146 (absolute or relative to the current directory) which is to contain the
Georg Brandldbab58f2012-06-24 16:37:59 +0200147 virtual environment. The ``create`` method will either create the
148 environment in the specified directory, or raise an appropriate
149 exception.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100150
Brett Cannon2f224a02019-07-23 14:34:32 -0700151 The ``create`` method of the :class:`EnvBuilder` class illustrates the
152 hooks available for subclass customization::
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100153
Georg Brandldbab58f2012-06-24 16:37:59 +0200154 def create(self, env_dir):
155 """
156 Create a virtualized Python environment in a directory.
157 env_dir is the target directory to create an environment in.
158 """
159 env_dir = os.path.abspath(env_dir)
Georg Brandla0b79232013-10-06 12:52:49 +0200160 context = self.ensure_directories(env_dir)
Georg Brandldbab58f2012-06-24 16:37:59 +0200161 self.create_configuration(context)
162 self.setup_python(context)
163 self.setup_scripts(context)
164 self.post_setup(context)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100165
Georg Brandla0b79232013-10-06 12:52:49 +0200166 Each of the methods :meth:`ensure_directories`,
Georg Brandldbab58f2012-06-24 16:37:59 +0200167 :meth:`create_configuration`, :meth:`setup_python`,
168 :meth:`setup_scripts` and :meth:`post_setup` can be overridden.
169
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100170 .. method:: ensure_directories(env_dir)
Georg Brandldbab58f2012-06-24 16:37:59 +0200171
172 Creates the environment directory and all necessary directories, and
173 returns a context object. This is just a holder for attributes (such as
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100174 paths), for use by the other methods. The directories are allowed to
175 exist already, as long as either ``clear`` or ``upgrade`` were
176 specified to allow operating on an existing environment directory.
Georg Brandldbab58f2012-06-24 16:37:59 +0200177
178 .. method:: create_configuration(context)
179
180 Creates the ``pyvenv.cfg`` configuration file in the environment.
181
182 .. method:: setup_python(context)
183
Steve Dowera1f9a332019-01-30 13:49:14 -0800184 Creates a copy or symlink to the Python executable in the environment.
185 On POSIX systems, if a specific executable ``python3.x`` was used,
186 symlinks to ``python`` and ``python3`` will be created pointing to that
187 executable, unless files with those names already exist.
Georg Brandldbab58f2012-06-24 16:37:59 +0200188
189 .. method:: setup_scripts(context)
190
191 Installs activation scripts appropriate to the platform into the virtual
Steve Dowera1f9a332019-01-30 13:49:14 -0800192 environment.
Georg Brandldbab58f2012-06-24 16:37:59 +0200193
Vinay Sajip264e0342019-09-09 14:50:38 +0100194 .. method:: upgrade_dependencies(context)
195
196 Upgrades the core venv dependency packages (currently ``pip`` and
197 ``setuptools``) in the environment. This is done by shelling out to the
198 ``pip`` executable in the environment.
199
Tzu-ping Chung045d4e22019-11-28 04:21:48 +0800200 .. versionadded:: 3.9
Vinay Sajip264e0342019-09-09 14:50:38 +0100201
Georg Brandldbab58f2012-06-24 16:37:59 +0200202 .. method:: post_setup(context)
203
204 A placeholder method which can be overridden in third party
205 implementations to pre-install packages in the virtual environment or
206 perform other post-creation steps.
207
Steve Dower1c3de542018-12-10 08:11:21 -0800208 .. versionchanged:: 3.7.2
209 Windows now uses redirector scripts for ``python[w].exe`` instead of
Steve Dowera1f9a332019-01-30 13:49:14 -0800210 copying the actual binaries. In 3.7.2 only :meth:`setup_python` does
211 nothing unless running from a build in the source tree.
212
213 .. versionchanged:: 3.7.3
214 Windows copies the redirector scripts as part of :meth:`setup_python`
215 instead of :meth:`setup_scripts`. This was not the case in 3.7.2.
216 When using symlinks, the original executables will be linked.
Steve Dower1c3de542018-12-10 08:11:21 -0800217
Georg Brandldbab58f2012-06-24 16:37:59 +0200218 In addition, :class:`EnvBuilder` provides this utility method that can be
219 called from :meth:`setup_scripts` or :meth:`post_setup` in subclasses to
220 assist in installing custom scripts into the virtual environment.
221
222 .. method:: install_scripts(context, path)
223
224 *path* is the path to a directory that should contain subdirectories
225 "common", "posix", "nt", each containing scripts destined for the bin
226 directory in the environment. The contents of "common" and the
227 directory corresponding to :data:`os.name` are copied after some text
228 replacement of placeholders:
229
230 * ``__VENV_DIR__`` is replaced with the absolute path of the environment
231 directory.
232
233 * ``__VENV_NAME__`` is replaced with the environment name (final path
234 segment of environment directory).
235
Vinay Sajipdff9e252013-10-02 11:36:16 +0100236 * ``__VENV_PROMPT__`` is replaced with the prompt (the environment
237 name surrounded by parentheses and with a following space)
238
Georg Brandldbab58f2012-06-24 16:37:59 +0200239 * ``__VENV_BIN_NAME__`` is replaced with the name of the bin directory
240 (either ``bin`` or ``Scripts``).
241
242 * ``__VENV_PYTHON__`` is replaced with the absolute path of the
243 environment's executable.
244
Vinay Sajip577d4ff2013-07-12 21:52:51 +0100245 The directories are allowed to exist (for when an existing environment
246 is being upgraded).
Georg Brandldbab58f2012-06-24 16:37:59 +0200247
248There is also a module-level convenience function:
249
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000250.. function:: create(env_dir, system_site_packages=False, clear=False, \
Sebastian Koslowski3921b1c2019-05-06 14:51:09 -0400251 symlinks=False, with_pip=False, prompt=None)
Georg Brandldbab58f2012-06-24 16:37:59 +0200252
253 Create an :class:`EnvBuilder` with the given keyword arguments, and call its
254 :meth:`~EnvBuilder.create` method with the *env_dir* argument.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000255
Sebastian Koslowski3921b1c2019-05-06 14:51:09 -0400256 .. versionadded:: 3.3
257
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000258 .. versionchanged:: 3.4
259 Added the ``with_pip`` parameter
260
Sebastian Koslowski3921b1c2019-05-06 14:51:09 -0400261 .. versionchanged:: 3.6
262 Added the ``prompt`` parameter
263
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000264An example of extending ``EnvBuilder``
265--------------------------------------
266
267The following script shows how to extend :class:`EnvBuilder` by implementing a
Brett Cannon15552c32016-07-08 10:46:21 -0700268subclass which installs setuptools and pip into a created virtual environment::
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000269
270 import os
271 import os.path
272 from subprocess import Popen, PIPE
273 import sys
274 from threading import Thread
275 from urllib.parse import urlparse
276 from urllib.request import urlretrieve
277 import venv
278
Vinay Sajip3c557f22013-07-12 20:54:25 +0100279 class ExtendedEnvBuilder(venv.EnvBuilder):
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000280 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100281 This builder installs setuptools and pip so that you can pip or
Brett Cannon15552c32016-07-08 10:46:21 -0700282 easy_install other packages into the created virtual environment.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000283
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200284 :param nodist: If true, setuptools and pip are not installed into the
Brett Cannon15552c32016-07-08 10:46:21 -0700285 created virtual environment.
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200286 :param nopip: If true, pip is not installed into the created
Brett Cannon15552c32016-07-08 10:46:21 -0700287 virtual environment.
Vinay Sajip3c557f22013-07-12 20:54:25 +0100288 :param progress: If setuptools or pip are installed, the progress of the
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000289 installation can be monitored by passing a progress
290 callable. If specified, it is called with two
291 arguments: a string indicating some progress, and a
292 context indicating where the string is coming from.
293 The context argument can have one of three values:
294 'main', indicating that it is called from virtualize()
295 itself, and 'stdout' and 'stderr', which are obtained
296 by reading lines from the output streams of a subprocess
297 which is used to install the app.
298
299 If a callable is not specified, default progress
300 information is output to sys.stderr.
301 """
302
303 def __init__(self, *args, **kwargs):
304 self.nodist = kwargs.pop('nodist', False)
305 self.nopip = kwargs.pop('nopip', False)
306 self.progress = kwargs.pop('progress', None)
307 self.verbose = kwargs.pop('verbose', False)
308 super().__init__(*args, **kwargs)
309
310 def post_setup(self, context):
311 """
312 Set up any packages which need to be pre-installed into the
Brett Cannon15552c32016-07-08 10:46:21 -0700313 virtual environment being created.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000314
Brett Cannon15552c32016-07-08 10:46:21 -0700315 :param context: The information for the virtual environment
316 creation request being processed.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000317 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100318 os.environ['VIRTUAL_ENV'] = context.env_dir
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000319 if not self.nodist:
Vinay Sajip3c557f22013-07-12 20:54:25 +0100320 self.install_setuptools(context)
321 # Can't install pip without setuptools
322 if not self.nopip and not self.nodist:
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000323 self.install_pip(context)
324
325 def reader(self, stream, context):
326 """
327 Read lines from a subprocess' output stream and either pass to a progress
328 callable (if specified) or write progress information to sys.stderr.
329 """
330 progress = self.progress
331 while True:
332 s = stream.readline()
333 if not s:
334 break
335 if progress is not None:
336 progress(s, context)
337 else:
338 if not self.verbose:
339 sys.stderr.write('.')
340 else:
341 sys.stderr.write(s.decode('utf-8'))
342 sys.stderr.flush()
Vinay Sajipad6bb032013-07-12 21:44:35 +0100343 stream.close()
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000344
345 def install_script(self, context, name, url):
346 _, _, path, _, _, _ = urlparse(url)
347 fn = os.path.split(path)[-1]
348 binpath = context.bin_path
349 distpath = os.path.join(binpath, fn)
Brett Cannon15552c32016-07-08 10:46:21 -0700350 # Download script into the virtual environment's binaries folder
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000351 urlretrieve(url, distpath)
352 progress = self.progress
Vinay Sajip3c557f22013-07-12 20:54:25 +0100353 if self.verbose:
354 term = '\n'
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000355 else:
Vinay Sajip3c557f22013-07-12 20:54:25 +0100356 term = ''
357 if progress is not None:
358 progress('Installing %s ...%s' % (name, term), 'main')
359 else:
360 sys.stderr.write('Installing %s ...%s' % (name, term))
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000361 sys.stderr.flush()
Brett Cannon15552c32016-07-08 10:46:21 -0700362 # Install in the virtual environment
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000363 args = [context.env_exe, fn]
364 p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
365 t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
366 t1.start()
367 t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
368 t2.start()
369 p.wait()
370 t1.join()
371 t2.join()
372 if progress is not None:
373 progress('done.', 'main')
374 else:
375 sys.stderr.write('done.\n')
376 # Clean up - no longer needed
377 os.unlink(distpath)
378
Vinay Sajip3c557f22013-07-12 20:54:25 +0100379 def install_setuptools(self, context):
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000380 """
Brett Cannon15552c32016-07-08 10:46:21 -0700381 Install setuptools in the virtual environment.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000382
Brett Cannon15552c32016-07-08 10:46:21 -0700383 :param context: The information for the virtual environment
384 creation request being processed.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000385 """
Vinay Sajip3c557f22013-07-12 20:54:25 +0100386 url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
387 self.install_script(context, 'setuptools', url)
388 # clear up the setuptools archive which gets downloaded
389 pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000390 files = filter(pred, os.listdir(context.bin_path))
391 for f in files:
392 f = os.path.join(context.bin_path, f)
393 os.unlink(f)
394
395 def install_pip(self, context):
396 """
Brett Cannon15552c32016-07-08 10:46:21 -0700397 Install pip in the virtual environment.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000398
Brett Cannon15552c32016-07-08 10:46:21 -0700399 :param context: The information for the virtual environment
400 creation request being processed.
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000401 """
402 url = 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py'
403 self.install_script(context, 'pip', url)
404
405 def main(args=None):
406 compatible = True
407 if sys.version_info < (3, 3):
408 compatible = False
409 elif not hasattr(sys, 'base_prefix'):
410 compatible = False
411 if not compatible:
412 raise ValueError('This script is only for use with '
413 'Python 3.3 or later')
414 else:
415 import argparse
416
417 parser = argparse.ArgumentParser(prog=__name__,
418 description='Creates virtual Python '
419 'environments in one or '
420 'more target '
421 'directories.')
422 parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
Brett Cannon15552c32016-07-08 10:46:21 -0700423 help='A directory in which to create the
424 'virtual environment.')
Vinay Sajip3c557f22013-07-12 20:54:25 +0100425 parser.add_argument('--no-setuptools', default=False,
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000426 action='store_true', dest='nodist',
Vinay Sajip3c557f22013-07-12 20:54:25 +0100427 help="Don't install setuptools or pip in the "
428 "virtual environment.")
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000429 parser.add_argument('--no-pip', default=False,
430 action='store_true', dest='nopip',
431 help="Don't install pip in the virtual "
432 "environment.")
433 parser.add_argument('--system-site-packages', default=False,
434 action='store_true', dest='system_site',
435 help='Give the virtual environment access to the '
436 'system site-packages dir.')
437 if os.name == 'nt':
438 use_symlinks = False
439 else:
440 use_symlinks = True
441 parser.add_argument('--symlinks', default=use_symlinks,
442 action='store_true', dest='symlinks',
443 help='Try to use symlinks rather than copies, '
444 'when symlinks are not the default for '
445 'the platform.')
446 parser.add_argument('--clear', default=False, action='store_true',
447 dest='clear', help='Delete the contents of the '
Brett Cannon15552c32016-07-08 10:46:21 -0700448 'virtual environment '
449 'directory if it already '
450 'exists, before virtual '
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000451 'environment creation.')
452 parser.add_argument('--upgrade', default=False, action='store_true',
Brett Cannon15552c32016-07-08 10:46:21 -0700453 dest='upgrade', help='Upgrade the virtual '
454 'environment directory to '
455 'use this version of '
456 'Python, assuming Python '
457 'has been upgraded '
458 'in-place.')
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000459 parser.add_argument('--verbose', default=False, action='store_true',
460 dest='verbose', help='Display the output '
461 'from the scripts which '
Vinay Sajip3c557f22013-07-12 20:54:25 +0100462 'install setuptools and pip.')
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000463 options = parser.parse_args(args)
464 if options.upgrade and options.clear:
465 raise ValueError('you cannot supply --upgrade and --clear together.')
Vinay Sajip3c557f22013-07-12 20:54:25 +0100466 builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000467 clear=options.clear,
468 symlinks=options.symlinks,
469 upgrade=options.upgrade,
470 nodist=options.nodist,
471 nopip=options.nopip,
472 verbose=options.verbose)
473 for d in options.dirs:
474 builder.create(d)
475
476 if __name__ == '__main__':
477 rc = 1
478 try:
479 main()
480 rc = 0
481 except Exception as e:
482 print('Error: %s' % e, file=sys.stderr)
483 sys.exit(rc)
484
Vinay Sajip3c557f22013-07-12 20:54:25 +0100485
Vinay Sajip2b4fcfb2013-01-30 13:44:00 +0000486This script is also available for download `online
Sanyam Khurana338cd832018-01-20 05:55:37 +0530487<https://gist.github.com/vsajip/4673395>`_.
Brett Cannon2f224a02019-07-23 14:34:32 -0700488
489
490.. _setuptools: https://pypi.org/project/setuptools/
491.. _pip: https://pypi.org/project/pip/