__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. """
  2. Virtual environment (venv) package for Python. Based on PEP 405.
  3. Copyright (C) 2011-2014 Vinay Sajip.
  4. Licensed to the PSF under a contributor agreement.
  5. """
  6. import logging
  7. import os
  8. import shutil
  9. import subprocess
  10. import sys
  11. import sysconfig
  12. import types
  13. CORE_VENV_DEPS = ('pip', 'setuptools')
  14. logger = logging.getLogger(__name__)
  15. class EnvBuilder:
  16. """
  17. This class exists to allow virtual environment creation to be
  18. customized. The constructor parameters determine the builder's
  19. behaviour when called upon to create a virtual environment.
  20. By default, the builder makes the system (global) site-packages dir
  21. *un*available to the created environment.
  22. If invoked using the Python -m option, the default is to use copying
  23. on Windows platforms but symlinks elsewhere. If instantiated some
  24. other way, the default is to *not* use symlinks.
  25. :param system_site_packages: If True, the system (global) site-packages
  26. dir is available to created environments.
  27. :param clear: If True, delete the contents of the environment directory if
  28. it already exists, before environment creation.
  29. :param symlinks: If True, attempt to symlink rather than copy files into
  30. virtual environment.
  31. :param upgrade: If True, upgrade an existing virtual environment.
  32. :param with_pip: If True, ensure pip is installed in the virtual
  33. environment
  34. :param prompt: Alternative terminal prefix for the environment.
  35. :param upgrade_deps: Update the base venv modules to the latest on PyPI
  36. """
  37. def __init__(self, system_site_packages=False, clear=False,
  38. symlinks=False, upgrade=False, with_pip=False, prompt=None,
  39. upgrade_deps=False):
  40. self.system_site_packages = system_site_packages
  41. self.clear = clear
  42. self.symlinks = symlinks
  43. self.upgrade = upgrade
  44. self.with_pip = with_pip
  45. self.orig_prompt = prompt
  46. if prompt == '.': # see bpo-38901
  47. prompt = os.path.basename(os.getcwd())
  48. self.prompt = prompt
  49. self.upgrade_deps = upgrade_deps
  50. def create(self, env_dir):
  51. """
  52. Create a virtual environment in a directory.
  53. :param env_dir: The target directory to create an environment in.
  54. """
  55. env_dir = os.path.abspath(env_dir)
  56. context = self.ensure_directories(env_dir)
  57. # See issue 24875. We need system_site_packages to be False
  58. # until after pip is installed.
  59. true_system_site_packages = self.system_site_packages
  60. self.system_site_packages = False
  61. self.create_configuration(context)
  62. self.setup_python(context)
  63. if self.with_pip:
  64. self._setup_pip(context)
  65. if not self.upgrade:
  66. self.setup_scripts(context)
  67. self.post_setup(context)
  68. if true_system_site_packages:
  69. # We had set it to False before, now
  70. # restore it and rewrite the configuration
  71. self.system_site_packages = True
  72. self.create_configuration(context)
  73. if self.upgrade_deps:
  74. self.upgrade_dependencies(context)
  75. def clear_directory(self, path):
  76. for fn in os.listdir(path):
  77. fn = os.path.join(path, fn)
  78. if os.path.islink(fn) or os.path.isfile(fn):
  79. os.remove(fn)
  80. elif os.path.isdir(fn):
  81. shutil.rmtree(fn)
  82. def _venv_path(self, env_dir, name):
  83. vars = {
  84. 'base': env_dir,
  85. 'platbase': env_dir,
  86. 'installed_base': env_dir,
  87. 'installed_platbase': env_dir,
  88. }
  89. return sysconfig.get_path(name, scheme='venv', vars=vars)
  90. def ensure_directories(self, env_dir):
  91. """
  92. Create the directories for the environment.
  93. Returns a context object which holds paths in the environment,
  94. for use by subsequent logic.
  95. """
  96. def create_if_needed(d):
  97. if not os.path.exists(d):
  98. os.makedirs(d)
  99. elif os.path.islink(d) or os.path.isfile(d):
  100. raise ValueError('Unable to create directory %r' % d)
  101. if os.pathsep in os.fspath(env_dir):
  102. raise ValueError(f'Refusing to create a venv in {env_dir} because '
  103. f'it contains the PATH separator {os.pathsep}.')
  104. if os.path.exists(env_dir) and self.clear:
  105. self.clear_directory(env_dir)
  106. context = types.SimpleNamespace()
  107. context.env_dir = env_dir
  108. context.env_name = os.path.split(env_dir)[1]
  109. prompt = self.prompt if self.prompt is not None else context.env_name
  110. context.prompt = '(%s) ' % prompt
  111. create_if_needed(env_dir)
  112. executable = sys._base_executable
  113. if not executable: # see gh-96861
  114. raise ValueError('Unable to determine path to the running '
  115. 'Python interpreter. Provide an explicit path or '
  116. 'check that your PATH environment variable is '
  117. 'correctly set.')
  118. dirname, exename = os.path.split(os.path.abspath(executable))
  119. context.executable = executable
  120. context.python_dir = dirname
  121. context.python_exe = exename
  122. binpath = self._venv_path(env_dir, 'scripts')
  123. incpath = self._venv_path(env_dir, 'include')
  124. libpath = self._venv_path(env_dir, 'purelib')
  125. context.inc_path = incpath
  126. create_if_needed(incpath)
  127. create_if_needed(libpath)
  128. # Issue 21197: create lib64 as a symlink to lib on 64-bit non-OS X POSIX
  129. if ((sys.maxsize > 2**32) and (os.name == 'posix') and
  130. (sys.platform != 'darwin')):
  131. link_path = os.path.join(env_dir, 'lib64')
  132. if not os.path.exists(link_path): # Issue #21643
  133. os.symlink('lib', link_path)
  134. context.bin_path = binpath
  135. context.bin_name = os.path.relpath(binpath, env_dir)
  136. context.env_exe = os.path.join(binpath, exename)
  137. create_if_needed(binpath)
  138. # Assign and update the command to use when launching the newly created
  139. # environment, in case it isn't simply the executable script (e.g. bpo-45337)
  140. context.env_exec_cmd = context.env_exe
  141. if sys.platform == 'win32':
  142. # bpo-45337: Fix up env_exec_cmd to account for file system redirections.
  143. # Some redirects only apply to CreateFile and not CreateProcess
  144. real_env_exe = os.path.realpath(context.env_exe)
  145. if os.path.normcase(real_env_exe) != os.path.normcase(context.env_exe):
  146. logger.warning('Actual environment location may have moved due to '
  147. 'redirects, links or junctions.\n'
  148. ' Requested location: "%s"\n'
  149. ' Actual location: "%s"',
  150. context.env_exe, real_env_exe)
  151. context.env_exec_cmd = real_env_exe
  152. return context
  153. def create_configuration(self, context):
  154. """
  155. Create a configuration file indicating where the environment's Python
  156. was copied from, and whether the system site-packages should be made
  157. available in the environment.
  158. :param context: The information for the environment creation request
  159. being processed.
  160. """
  161. context.cfg_path = path = os.path.join(context.env_dir, 'pyvenv.cfg')
  162. with open(path, 'w', encoding='utf-8') as f:
  163. f.write('home = %s\n' % context.python_dir)
  164. if self.system_site_packages:
  165. incl = 'true'
  166. else:
  167. incl = 'false'
  168. f.write('include-system-site-packages = %s\n' % incl)
  169. f.write('version = %d.%d.%d\n' % sys.version_info[:3])
  170. if self.prompt is not None:
  171. f.write(f'prompt = {self.prompt!r}\n')
  172. f.write('executable = %s\n' % os.path.realpath(sys.executable))
  173. args = []
  174. nt = os.name == 'nt'
  175. if nt and self.symlinks:
  176. args.append('--symlinks')
  177. if not nt and not self.symlinks:
  178. args.append('--copies')
  179. if not self.with_pip:
  180. args.append('--without-pip')
  181. if self.system_site_packages:
  182. args.append('--system-site-packages')
  183. if self.clear:
  184. args.append('--clear')
  185. if self.upgrade:
  186. args.append('--upgrade')
  187. if self.upgrade_deps:
  188. args.append('--upgrade-deps')
  189. if self.orig_prompt is not None:
  190. args.append(f'--prompt="{self.orig_prompt}"')
  191. args.append(context.env_dir)
  192. args = ' '.join(args)
  193. f.write(f'command = {sys.executable} -m venv {args}\n')
  194. if os.name != 'nt':
  195. def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
  196. """
  197. Try symlinking a file, and if that fails, fall back to copying.
  198. """
  199. force_copy = not self.symlinks
  200. if not force_copy:
  201. try:
  202. if not os.path.islink(dst): # can't link to itself!
  203. if relative_symlinks_ok:
  204. assert os.path.dirname(src) == os.path.dirname(dst)
  205. os.symlink(os.path.basename(src), dst)
  206. else:
  207. os.symlink(src, dst)
  208. except Exception: # may need to use a more specific exception
  209. logger.warning('Unable to symlink %r to %r', src, dst)
  210. force_copy = True
  211. if force_copy:
  212. shutil.copyfile(src, dst)
  213. else:
  214. def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
  215. """
  216. Try symlinking a file, and if that fails, fall back to copying.
  217. """
  218. bad_src = os.path.lexists(src) and not os.path.exists(src)
  219. if self.symlinks and not bad_src and not os.path.islink(dst):
  220. try:
  221. if relative_symlinks_ok:
  222. assert os.path.dirname(src) == os.path.dirname(dst)
  223. os.symlink(os.path.basename(src), dst)
  224. else:
  225. os.symlink(src, dst)
  226. return
  227. except Exception: # may need to use a more specific exception
  228. logger.warning('Unable to symlink %r to %r', src, dst)
  229. # On Windows, we rewrite symlinks to our base python.exe into
  230. # copies of venvlauncher.exe
  231. basename, ext = os.path.splitext(os.path.basename(src))
  232. srcfn = os.path.join(os.path.dirname(__file__),
  233. "scripts",
  234. "nt",
  235. basename + ext)
  236. # Builds or venv's from builds need to remap source file
  237. # locations, as we do not put them into Lib/venv/scripts
  238. if sysconfig.is_python_build() or not os.path.isfile(srcfn):
  239. if basename.endswith('_d'):
  240. ext = '_d' + ext
  241. basename = basename[:-2]
  242. if basename == 'python':
  243. basename = 'venvlauncher'
  244. elif basename == 'pythonw':
  245. basename = 'venvwlauncher'
  246. src = os.path.join(os.path.dirname(src), basename + ext)
  247. else:
  248. src = srcfn
  249. if not os.path.exists(src):
  250. if not bad_src:
  251. logger.warning('Unable to copy %r', src)
  252. return
  253. shutil.copyfile(src, dst)
  254. def setup_python(self, context):
  255. """
  256. Set up a Python executable in the environment.
  257. :param context: The information for the environment creation request
  258. being processed.
  259. """
  260. binpath = context.bin_path
  261. path = context.env_exe
  262. copier = self.symlink_or_copy
  263. dirname = context.python_dir
  264. if os.name != 'nt':
  265. copier(context.executable, path)
  266. if not os.path.islink(path):
  267. os.chmod(path, 0o755)
  268. for suffix in ('python', 'python3', f'python3.{sys.version_info[1]}'):
  269. path = os.path.join(binpath, suffix)
  270. if not os.path.exists(path):
  271. # Issue 18807: make copies if
  272. # symlinks are not wanted
  273. copier(context.env_exe, path, relative_symlinks_ok=True)
  274. if not os.path.islink(path):
  275. os.chmod(path, 0o755)
  276. else:
  277. if self.symlinks:
  278. # For symlinking, we need a complete copy of the root directory
  279. # If symlinks fail, you'll get unnecessary copies of files, but
  280. # we assume that if you've opted into symlinks on Windows then
  281. # you know what you're doing.
  282. suffixes = [
  283. f for f in os.listdir(dirname) if
  284. os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
  285. ]
  286. if sysconfig.is_python_build():
  287. suffixes = [
  288. f for f in suffixes if
  289. os.path.normcase(f).startswith(('python', 'vcruntime'))
  290. ]
  291. else:
  292. suffixes = {'python.exe', 'python_d.exe', 'pythonw.exe', 'pythonw_d.exe'}
  293. base_exe = os.path.basename(context.env_exe)
  294. suffixes.add(base_exe)
  295. for suffix in suffixes:
  296. src = os.path.join(dirname, suffix)
  297. if os.path.lexists(src):
  298. copier(src, os.path.join(binpath, suffix))
  299. if sysconfig.is_python_build():
  300. # copy init.tcl
  301. for root, dirs, files in os.walk(context.python_dir):
  302. if 'init.tcl' in files:
  303. tcldir = os.path.basename(root)
  304. tcldir = os.path.join(context.env_dir, 'Lib', tcldir)
  305. if not os.path.exists(tcldir):
  306. os.makedirs(tcldir)
  307. src = os.path.join(root, 'init.tcl')
  308. dst = os.path.join(tcldir, 'init.tcl')
  309. shutil.copyfile(src, dst)
  310. break
  311. def _call_new_python(self, context, *py_args, **kwargs):
  312. """Executes the newly created Python using safe-ish options"""
  313. # gh-98251: We do not want to just use '-I' because that masks
  314. # legitimate user preferences (such as not writing bytecode). All we
  315. # really need is to ensure that the path variables do not overrule
  316. # normal venv handling.
  317. args = [context.env_exec_cmd, *py_args]
  318. kwargs['env'] = env = os.environ.copy()
  319. env['VIRTUAL_ENV'] = context.env_dir
  320. env.pop('PYTHONHOME', None)
  321. env.pop('PYTHONPATH', None)
  322. kwargs['cwd'] = context.env_dir
  323. kwargs['executable'] = context.env_exec_cmd
  324. subprocess.check_output(args, **kwargs)
  325. def _setup_pip(self, context):
  326. """Installs or upgrades pip in a virtual environment"""
  327. self._call_new_python(context, '-m', 'ensurepip', '--upgrade',
  328. '--default-pip', stderr=subprocess.STDOUT)
  329. def setup_scripts(self, context):
  330. """
  331. Set up scripts into the created environment from a directory.
  332. This method installs the default scripts into the environment
  333. being created. You can prevent the default installation by overriding
  334. this method if you really need to, or if you need to specify
  335. a different location for the scripts to install. By default, the
  336. 'scripts' directory in the venv package is used as the source of
  337. scripts to install.
  338. """
  339. path = os.path.abspath(os.path.dirname(__file__))
  340. path = os.path.join(path, 'scripts')
  341. self.install_scripts(context, path)
  342. def post_setup(self, context):
  343. """
  344. Hook for post-setup modification of the venv. Subclasses may install
  345. additional packages or scripts here, add activation shell scripts, etc.
  346. :param context: The information for the environment creation request
  347. being processed.
  348. """
  349. pass
  350. def replace_variables(self, text, context):
  351. """
  352. Replace variable placeholders in script text with context-specific
  353. variables.
  354. Return the text passed in , but with variables replaced.
  355. :param text: The text in which to replace placeholder variables.
  356. :param context: The information for the environment creation request
  357. being processed.
  358. """
  359. text = text.replace('__VENV_DIR__', context.env_dir)
  360. text = text.replace('__VENV_NAME__', context.env_name)
  361. text = text.replace('__VENV_PROMPT__', context.prompt)
  362. text = text.replace('__VENV_BIN_NAME__', context.bin_name)
  363. text = text.replace('__VENV_PYTHON__', context.env_exe)
  364. return text
  365. def install_scripts(self, context, path):
  366. """
  367. Install scripts into the created environment from a directory.
  368. :param context: The information for the environment creation request
  369. being processed.
  370. :param path: Absolute pathname of a directory containing script.
  371. Scripts in the 'common' subdirectory of this directory,
  372. and those in the directory named for the platform
  373. being run on, are installed in the created environment.
  374. Placeholder variables are replaced with environment-
  375. specific values.
  376. """
  377. binpath = context.bin_path
  378. plen = len(path)
  379. for root, dirs, files in os.walk(path):
  380. if root == path: # at top-level, remove irrelevant dirs
  381. for d in dirs[:]:
  382. if d not in ('common', os.name):
  383. dirs.remove(d)
  384. continue # ignore files in top level
  385. for f in files:
  386. if (os.name == 'nt' and f.startswith('python')
  387. and f.endswith(('.exe', '.pdb'))):
  388. continue
  389. srcfile = os.path.join(root, f)
  390. suffix = root[plen:].split(os.sep)[2:]
  391. if not suffix:
  392. dstdir = binpath
  393. else:
  394. dstdir = os.path.join(binpath, *suffix)
  395. if not os.path.exists(dstdir):
  396. os.makedirs(dstdir)
  397. dstfile = os.path.join(dstdir, f)
  398. with open(srcfile, 'rb') as f:
  399. data = f.read()
  400. if not srcfile.endswith(('.exe', '.pdb')):
  401. try:
  402. data = data.decode('utf-8')
  403. data = self.replace_variables(data, context)
  404. data = data.encode('utf-8')
  405. except UnicodeError as e:
  406. data = None
  407. logger.warning('unable to copy script %r, '
  408. 'may be binary: %s', srcfile, e)
  409. if data is not None:
  410. with open(dstfile, 'wb') as f:
  411. f.write(data)
  412. shutil.copymode(srcfile, dstfile)
  413. def upgrade_dependencies(self, context):
  414. logger.debug(
  415. f'Upgrading {CORE_VENV_DEPS} packages in {context.bin_path}'
  416. )
  417. self._call_new_python(context, '-m', 'pip', 'install', '--upgrade',
  418. *CORE_VENV_DEPS)
  419. def create(env_dir, system_site_packages=False, clear=False,
  420. symlinks=False, with_pip=False, prompt=None, upgrade_deps=False):
  421. """Create a virtual environment in a directory."""
  422. builder = EnvBuilder(system_site_packages=system_site_packages,
  423. clear=clear, symlinks=symlinks, with_pip=with_pip,
  424. prompt=prompt, upgrade_deps=upgrade_deps)
  425. builder.create(env_dir)
  426. def main(args=None):
  427. compatible = True
  428. if sys.version_info < (3, 3):
  429. compatible = False
  430. elif not hasattr(sys, 'base_prefix'):
  431. compatible = False
  432. if not compatible:
  433. raise ValueError('This script is only for use with Python >= 3.3')
  434. else:
  435. import argparse
  436. parser = argparse.ArgumentParser(prog=__name__,
  437. description='Creates virtual Python '
  438. 'environments in one or '
  439. 'more target '
  440. 'directories.',
  441. epilog='Once an environment has been '
  442. 'created, you may wish to '
  443. 'activate it, e.g. by '
  444. 'sourcing an activate script '
  445. 'in its bin directory.')
  446. parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
  447. help='A directory to create the environment in.')
  448. parser.add_argument('--system-site-packages', default=False,
  449. action='store_true', dest='system_site',
  450. help='Give the virtual environment access to the '
  451. 'system site-packages dir.')
  452. if os.name == 'nt':
  453. use_symlinks = False
  454. else:
  455. use_symlinks = True
  456. group = parser.add_mutually_exclusive_group()
  457. group.add_argument('--symlinks', default=use_symlinks,
  458. action='store_true', dest='symlinks',
  459. help='Try to use symlinks rather than copies, '
  460. 'when symlinks are not the default for '
  461. 'the platform.')
  462. group.add_argument('--copies', default=not use_symlinks,
  463. action='store_false', dest='symlinks',
  464. help='Try to use copies rather than symlinks, '
  465. 'even when symlinks are the default for '
  466. 'the platform.')
  467. parser.add_argument('--clear', default=False, action='store_true',
  468. dest='clear', help='Delete the contents of the '
  469. 'environment directory if it '
  470. 'already exists, before '
  471. 'environment creation.')
  472. parser.add_argument('--upgrade', default=False, action='store_true',
  473. dest='upgrade', help='Upgrade the environment '
  474. 'directory to use this version '
  475. 'of Python, assuming Python '
  476. 'has been upgraded in-place.')
  477. parser.add_argument('--without-pip', dest='with_pip',
  478. default=True, action='store_false',
  479. help='Skips installing or upgrading pip in the '
  480. 'virtual environment (pip is bootstrapped '
  481. 'by default)')
  482. parser.add_argument('--prompt',
  483. help='Provides an alternative prompt prefix for '
  484. 'this environment.')
  485. parser.add_argument('--upgrade-deps', default=False, action='store_true',
  486. dest='upgrade_deps',
  487. help='Upgrade core dependencies: {} to the latest '
  488. 'version in PyPI'.format(
  489. ' '.join(CORE_VENV_DEPS)))
  490. options = parser.parse_args(args)
  491. if options.upgrade and options.clear:
  492. raise ValueError('you cannot supply --upgrade and --clear together.')
  493. builder = EnvBuilder(system_site_packages=options.system_site,
  494. clear=options.clear,
  495. symlinks=options.symlinks,
  496. upgrade=options.upgrade,
  497. with_pip=options.with_pip,
  498. prompt=options.prompt,
  499. upgrade_deps=options.upgrade_deps)
  500. for d in options.dirs:
  501. builder.create(d)
  502. if __name__ == '__main__':
  503. rc = 1
  504. try:
  505. main()
  506. rc = 0
  507. except Exception as e:
  508. print('Error: %s' % e, file=sys.stderr)
  509. sys.exit(rc)