• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!venv` --- Creation of virtual environments
2=================================================
3
4.. module:: venv
5   :synopsis: Creation of virtual environments.
6
7.. moduleauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk>
8.. sectionauthor:: Vinay Sajip <vinay_sajip@yahoo.co.uk>
9
10.. versionadded:: 3.3
11
12**Source code:** :source:`Lib/venv/`
13
14.. index:: pair: Environments; virtual
15
16--------------
17
18.. _venv-def:
19.. _venv-intro:
20
21The :mod:`!venv` module supports creating lightweight "virtual environments",
22each with their own independent set of Python packages installed in
23their :mod:`site` directories.
24A virtual environment is created on top of an existing
25Python installation, known as the virtual environment's "base" Python, and may
26optionally be isolated from the packages in the base environment,
27so only those explicitly installed in the virtual environment are available.
28
29When used from within a virtual environment, common installation tools such as
30:pypi:`pip` will install Python packages into a virtual environment
31without needing to be told to do so explicitly.
32
33A virtual environment is (amongst other things):
34
35* Used to contain a specific Python interpreter and software libraries and
36  binaries which are needed to support a project (library or application). These
37  are by default isolated from software in other virtual environments and Python
38  interpreters and libraries installed in the operating system.
39
40* Contained in a directory, conventionally named ``.venv`` or ``venv`` in
41  the project directory, or under a container directory for lots of virtual
42  environments, such as ``~/.virtualenvs``.
43
44* Not checked into source control systems such as Git.
45
46* Considered as disposable -- it should be simple to delete and recreate it from
47  scratch. You don't place any project code in the environment.
48
49* Not considered as movable or copyable -- you just recreate the same
50  environment in the target location.
51
52See :pep:`405` for more background on Python virtual environments.
53
54.. seealso::
55
56   `Python Packaging User Guide: Creating and using virtual environments
57   <https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#create-and-use-virtual-environments>`__
58
59.. include:: ../includes/wasm-mobile-notavail.rst
60
61Creating virtual environments
62-----------------------------
63
64:ref:`Virtual environments <venv-def>` are created by executing the ``venv``
65module:
66
67.. code-block:: shell
68
69    python -m venv /path/to/new/virtual/environment
70
71This creates the target directory (including parent directories as needed)
72and places a :file:`pyvenv.cfg` file in it with a ``home`` key
73pointing to the Python installation from which the command was run.
74It also creates a :file:`bin` (or :file:`Scripts` on Windows) subdirectory
75containing a copy or symlink of the Python executable
76(as appropriate for the platform or arguments used at environment creation time).
77It also creates a :file:`lib/pythonX.Y/site-packages` subdirectory
78(on Windows, this is :file:`Lib\site-packages`).
79If an existing directory is specified, it will be re-used.
80
81.. versionchanged:: 3.5
82   The use of ``venv`` is now recommended for creating virtual environments.
83
84.. deprecated-removed:: 3.6 3.8
85   :program:`pyvenv` was the recommended tool for creating virtual environments
86   for Python 3.3 and 3.4, and replaced in 3.5 by executing ``venv`` directly.
87
88.. highlight:: none
89
90On Windows, invoke the ``venv`` command as follows:
91
92.. code-block:: ps1con
93
94   PS> python -m venv C:\path\to\new\virtual\environment
95
96The command, if run with ``-h``, will show the available options::
97
98   usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
99               [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps]
100               [--without-scm-ignore-files]
101               ENV_DIR [ENV_DIR ...]
102
103   Creates virtual Python environments in one or more target directories.
104
105   positional arguments:
106     ENV_DIR               A directory to create the environment in.
107
108   options:
109     -h, --help            show this help message and exit
110     --system-site-packages
111                           Give the virtual environment access to the system
112                           site-packages dir.
113     --symlinks            Try to use symlinks rather than copies, when
114                           symlinks are not the default for the platform.
115     --copies              Try to use copies rather than symlinks, even when
116                           symlinks are the default for the platform.
117     --clear               Delete the contents of the environment directory
118                           if it already exists, before environment creation.
119     --upgrade             Upgrade the environment directory to use this
120                           version of Python, assuming Python has been
121                           upgraded in-place.
122     --without-pip         Skips installing or upgrading pip in the virtual
123                           environment (pip is bootstrapped by default)
124     --prompt PROMPT       Provides an alternative prompt prefix for this
125                           environment.
126     --upgrade-deps        Upgrade core dependencies (pip) to the latest
127                           version in PyPI
128     --without-scm-ignore-files
129                           Skips adding SCM ignore files to the environment
130                           directory (Git is supported by default).
131
132   Once an environment has been created, you may wish to activate it, e.g. by
133   sourcing an activate script in its bin directory.
134
135
136.. versionchanged:: 3.4
137   Installs pip by default, added the ``--without-pip``  and ``--copies``
138   options.
139
140.. versionchanged:: 3.4
141   In earlier versions, if the target directory already existed, an error was
142   raised, unless the ``--clear`` or ``--upgrade`` option was provided.
143
144.. versionchanged:: 3.9
145   Add ``--upgrade-deps`` option to upgrade pip + setuptools to the latest on PyPI.
146
147.. versionchanged:: 3.12
148
149   ``setuptools`` is no longer a core venv dependency.
150
151.. versionchanged:: 3.13
152
153   Added the ``--without-scm-ignore-files`` option.
154.. versionchanged:: 3.13
155   ``venv`` now creates a :file:`.gitignore` file for Git by default.
156
157.. note::
158   While symlinks are supported on Windows, they are not recommended. Of
159   particular note is that double-clicking ``python.exe`` in File Explorer
160   will resolve the symlink eagerly and ignore the virtual environment.
161
162.. note::
163   On Microsoft Windows, it may be required to enable the ``Activate.ps1``
164   script by setting the execution policy for the user. You can do this by
165   issuing the following PowerShell command:
166
167   .. code-block:: powershell
168
169      PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
170
171   See `About Execution Policies
172   <https://go.microsoft.com/fwlink/?LinkID=135170>`_
173   for more information.
174
175The created :file:`pyvenv.cfg` file also includes the
176``include-system-site-packages`` key, set to ``true`` if ``venv`` is
177run with the ``--system-site-packages`` option, ``false`` otherwise.
178
179Unless the ``--without-pip`` option is given, :mod:`ensurepip` will be
180invoked to bootstrap ``pip`` into the virtual environment.
181
182Multiple paths can be given to ``venv``, in which case an identical virtual
183environment will be created, according to the given options, at each provided
184path.
185
186.. _venv-explanation:
187
188How venvs work
189--------------
190
191When a Python interpreter is running from a virtual environment,
192:data:`sys.prefix` and :data:`sys.exec_prefix`
193point to the directories of the virtual environment,
194whereas :data:`sys.base_prefix` and :data:`sys.base_exec_prefix`
195point to those of the base Python used to create the environment.
196It is sufficient to check
197``sys.prefix != sys.base_prefix`` to determine if the current interpreter is
198running from a virtual environment.
199
200A virtual environment may be "activated" using a script in its binary directory
201(``bin`` on POSIX; ``Scripts`` on Windows).
202This will prepend that directory to your :envvar:`PATH`, so that running
203:program:`python` will invoke the environment's Python interpreter
204and you can run installed scripts without having to use their full path.
205The invocation of the activation script is platform-specific
206(:samp:`{<venv>}` must be replaced by the path to the directory
207containing the virtual environment):
208
209+-------------+------------+--------------------------------------------------+
210| Platform    | Shell      | Command to activate virtual environment          |
211+=============+============+==================================================+
212| POSIX       | bash/zsh   | :samp:`$ source {<venv>}/bin/activate`           |
213|             +------------+--------------------------------------------------+
214|             | fish       | :samp:`$ source {<venv>}/bin/activate.fish`      |
215|             +------------+--------------------------------------------------+
216|             | csh/tcsh   | :samp:`$ source {<venv>}/bin/activate.csh`       |
217|             +------------+--------------------------------------------------+
218|             | pwsh       | :samp:`$ {<venv>}/bin/Activate.ps1`              |
219+-------------+------------+--------------------------------------------------+
220| Windows     | cmd.exe    | :samp:`C:\\> {<venv>}\\Scripts\\activate.bat`    |
221|             +------------+--------------------------------------------------+
222|             | PowerShell | :samp:`PS C:\\> {<venv>}\\Scripts\\Activate.ps1` |
223+-------------+------------+--------------------------------------------------+
224
225.. versionadded:: 3.4
226   :program:`fish` and :program:`csh` activation scripts.
227
228.. versionadded:: 3.8
229   PowerShell activation scripts installed under POSIX for PowerShell Core
230   support.
231
232You don't specifically *need* to activate a virtual environment,
233as you can just specify the full path to that environment's
234Python interpreter when invoking Python.
235Furthermore, all scripts installed in the environment
236should be runnable without activating it.
237
238In order to achieve this, scripts installed into virtual environments have
239a "shebang" line which points to the environment's Python interpreter,
240:samp:`#!/{<path-to-venv>}/bin/python`.
241This means that the script will run with that interpreter regardless of the
242value of :envvar:`PATH`. On Windows, "shebang" line processing is supported if
243you have the :ref:`launcher` installed. Thus, double-clicking an installed
244script in a Windows Explorer window should run it with the correct interpreter
245without the environment needing to be activated or on the :envvar:`PATH`.
246
247When a virtual environment has been activated, the :envvar:`!VIRTUAL_ENV`
248environment variable is set to the path of the environment.
249Since explicitly activating a virtual environment is not required to use it,
250:envvar:`!VIRTUAL_ENV` cannot be relied upon to determine
251whether a virtual environment is being used.
252
253.. warning:: Because scripts installed in environments should not expect the
254   environment to be activated, their shebang lines contain the absolute paths
255   to their environment's interpreters. Because of this, environments are
256   inherently non-portable, in the general case. You should always have a
257   simple means of recreating an environment (for example, if you have a
258   requirements file ``requirements.txt``, you can invoke ``pip install -r
259   requirements.txt`` using the environment's ``pip`` to install all of the
260   packages needed by the environment). If for any reason you need to move the
261   environment to a new location, you should recreate it at the desired
262   location and delete the one at the old location. If you move an environment
263   because you moved a parent directory of it, you should recreate the
264   environment in its new location. Otherwise, software installed into the
265   environment may not work as expected.
266
267You can deactivate a virtual environment by typing ``deactivate`` in your shell.
268The exact mechanism is platform-specific and is an internal implementation
269detail (typically, a script or shell function will be used).
270
271
272.. _venv-api:
273
274API
275---
276
277.. highlight:: python
278
279The high-level method described above makes use of a simple API which provides
280mechanisms for third-party virtual environment creators to customize environment
281creation according to their needs, the :class:`EnvBuilder` class.
282
283.. class:: EnvBuilder(system_site_packages=False, clear=False, \
284                      symlinks=False, upgrade=False, with_pip=False, \
285                      prompt=None, upgrade_deps=False, \
286                      *, scm_ignore_files=frozenset())
287
288    The :class:`EnvBuilder` class accepts the following keyword arguments on
289    instantiation:
290
291    * *system_site_packages* -- a boolean value indicating that the system Python
292      site-packages should be available to the environment (defaults to ``False``).
293
294    * *clear* -- a boolean value which, if true, will delete the contents of
295      any existing target directory, before creating the environment.
296
297    * *symlinks* -- a boolean value indicating whether to attempt to symlink the
298      Python binary rather than copying.
299
300    * *upgrade* -- a boolean value which, if true, will upgrade an existing
301      environment with the running Python - for use when that Python has been
302      upgraded in-place (defaults to ``False``).
303
304    * *with_pip* -- a boolean value which, if true, ensures pip is
305      installed in the virtual environment. This uses :mod:`ensurepip` with
306      the ``--default-pip`` option.
307
308    * *prompt* -- a string to be used after virtual environment is activated
309      (defaults to ``None`` which means directory name of the environment would
310      be used). If the special string ``"."`` is provided, the basename of the
311      current directory is used as the prompt.
312
313    * *upgrade_deps* -- Update the base venv modules to the latest on PyPI
314
315    * *scm_ignore_files* -- Create ignore files based for the specified source
316      control managers (SCM) in the iterable. Support is defined by having a
317      method named ``create_{scm}_ignore_file``. The only value supported by
318      default is ``"git"`` via :meth:`create_git_ignore_file`.
319
320
321    .. versionchanged:: 3.4
322       Added the ``with_pip`` parameter
323
324    .. versionchanged:: 3.6
325       Added the ``prompt`` parameter
326
327    .. versionchanged:: 3.9
328       Added the ``upgrade_deps`` parameter
329
330    .. versionchanged:: 3.13
331       Added the ``scm_ignore_files`` parameter
332
333    :class:`EnvBuilder` may be used as a base class.
334
335    .. method:: create(env_dir)
336
337        Create a virtual environment by specifying the target directory
338        (absolute or relative to the current directory) which is to contain the
339        virtual environment.  The ``create`` method will either create the
340        environment in the specified directory, or raise an appropriate
341        exception.
342
343        The ``create`` method of the :class:`EnvBuilder` class illustrates the
344        hooks available for subclass customization::
345
346            def create(self, env_dir):
347                """
348                Create a virtualized Python environment in a directory.
349                env_dir is the target directory to create an environment in.
350                """
351                env_dir = os.path.abspath(env_dir)
352                context = self.ensure_directories(env_dir)
353                self.create_configuration(context)
354                self.setup_python(context)
355                self.setup_scripts(context)
356                self.post_setup(context)
357
358        Each of the methods :meth:`ensure_directories`,
359        :meth:`create_configuration`, :meth:`setup_python`,
360        :meth:`setup_scripts` and :meth:`post_setup` can be overridden.
361
362    .. method:: ensure_directories(env_dir)
363
364        Creates the environment directory and all necessary subdirectories that
365        don't already exist, and returns a context object.  This context object
366        is just a holder for attributes (such as paths) for use by the other
367        methods.  If the :class:`EnvBuilder` is created with the arg
368        ``clear=True``, contents of the environment directory will be cleared
369        and then all necessary subdirectories will be recreated.
370
371        The returned context object is a :class:`types.SimpleNamespace` with the
372        following attributes:
373
374        * ``env_dir`` - The location of the virtual environment. Used for
375          ``__VENV_DIR__`` in activation scripts (see :meth:`install_scripts`).
376
377        * ``env_name`` - The name of the virtual environment. Used for
378          ``__VENV_NAME__`` in activation scripts (see :meth:`install_scripts`).
379
380        * ``prompt`` - The prompt to be used by the activation scripts. Used for
381          ``__VENV_PROMPT__`` in activation scripts (see :meth:`install_scripts`).
382
383        * ``executable`` - The underlying Python executable used by the virtual
384          environment. This takes into account the case where a virtual environment
385          is created from another virtual environment.
386
387        * ``inc_path`` - The include path for the virtual environment.
388
389        * ``lib_path`` - The purelib path for the virtual environment.
390
391        * ``bin_path`` - The script path for the virtual environment.
392
393        * ``bin_name`` - The name of the script path relative to the virtual
394          environment location. Used for ``__VENV_BIN_NAME__`` in activation
395          scripts (see :meth:`install_scripts`).
396
397        * ``env_exe`` - The name of the Python interpreter in the virtual
398          environment. Used for ``__VENV_PYTHON__`` in activation scripts
399          (see :meth:`install_scripts`).
400
401        * ``env_exec_cmd`` - The name of the Python interpreter, taking into
402          account filesystem redirections. This can be used to run Python in
403          the virtual environment.
404
405
406        .. versionchanged:: 3.11
407           The *venv*
408           :ref:`sysconfig installation scheme <installation_paths>`
409           is used to construct the paths of the created directories.
410
411        .. versionchanged:: 3.12
412           The attribute ``lib_path`` was added to the context, and the context
413           object was documented.
414
415    .. method:: create_configuration(context)
416
417        Creates the ``pyvenv.cfg`` configuration file in the environment.
418
419    .. method:: setup_python(context)
420
421        Creates a copy or symlink to the Python executable in the environment.
422        On POSIX systems, if a specific executable ``python3.x`` was used,
423        symlinks to ``python`` and ``python3`` will be created pointing to that
424        executable, unless files with those names already exist.
425
426    .. method:: setup_scripts(context)
427
428        Installs activation scripts appropriate to the platform into the virtual
429        environment.
430
431    .. method:: upgrade_dependencies(context)
432
433       Upgrades the core venv dependency packages (currently :pypi:`pip`)
434       in the environment. This is done by shelling out to the
435       ``pip`` executable in the environment.
436
437       .. versionadded:: 3.9
438       .. versionchanged:: 3.12
439
440          :pypi:`setuptools` is no longer a core venv dependency.
441
442    .. method:: post_setup(context)
443
444        A placeholder method which can be overridden in third party
445        implementations to pre-install packages in the virtual environment or
446        perform other post-creation steps.
447
448    .. method:: install_scripts(context, path)
449
450        This method can be
451        called from :meth:`setup_scripts` or :meth:`post_setup` in subclasses to
452        assist in installing custom scripts into the virtual environment.
453
454        *path* is the path to a directory that should contain subdirectories
455        ``common``, ``posix``, ``nt``; each containing scripts destined for the
456        ``bin`` directory in the environment.  The contents of ``common`` and the
457        directory corresponding to :data:`os.name` are copied after some text
458        replacement of placeholders:
459
460        * ``__VENV_DIR__`` is replaced with the absolute path of the environment
461          directory.
462
463        * ``__VENV_NAME__`` is replaced with the environment name (final path
464          segment of environment directory).
465
466        * ``__VENV_PROMPT__`` is replaced with the prompt (the environment
467          name surrounded by parentheses and with a following space)
468
469        * ``__VENV_BIN_NAME__`` is replaced with the name of the bin directory
470          (either ``bin`` or ``Scripts``).
471
472        * ``__VENV_PYTHON__`` is replaced with the absolute path of the
473          environment's executable.
474
475        The directories are allowed to exist (for when an existing environment
476        is being upgraded).
477
478    .. method:: create_git_ignore_file(context)
479
480       Creates a ``.gitignore`` file within the virtual environment that causes
481       the entire directory to be ignored by the Git source control manager.
482
483       .. versionadded:: 3.13
484
485    .. versionchanged:: 3.7.2
486       Windows now uses redirector scripts for ``python[w].exe`` instead of
487       copying the actual binaries. In 3.7.2 only :meth:`setup_python` does
488       nothing unless running from a build in the source tree.
489
490    .. versionchanged:: 3.7.3
491       Windows copies the redirector scripts as part of :meth:`setup_python`
492       instead of :meth:`setup_scripts`. This was not the case in 3.7.2.
493       When using symlinks, the original executables will be linked.
494
495There is also a module-level convenience function:
496
497.. function:: create(env_dir, system_site_packages=False, clear=False, \
498                     symlinks=False, with_pip=False, prompt=None, \
499                     upgrade_deps=False, *, scm_ignore_files=frozenset())
500
501    Create an :class:`EnvBuilder` with the given keyword arguments, and call its
502    :meth:`~EnvBuilder.create` method with the *env_dir* argument.
503
504    .. versionadded:: 3.3
505
506    .. versionchanged:: 3.4
507       Added the *with_pip* parameter
508
509    .. versionchanged:: 3.6
510       Added the *prompt* parameter
511
512    .. versionchanged:: 3.9
513       Added the *upgrade_deps* parameter
514
515    .. versionchanged:: 3.13
516       Added the *scm_ignore_files* parameter
517
518An example of extending ``EnvBuilder``
519--------------------------------------
520
521The following script shows how to extend :class:`EnvBuilder` by implementing a
522subclass which installs setuptools and pip into a created virtual environment::
523
524    import os
525    import os.path
526    from subprocess import Popen, PIPE
527    import sys
528    from threading import Thread
529    from urllib.parse import urlparse
530    from urllib.request import urlretrieve
531    import venv
532
533    class ExtendedEnvBuilder(venv.EnvBuilder):
534        """
535        This builder installs setuptools and pip so that you can pip or
536        easy_install other packages into the created virtual environment.
537
538        :param nodist: If true, setuptools and pip are not installed into the
539                       created virtual environment.
540        :param nopip: If true, pip is not installed into the created
541                      virtual environment.
542        :param progress: If setuptools or pip are installed, the progress of the
543                         installation can be monitored by passing a progress
544                         callable. If specified, it is called with two
545                         arguments: a string indicating some progress, and a
546                         context indicating where the string is coming from.
547                         The context argument can have one of three values:
548                         'main', indicating that it is called from virtualize()
549                         itself, and 'stdout' and 'stderr', which are obtained
550                         by reading lines from the output streams of a subprocess
551                         which is used to install the app.
552
553                         If a callable is not specified, default progress
554                         information is output to sys.stderr.
555        """
556
557        def __init__(self, *args, **kwargs):
558            self.nodist = kwargs.pop('nodist', False)
559            self.nopip = kwargs.pop('nopip', False)
560            self.progress = kwargs.pop('progress', None)
561            self.verbose = kwargs.pop('verbose', False)
562            super().__init__(*args, **kwargs)
563
564        def post_setup(self, context):
565            """
566            Set up any packages which need to be pre-installed into the
567            virtual environment being created.
568
569            :param context: The information for the virtual environment
570                            creation request being processed.
571            """
572            os.environ['VIRTUAL_ENV'] = context.env_dir
573            if not self.nodist:
574                self.install_setuptools(context)
575            # Can't install pip without setuptools
576            if not self.nopip and not self.nodist:
577                self.install_pip(context)
578
579        def reader(self, stream, context):
580            """
581            Read lines from a subprocess' output stream and either pass to a progress
582            callable (if specified) or write progress information to sys.stderr.
583            """
584            progress = self.progress
585            while True:
586                s = stream.readline()
587                if not s:
588                    break
589                if progress is not None:
590                    progress(s, context)
591                else:
592                    if not self.verbose:
593                        sys.stderr.write('.')
594                    else:
595                        sys.stderr.write(s.decode('utf-8'))
596                    sys.stderr.flush()
597            stream.close()
598
599        def install_script(self, context, name, url):
600            _, _, path, _, _, _ = urlparse(url)
601            fn = os.path.split(path)[-1]
602            binpath = context.bin_path
603            distpath = os.path.join(binpath, fn)
604            # Download script into the virtual environment's binaries folder
605            urlretrieve(url, distpath)
606            progress = self.progress
607            if self.verbose:
608                term = '\n'
609            else:
610                term = ''
611            if progress is not None:
612                progress('Installing %s ...%s' % (name, term), 'main')
613            else:
614                sys.stderr.write('Installing %s ...%s' % (name, term))
615                sys.stderr.flush()
616            # Install in the virtual environment
617            args = [context.env_exe, fn]
618            p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
619            t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
620            t1.start()
621            t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
622            t2.start()
623            p.wait()
624            t1.join()
625            t2.join()
626            if progress is not None:
627                progress('done.', 'main')
628            else:
629                sys.stderr.write('done.\n')
630            # Clean up - no longer needed
631            os.unlink(distpath)
632
633        def install_setuptools(self, context):
634            """
635            Install setuptools in the virtual environment.
636
637            :param context: The information for the virtual environment
638                            creation request being processed.
639            """
640            url = "https://bootstrap.pypa.io/ez_setup.py"
641            self.install_script(context, 'setuptools', url)
642            # clear up the setuptools archive which gets downloaded
643            pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
644            files = filter(pred, os.listdir(context.bin_path))
645            for f in files:
646                f = os.path.join(context.bin_path, f)
647                os.unlink(f)
648
649        def install_pip(self, context):
650            """
651            Install pip in the virtual environment.
652
653            :param context: The information for the virtual environment
654                            creation request being processed.
655            """
656            url = 'https://bootstrap.pypa.io/get-pip.py'
657            self.install_script(context, 'pip', url)
658
659
660    def main(args=None):
661        import argparse
662
663        parser = argparse.ArgumentParser(prog=__name__,
664                                         description='Creates virtual Python '
665                                                     'environments in one or '
666                                                     'more target '
667                                                     'directories.')
668        parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
669                            help='A directory in which to create the '
670                                 'virtual environment.')
671        parser.add_argument('--no-setuptools', default=False,
672                            action='store_true', dest='nodist',
673                            help="Don't install setuptools or pip in the "
674                                 "virtual environment.")
675        parser.add_argument('--no-pip', default=False,
676                            action='store_true', dest='nopip',
677                            help="Don't install pip in the virtual "
678                                 "environment.")
679        parser.add_argument('--system-site-packages', default=False,
680                            action='store_true', dest='system_site',
681                            help='Give the virtual environment access to the '
682                                 'system site-packages dir.')
683        if os.name == 'nt':
684            use_symlinks = False
685        else:
686            use_symlinks = True
687        parser.add_argument('--symlinks', default=use_symlinks,
688                            action='store_true', dest='symlinks',
689                            help='Try to use symlinks rather than copies, '
690                                 'when symlinks are not the default for '
691                                 'the platform.')
692        parser.add_argument('--clear', default=False, action='store_true',
693                            dest='clear', help='Delete the contents of the '
694                                               'virtual environment '
695                                               'directory if it already '
696                                               'exists, before virtual '
697                                               'environment creation.')
698        parser.add_argument('--upgrade', default=False, action='store_true',
699                            dest='upgrade', help='Upgrade the virtual '
700                                                 'environment directory to '
701                                                 'use this version of '
702                                                 'Python, assuming Python '
703                                                 'has been upgraded '
704                                                 'in-place.')
705        parser.add_argument('--verbose', default=False, action='store_true',
706                            dest='verbose', help='Display the output '
707                                                 'from the scripts which '
708                                                 'install setuptools and pip.')
709        options = parser.parse_args(args)
710        if options.upgrade and options.clear:
711            raise ValueError('you cannot supply --upgrade and --clear together.')
712        builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
713                                       clear=options.clear,
714                                       symlinks=options.symlinks,
715                                       upgrade=options.upgrade,
716                                       nodist=options.nodist,
717                                       nopip=options.nopip,
718                                       verbose=options.verbose)
719        for d in options.dirs:
720            builder.create(d)
721
722    if __name__ == '__main__':
723        rc = 1
724        try:
725            main()
726            rc = 0
727        except Exception as e:
728            print('Error: %s' % e, file=sys.stderr)
729        sys.exit(rc)
730
731
732This script is also available for download `online
733<https://gist.github.com/vsajip/4673395>`_.
734