Debian Codegraph @

Doc/library/venv.rst

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