Debian Codegraph @

lib-python/3/venv/__init__.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 """
2 Virtual environment (venv) package for Python. Based on PEP 405.
3
4 Copyright (C) 2011-2014 Vinay Sajip.
5 Licensed to the PSF under a contributor agreement.
6 """
7 import logging
8 import os
9 import shutil
10 import subprocess
11 import sys
12 import sysconfig
13 import types
14 import shlex
15
16
17 CORE_VENV_DEPS = ('pip', 'setuptools')
18 logger = logging.getLogger(__name__)
19
20 IS_PYPY = sys.implementation.name == 'pypy'
21
22 class EnvBuilder:
23 """
24 This class exists to allow virtual environment creation to be
25 customized. The constructor parameters determine the builder's
26 behaviour when called upon to create a virtual environment.
27
28 By default, the builder makes the system (global) site-packages dir
29 *un*available to the created environment.
30
31 If invoked using the Python -m option, the default is to use copying
32 on Windows platforms but symlinks elsewhere. If instantiated some
33 other way, the default is to *not* use symlinks.
34
35 :param system_site_packages: If True, the system (global) site-packages
36 dir is available to created environments.
37 :param clear: If True, delete the contents of the environment directory if
38 it already exists, before environment creation.
39 :param symlinks: If True, attempt to symlink rather than copy files into
40 virtual environment.
41 :param upgrade: If True, upgrade an existing virtual environment.
42 :param with_pip: If True, ensure pip is installed in the virtual
43 environment
44 :param prompt: Alternative terminal prefix for the environment.
45 :param upgrade_deps: Update the base venv modules to the latest on PyPI
46 """
47
48 def __init__(self, system_site_packages=False, clear=False,
49 symlinks=False, upgrade=False, with_pip=False, prompt=None,
50 upgrade_deps=False):
51 self.system_site_packages = system_site_packages
52 self.clear = clear
53 self.symlinks = symlinks
54 self.upgrade = upgrade
55 self.with_pip = with_pip
56 self.orig_prompt = prompt
57 if prompt == '.': # see bpo-38901
58 prompt = os.path.basename(os.getcwd())
59 self.prompt = prompt
60 self.upgrade_deps = upgrade_deps
61
62 def create(self, env_dir):
63 """
64 Create a virtual environment in a directory.
65
66 :param env_dir: The target directory to create an environment in.
67
68 """
69 env_dir = os.path.abspath(env_dir)
70 context = self.ensure_directories(env_dir)
71 # See issue 24875. We need system_site_packages to be False
72 # until after pip is installed.
73 true_system_site_packages = self.system_site_packages
74 self.system_site_packages = False
75 self.create_configuration(context)
76 self.setup_python(context)
77 if self.with_pip:
78 self._setup_pip(context)
79 if not self.upgrade:
80 self.setup_scripts(context)
81 self.post_setup(context)
82 if true_system_site_packages:
83 # We had set it to False before, now
84 # restore it and rewrite the configuration
85 self.system_site_packages = True
86 self.create_configuration(context)
87 if self.upgrade_deps:
88 self.upgrade_dependencies(context)
89
90 def clear_directory(self, path):
91 for fn in os.listdir(path):
92 fn = os.path.join(path, fn)
93 if os.path.islink(fn) or os.path.isfile(fn):
94 os.remove(fn)
95 elif os.path.isdir(fn):
96 shutil.rmtree(fn)
97
98 def _venv_path(self, env_dir, name):
99 vars = {
100 'base': env_dir,
101 'platbase': env_dir,
102 'installed_base': env_dir,
103 'installed_platbase': env_dir,
104 }
105 return sysconfig.get_path(name, scheme='venv', vars=vars)
106
107 def ensure_directories(self, env_dir):
108 """
109 Create the directories for the environment.
110
111 Returns a context object which holds paths in the environment,
112 for use by subsequent logic.
113 """
114
115 def create_if_needed(d):
116 if not os.path.exists(d):
117 os.makedirs(d)
118 elif os.path.islink(d) or os.path.isfile(d):
119 raise ValueError('Unable to create directory %r' % d)
120
121 if os.pathsep in os.fspath(env_dir):
122 raise ValueError(f'Refusing to create a venv in {env_dir} because '
123 f'it contains the PATH separator {os.pathsep}.')
124 if os.path.exists(env_dir) and self.clear:
125 self.clear_directory(env_dir)
126 context = types.SimpleNamespace()
127 context.env_dir = env_dir
128 context.env_name = os.path.split(env_dir)[1]
129 prompt = self.prompt if self.prompt is not None else context.env_name
130 context.prompt = '(%s) ' % prompt
131 create_if_needed(env_dir)
132 executable = sys._base_executable
133 if not executable: # see gh-96861
134 raise ValueError('Unable to determine path to the running '
135 'Python interpreter. Provide an explicit path or '
136 'check that your PATH environment variable is '
137 'correctly set.')
138 dirname, exename = os.path.split(os.path.abspath(executable))
139 context.executable = executable
140 context.python_dir = dirname
141 context.python_exe = exename
142 binpath = self._venv_path(env_dir, 'scripts')
143 incpath = self._venv_path(env_dir, 'include')
144 libpath = self._venv_path(env_dir, 'purelib')
145
146 context.inc_path = incpath
147 create_if_needed(incpath)
148 create_if_needed(libpath)
149 # Issue 21197: create lib64 as a symlink to lib on 64-bit non-OS X POSIX
150 if ((sys.maxsize > 2**32) and (os.name == 'posix') and
151 (sys.platform != 'darwin')):
152 link_path = os.path.join(env_dir, 'lib64')
153 if not os.path.exists(link_path): # Issue #21643
154 os.symlink('lib', link_path)
155 context.bin_path = binpath
156 context.bin_name = os.path.relpath(binpath, env_dir)
157 context.env_exe = os.path.join(binpath, exename)
158 create_if_needed(binpath)
159 # Assign and update the command to use when launching the newly created
160 # environment, in case it isn't simply the executable script (e.g. bpo-45337)
161 context.env_exec_cmd = context.env_exe
162 if sys.platform == 'win32':
163 # bpo-45337: Fix up env_exec_cmd to account for file system redirections.
164 # Some redirects only apply to CreateFile and not CreateProcess
165 real_env_exe = os.path.realpath(context.env_exe)
166 if os.path.normcase(real_env_exe) != os.path.normcase(context.env_exe):
167 logger.warning('Actual environment location may have moved due to '
168 'redirects, links or junctions.\n'
169 ' Requested location: "%s"\n'
170 ' Actual location: "%s"',
171 context.env_exe, real_env_exe)
172 context.env_exec_cmd = real_env_exe
173 return context
174
175 def create_configuration(self, context):
176 """
177 Create a configuration file indicating where the environment's Python
178 was copied from, and whether the system site-packages should be made
179 available in the environment.
180
181 :param context: The information for the environment creation request
182 being processed.
183 """
184 context.cfg_path = path = os.path.join(context.env_dir, 'pyvenv.cfg')
185 with open(path, 'w', encoding='utf-8') as f:
186 f.write('home = %s\n' % context.python_dir)
187 if self.system_site_packages:
188 incl = 'true'
189 else:
190 incl = 'false'
191 f.write('include-system-site-packages = %s\n' % incl)
192 f.write('version = %d.%d.%d\n' % sys.version_info[:3])
193 if self.prompt is not None:
194 f.write(f'prompt = {self.prompt!r}\n')
195 f.write('executable = %s\n' % os.path.realpath(sys.executable))
196 args = []
197 nt = os.name == 'nt'
198 if nt and self.symlinks:
199 args.append('--symlinks')
200 if not nt and not self.symlinks:
201 args.append('--copies')
202 if not self.with_pip:
203 args.append('--without-pip')
204 if self.system_site_packages:
205 args.append('--system-site-packages')
206 if self.clear:
207 args.append('--clear')
208 if self.upgrade:
209 args.append('--upgrade')
210 if self.upgrade_deps:
211 args.append('--upgrade-deps')
212 if self.orig_prompt is not None:
213 args.append(f'--prompt="{self.orig_prompt}"')
214
215 args.append(context.env_dir)
216 args = ' '.join(args)
217 f.write(f'command = {sys.executable} -m venv {args}\n')
218
219 if os.name != 'nt':
220 def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
221 """
222 Try symlinking a file, and if that fails, fall back to copying.
223 """
224 force_copy = not self.symlinks
225 if not force_copy:
226 try:
227 if not os.path.islink(dst): # can't link to itself!
228 if relative_symlinks_ok:
229 assert os.path.dirname(src) == os.path.dirname(dst)
230 os.symlink(os.path.basename(src), dst)
231 else:
232 os.symlink(src, dst)
233 except Exception: # may need to use a more specific exception
234 logger.warning('Unable to symlink %r to %r', src, dst)
235 force_copy = True
236 if force_copy:
237 if os.path.isdir(src):
238 shutil.copytree(src, dst)
239 elif os.path.islink(src):
240 # On PyPy, creating a copy of a symlinked-venv must still
241 # point back to the original file since the exe needs
242 # libpypy* and perhaps other 'portable' shared objects
243 final = os.path.realpath(src)
244 os.symlink(final, dst)
245 else:
246 shutil.copyfile(src, dst)
247 else:
248 def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
249 """
250 Try symlinking a file, and if that fails, fall back to copying.
251 """
252 bad_src = os.path.lexists(src) and not os.path.exists(src)
253 if self.symlinks and not bad_src and not os.path.islink(dst):
254 try:
255 if relative_symlinks_ok:
256 assert os.path.dirname(src) == os.path.dirname(dst)
257 os.symlink(os.path.basename(src), dst)
258 else:
259 os.symlink(src, dst)
260 return
261 except Exception: # may need to use a more specific exception
262 logger.warning('Unable to symlink %r to %r', src, dst)
263
264 # On Windows, we rewrite symlinks to our base python.exe into
265 # copies of venvlauncher.exe
266 basename, ext = os.path.splitext(os.path.basename(src))
267 srcfn = os.path.join(os.path.dirname(__file__),
268 "scripts",
269 "nt",
270 basename + ext)
271 # Builds or venv's from builds need to remap source file
272 # locations, as we do not put them into Lib/venv/scripts
273 if sysconfig.is_python_build() or not os.path.isfile(srcfn):
274 if basename.endswith('_d'):
275 ext = '_d' + ext
276 basename = basename[:-2]
277 if not IS_PYPY and basename == 'python':
278 basename = 'venvlauncher'
279 elif not IS_PYPY and basename == 'pythonw':
280 basename = 'venvwlauncher'
281 src = os.path.join(os.path.dirname(src), basename + ext)
282 else:
283 src = srcfn
284 if not os.path.exists(src):
285 if not bad_src:
286 logger.warning('Unable to copy %r', src)
287 return
288
289 shutil.copyfile(src, dst)
290
291 def setup_python(self, context):
292 """
293 Set up a Python executable in the environment.
294
295 :param context: The information for the environment creation request
296 being processed.
297 """
298 binpath = context.bin_path
299 path = context.env_exe
300 copier = self.symlink_or_copy
301 dirname = context.python_dir
302 if os.name != 'nt':
303 copier(context.executable, path)
304 if not os.path.islink(path):
305 os.chmod(path, 0o755)
306 for suffix in ('python', 'python3', f'python3.{sys.version_info[1]}', 'pypy3', 'pypy'):
307 path = os.path.join(binpath, suffix)
308 if not os.path.exists(path):
309 # Issue 18807: make copies if
310 # symlinks are not wanted
311 copier(context.env_exe, path, relative_symlinks_ok=True)
312 if not os.path.islink(path):
313 os.chmod(path, 0o755)
314 if not self.symlinks:
315 #
316 # PyPy extension: also copy the main library, not just the
317 # small executable
318 for libname in ['libpypy3.11-c.so', 'libpypy3.11-c.dylib']:
319 dest_library = os.path.join(binpath, libname)
320 src_library = os.path.join(os.path.dirname(context.executable),
321 libname)
322 if (not os.path.exists(dest_library) and
323 os.path.exists(src_library)):
324 copier(src_library, dest_library)
325 if not os.path.islink(dest_library):
326 os.chmod(dest_library, 0o755)
327 libsrc = os.path.join(context.python_dir, '..', 'lib')
328 deps_file = os.path.join(libsrc, "PYPY_PORTABLE_DEPS.txt")
329 if os.path.exists(libsrc) and os.path.exists(deps_file):
330 # PyPy: also copy lib/*.so*, lib/tk, lib/tcl for portable
331 # builds
332 libdst = os.path.join(context.env_dir, 'lib')
333 if not os.path.exists(libdst):
334 os.mkdir(libdst)
335 with open(deps_file, encoding="utf-8") as fid:
336 for f in fid:
337 src = os.path.join(libsrc, f.strip())
338 dst = os.path.join(libdst, f.strip())
339 if os.path.exists(src):
340 if os.path.exists(dst):
341 # skip directories when upgrading
342 continue
343 copier(src, dst)
344 #
345 else:
346 if self.symlinks:
347 # For symlinking, we need a complete copy of the root directory
348 # If symlinks fail, you'll get unnecessary copies of files, but
349 # we assume that if you've opted into symlinks on Windows then
350 # you know what you're doing.
351 suffixes = [
352 f for f in os.listdir(dirname) if
353 os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
354 ]
355 if sysconfig.is_python_build():
356 suffixes = [
357 f for f in suffixes if
358 os.path.normcase(f).startswith(('python', 'vcruntime'))
359 ]
360 else:
361 # PyPy change: since PyPy does not use a PEP 397 launcher,
362 # copy all the exes and dlls.
363 suffixes = [
364 f for f in os.listdir(dirname) if
365 os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
366 ]
367 base_exe = os.path.basename(context.env_exe)
368 suffixes.append(base_exe)
369
370 for suffix in suffixes:
371 src = os.path.join(dirname, suffix)
372 if os.path.lexists(src):
373 copier(src, os.path.join(binpath, suffix))
374
375 exe = os.path.split(sys.executable)[1].lower()
376 if exe not in suffixes:
377 if "pypy3.11-c.exe" in suffixes:
378 # dirname is a source build, with only the
379 # pypy*-c.exe? Make sure to create
380 # sys.executable as well
381 src = os.path.join(dirname, "pypy3.11-c.exe")
382 dst = os.path.join(binpath, exe)
383 copier(src, dst)
384 elif not suffixes:
385 # dirname is a source build from dirname\pypy\goal
386 # so add that to dirname and try again
387 dirname = os.path.join(dirname, "pypy", "goal")
388 suffixes = [
389 f for f in os.listdir(dirname) if
390 os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
391 ]
392 for suffix in suffixes:
393 src = os.path.join(dirname, suffix)
394 if os.path.lexists(src):
395 copier(src, os.path.join(binpath, suffix))
396 src = os.path.join(dirname, "pypy3.11-c.exe")
397 if src != context.env_exec_cmd:
398 copier(src, context.env_exec_cmd)
399 copier(src, os.path.join(binpath, "python.exe"))
400 copier(src, os.path.join(binpath, "python3.exe"))
401 else:
402 raise RuntimeError(f"problem finding exe {exe} in {suffixes}")
403
404 if sysconfig.is_python_build(True):
405 # copy init.tcl
406 for root, dirs, files in os.walk(context.python_dir):
407 if 'init.tcl' in files:
408 tcldir = os.path.basename(root)
409 tcldir = os.path.join(context.env_dir, 'Lib', tcldir)
410 if not os.path.exists(tcldir):
411 os.makedirs(tcldir)
412 src = os.path.join(root, 'init.tcl')
413 dst = os.path.join(tcldir, 'init.tcl')
414 shutil.copyfile(src, dst)
415 break
416
417 def _call_new_python(self, context, *py_args, **kwargs):
418 """Executes the newly created Python using safe-ish options"""
419 # gh-98251: We do not want to just use '-I' because that masks
420 # legitimate user preferences (such as not writing bytecode). All we
421 # really need is to ensure that the path variables do not overrule
422 # normal venv handling.
423 args = [context.env_exec_cmd, *py_args]
424 kwargs['env'] = env = os.environ.copy()
425 env['VIRTUAL_ENV'] = context.env_dir
426 env.pop('PYTHONHOME', None)
427 env.pop('PYTHONPATH', None)
428 kwargs['cwd'] = context.env_dir
429 kwargs['executable'] = context.env_exec_cmd
430 subprocess.check_output(args, **kwargs)
431
432 def _setup_pip(self, context):
433 """Installs or upgrades pip in a virtual environment"""
•434 try:
435 self._call_new_python(context, '-m', 'ensurepip', '--upgrade',
436 '--default-pip', stderr=subprocess.STDOUT)
437 except subprocess.CalledProcessError:
438 stdlib = sysconfig.get_path('stdlib')
439 if not os.path.exists(f'{stdlib}/ensurepip/__main__.py'):
440 print("""\
441 The virtual environment was not created successfully because ensurepip is not
442 available. On Debian/Ubuntu systems, you need to install the pypy3-venv
443 package using the following command.
444
445 apt-get install pypy3-venv
446
447 You may need to use sudo with that command. After installing the pypy3-venv
448 package, recreate your virtual environment.
449
450 Failing command: {}
451 """.format(context.env_exec_cmd))
452 sys.exit(1)
453 raise
454
455 def setup_scripts(self, context):
456 """
457 Set up scripts into the created environment from a directory.
458
459 This method installs the default scripts into the environment
460 being created. You can prevent the default installation by overriding
461 this method if you really need to, or if you need to specify
462 a different location for the scripts to install. By default, the
463 'scripts' directory in the venv package is used as the source of
464 scripts to install.
465 """
466 path = os.path.abspath(os.path.dirname(__file__))
467 path = os.path.join(path, 'scripts')
468 self.install_scripts(context, path)
469
470 def post_setup(self, context):
471 """
472 Hook for post-setup modification of the venv. Subclasses may install
473 additional packages or scripts here, add activation shell scripts, etc.
474
475 :param context: The information for the environment creation request
476 being processed.
477 """
478 pass
479
480 def replace_variables(self, text, context):
481 """
482 Replace variable placeholders in script text with context-specific
483 variables.
484
485 Return the text passed in , but with variables replaced.
486
487 :param text: The text in which to replace placeholder variables.
488 :param context: The information for the environment creation request
489 being processed.
490 """
491 replacements = {
492 '__VENV_DIR__': context.env_dir,
493 '__VENV_NAME__': context.env_name,
494 '__VENV_PROMPT__': context.prompt,
495 '__VENV_BIN_NAME__': context.bin_name,
496 '__VENV_PYTHON__': context.env_exe,
497 }
498
499 def quote_ps1(s):
500 """
501 This should satisfy PowerShell quoting rules [1], unless the quoted
502 string is passed directly to Windows native commands [2].
503 [1]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
504 [2]: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing#passing-arguments-that-contain-quote-characters
505 """
506 s = s.replace("'", "''")
507 return f"'{s}'"
508
509 def quote_bat(s):
510 return s
511
512 # gh-124651: need to quote the template strings properly
513 quote = shlex.quote
514 script_path = context.script_path
515 if script_path.endswith('.ps1'):
516 quote = quote_ps1
517 elif script_path.endswith('.bat'):
518 quote = quote_bat
519 else:
520 # fallbacks to POSIX shell compliant quote
521 quote = shlex.quote
522
523 replacements = {key: quote(s) for key, s in replacements.items()}
524 for key, quoted in replacements.items():
525 text = text.replace(key, quoted)
526 return text
527
528 def install_scripts(self, context, path):
529 """
530 Install scripts into the created environment from a directory.
531
532 :param context: The information for the environment creation request
533 being processed.
534 :param path: Absolute pathname of a directory containing script.
535 Scripts in the 'common' subdirectory of this directory,
536 and those in the directory named for the platform
537 being run on, are installed in the created environment.
538 Placeholder variables are replaced with environment-
539 specific values.
540 """
541 binpath = context.bin_path
542 plen = len(path)
543 for root, dirs, files in os.walk(path):
544 if root == path: # at top-level, remove irrelevant dirs
545 for d in dirs[:]:
546 if d not in ('common', os.name):
547 dirs.remove(d)
548 continue # ignore files in top level
549 for f in files:
550 if (os.name == 'nt' and f.startswith('python')
551 and f.endswith(('.exe', '.pdb'))):
552 continue
553 srcfile = os.path.join(root, f)
554 suffix = root[plen:].split(os.sep)[2:]
555 if not suffix:
556 dstdir = binpath
557 else:
558 dstdir = os.path.join(binpath, *suffix)
559 if not os.path.exists(dstdir):
560 os.makedirs(dstdir)
561 dstfile = os.path.join(dstdir, f)
562 with open(srcfile, 'rb') as f:
563 data = f.read()
564 if not srcfile.endswith(('.exe', '.pdb')):
565 context.script_path = srcfile
566 try:
567 data = data.decode('utf-8')
568 data = self.replace_variables(data, context)
569 data = data.encode('utf-8')
570 except UnicodeError as e:
571 data = None
572 logger.warning('unable to copy script %r, '
573 'may be binary: %s', srcfile, e)
574 if data is not None:
575 with open(dstfile, 'wb') as f:
576 f.write(data)
577 shutil.copymode(srcfile, dstfile)
578
579 def upgrade_dependencies(self, context):
580 logger.debug(
581 f'Upgrading {CORE_VENV_DEPS} packages in {context.bin_path}'
582 )
583 self._call_new_python(context, '-m', 'pip', 'install', '--upgrade',
584 *CORE_VENV_DEPS)
585
586
587 def create(env_dir, system_site_packages=False, clear=False,
588 symlinks=False, with_pip=False, prompt=None, upgrade_deps=False):
589 """Create a virtual environment in a directory."""
590 builder = EnvBuilder(system_site_packages=system_site_packages,
591 clear=clear, symlinks=symlinks, with_pip=with_pip,
592 prompt=prompt, upgrade_deps=upgrade_deps)
593 builder.create(env_dir)
594
595 def main(args=None):
596 compatible = True
597 if sys.version_info < (3, 3):
598 compatible = False
599 elif not hasattr(sys, 'base_prefix'):
600 compatible = False
601 if not compatible:
602 raise ValueError('This script is only for use with Python >= 3.3')
603 else:
604 import argparse
605
606 parser = argparse.ArgumentParser(prog=__name__,
607 description='Creates virtual Python '
608 'environments in one or '
609 'more target '
610 'directories.',
611 epilog='Once an environment has been '
612 'created, you may wish to '
613 'activate it, e.g. by '
614 'sourcing an activate script '
615 'in its bin directory.')
616 parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
617 help='A directory to create the environment in.')
618 parser.add_argument('--system-site-packages', default=False,
619 action='store_true', dest='system_site',
620 help='Give the virtual environment access to the '
621 'system site-packages dir.')
622 if os.name == 'nt':
623 use_symlinks = False
624 else:
625 use_symlinks = True
626 group = parser.add_mutually_exclusive_group()
627 group.add_argument('--symlinks', default=use_symlinks,
628 action='store_true', dest='symlinks',
629 help='Try to use symlinks rather than copies, '
630 'when symlinks are not the default for '
631 'the platform.')
632 group.add_argument('--copies', default=not use_symlinks,
633 action='store_false', dest='symlinks',
634 help='Try to use copies rather than symlinks, '
635 'even when symlinks are the default for '
636 'the platform.')
637 parser.add_argument('--clear', default=False, action='store_true',
638 dest='clear', help='Delete the contents of the '
639 'environment directory if it '
640 'already exists, before '
641 'environment creation.')
642 parser.add_argument('--upgrade', default=False, action='store_true',
643 dest='upgrade', help='Upgrade the environment '
644 'directory to use this version '
645 'of Python, assuming Python '
646 'has been upgraded in-place.')
647 parser.add_argument('--without-pip', dest='with_pip',
648 default=True, action='store_false',
649 help='Skips installing or upgrading pip in the '
650 'virtual environment (pip is bootstrapped '
651 'by default)')
652 parser.add_argument('--prompt',
653 help='Provides an alternative prompt prefix for '
654 'this environment.')
655 parser.add_argument('--upgrade-deps', default=False, action='store_true',
656 dest='upgrade_deps',
657 help='Upgrade core dependencies: {} to the latest '
658 'version in PyPI'.format(
659 ' '.join(CORE_VENV_DEPS)))
660 options = parser.parse_args(args)
661 if options.upgrade and options.clear:
662 raise ValueError('you cannot supply --upgrade and --clear together.')
663 builder = EnvBuilder(system_site_packages=options.system_site,
664 clear=options.clear,
665 symlinks=options.symlinks,
666 upgrade=options.upgrade,
667 with_pip=options.with_pip,
668 prompt=options.prompt,
669 upgrade_deps=options.upgrade_deps)
670 for d in options.dirs:
671 builder.create(d)
672
673 if __name__ == '__main__':
674 rc = 1
675 try:
676 main()
677 rc = 0
678 except Exception as e:
679 print('Error: %s' % e, file=sys.stderr)
680 sys.exit(rc)