__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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',)
  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. context.lib_path = libpath
  128. create_if_needed(libpath)
  129. # Issue 21197: create lib64 as a symlink to lib on 64-bit non-OS X POSIX
  130. if ((sys.maxsize > 2**32) and (os.name == 'posix') and
  131. (sys.platform != 'darwin')):
  132. link_path = os.path.join(env_dir, 'lib64')
  133. if not os.path.exists(link_path): # Issue #21643
  134. os.symlink('lib', link_path)
  135. context.bin_path = binpath
  136. context.bin_name = os.path.relpath(binpath, env_dir)
  137. context.env_exe = os.path.join(binpath, exename)
  138. create_if_needed(binpath)
  139. # Assign and update the command to use when launching the newly created
  140. # environment, in case it isn't simply the executable script (e.g. bpo-45337)
  141. context.env_exec_cmd = context.env_exe
  142. if sys.platform == 'win32':
  143. # bpo-45337: Fix up env_exec_cmd to account for file system redirections.
  144. # Some redirects only apply to CreateFile and not CreateProcess
  145. real_env_exe = os.path.realpath(context.env_exe)
  146. if os.path.normcase(real_env_exe) != os.path.normcase(context.env_exe):
  147. logger.warning('Actual environment location may have moved due to '
  148. 'redirects, links or junctions.\n'
  149. ' Requested location: "%s"\n'
  150. ' Actual location: "%s"',
  151. context.env_exe, real_env_exe)
  152. context.env_exec_cmd = real_env_exe
  153. return context
  154. def create_configuration(self, context):
  155. """
  156. Create a configuration file indicating where the environment's Python
  157. was copied from, and whether the system site-packages should be made
  158. available in the environment.
  159. :param context: The information for the environment creation request
  160. being processed.
  161. """
  162. context.cfg_path = path = os.path.join(context.env_dir, 'pyvenv.cfg')
  163. with open(path, 'w', encoding='utf-8') as f:
  164. f.write('home = %s\n' % context.python_dir)
  165. if self.system_site_packages:
  166. incl = 'true'
  167. else:
  168. incl = 'false'
  169. f.write('include-system-site-packages = %s\n' % incl)
  170. f.write('version = %d.%d.%d\n' % sys.version_info[:3])
  171. if self.prompt is not None:
  172. f.write(f'prompt = {self.prompt!r}\n')
  173. f.write('executable = %s\n' % os.path.realpath(sys.executable))
  174. args = []
  175. nt = os.name == 'nt'
  176. if nt and self.symlinks:
  177. args.append('--symlinks')
  178. if not nt and not self.symlinks:
  179. args.append('--copies')
  180. if not self.with_pip:
  181. args.append('--without-pip')
  182. if self.system_site_packages:
  183. args.append('--system-site-packages')
  184. if self.clear:
  185. args.append('--clear')
  186. if self.upgrade:
  187. args.append('--upgrade')
  188. if self.upgrade_deps:
  189. args.append('--upgrade-deps')
  190. if self.orig_prompt is not None:
  191. args.append(f'--prompt="{self.orig_prompt}"')
  192. args.append(context.env_dir)
  193. args = ' '.join(args)
  194. f.write(f'command = {sys.executable} -m venv {args}\n')
  195. if os.name != 'nt':
  196. def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
  197. """
  198. Try symlinking a file, and if that fails, fall back to copying.
  199. """
  200. force_copy = not self.symlinks
  201. if not force_copy:
  202. try:
  203. if not os.path.islink(dst): # can't link to itself!
  204. if relative_symlinks_ok:
  205. assert os.path.dirname(src) == os.path.dirname(dst)
  206. os.symlink(os.path.basename(src), dst)
  207. else:
  208. os.symlink(src, dst)
  209. except Exception: # may need to use a more specific exception
  210. logger.warning('Unable to symlink %r to %r', src, dst)
  211. force_copy = True
  212. if force_copy:
  213. shutil.copyfile(src, dst)
  214. else:
  215. def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
  216. """
  217. Try symlinking a file, and if that fails, fall back to copying.
  218. """
  219. bad_src = os.path.lexists(src) and not os.path.exists(src)
  220. if self.symlinks and not bad_src and not os.path.islink(dst):
  221. try:
  222. if relative_symlinks_ok:
  223. assert os.path.dirname(src) == os.path.dirname(dst)
  224. os.symlink(os.path.basename(src), dst)
  225. else:
  226. os.symlink(src, dst)
  227. return
  228. except Exception: # may need to use a more specific exception
  229. logger.warning('Unable to symlink %r to %r', src, dst)
  230. # On Windows, we rewrite symlinks to our base python.exe into
  231. # copies of venvlauncher.exe
  232. basename, ext = os.path.splitext(os.path.basename(src))
  233. srcfn = os.path.join(os.path.dirname(__file__),
  234. "scripts",
  235. "nt",
  236. basename + ext)
  237. # Builds or venv's from builds need to remap source file
  238. # locations, as we do not put them into Lib/venv/scripts
  239. if sysconfig.is_python_build() or not os.path.isfile(srcfn):
  240. if basename.endswith('_d'):
  241. ext = '_d' + ext
  242. basename = basename[:-2]
  243. if basename == 'python':
  244. basename = 'venvlauncher'
  245. elif basename == 'pythonw':
  246. basename = 'venvwlauncher'
  247. src = os.path.join(os.path.dirname(src), basename + ext)
  248. else:
  249. src = srcfn
  250. if not os.path.exists(src):
  251. if not bad_src:
  252. logger.warning('Unable to copy %r', src)
  253. return
  254. shutil.copyfile(src, dst)
  255. def setup_python(self, context):
  256. """
  257. Set up a Python executable in the environment.
  258. :param context: The information for the environment creation request
  259. being processed.
  260. """
  261. binpath = context.bin_path
  262. path = context.env_exe
  263. copier = self.symlink_or_copy
  264. dirname = context.python_dir
  265. if os.name != 'nt':
  266. copier(context.executable, path)
  267. if not os.path.islink(path):
  268. os.chmod(path, 0o755)
  269. for suffix in ('python', 'python3', f'python3.{sys.version_info[1]}'):
  270. path = os.path.join(binpath, suffix)
  271. if not os.path.exists(path):
  272. # Issue 18807: make copies if
  273. # symlinks are not wanted
  274. copier(context.env_exe, path, relative_symlinks_ok=True)
  275. if not os.path.islink(path):
  276. os.chmod(path, 0o755)
  277. else:
  278. if self.symlinks:
  279. # For symlinking, we need a complete copy of the root directory
  280. # If symlinks fail, you'll get unnecessary copies of files, but
  281. # we assume that if you've opted into symlinks on Windows then
  282. # you know what you're doing.
  283. suffixes = [
  284. f for f in os.listdir(dirname) if
  285. os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
  286. ]
  287. if sysconfig.is_python_build():
  288. suffixes = [
  289. f for f in suffixes if
  290. os.path.normcase(f).startswith(('python', 'vcruntime'))
  291. ]
  292. else:
  293. suffixes = {'python.exe', 'python_d.exe', 'pythonw.exe', 'pythonw_d.exe'}
  294. base_exe = os.path.basename(context.env_exe)
  295. suffixes.add(base_exe)
  296. for suffix in suffixes:
  297. src = os.path.join(dirname, suffix)
  298. if os.path.lexists(src):
  299. copier(src, os.path.join(binpath, suffix))
  300. if sysconfig.is_python_build():
  301. # copy init.tcl
  302. for root, dirs, files in os.walk(context.python_dir):
  303. if 'init.tcl' in files:
  304. tcldir = os.path.basename(root)
  305. tcldir = os.path.join(context.env_dir, 'Lib', tcldir)
  306. if not os.path.exists(tcldir):
  307. os.makedirs(tcldir)
  308. src = os.path.join(root, 'init.tcl')
  309. dst = os.path.join(tcldir, 'init.tcl')
  310. shutil.copyfile(src, dst)
  311. break
  312. def _call_new_python(self, context, *py_args, **kwargs):
  313. """Executes the newly created Python using safe-ish options"""
  314. # gh-98251: We do not want to just use '-I' because that masks
  315. # legitimate user preferences (such as not writing bytecode). All we
  316. # really need is to ensure that the path variables do not overrule
  317. # normal venv handling.
  318. args = [context.env_exec_cmd, *py_args]
  319. kwargs['env'] = env = os.environ.copy()
  320. env['VIRTUAL_ENV'] = context.env_dir
  321. env.pop('PYTHONHOME', None)
  322. env.pop('PYTHONPATH', None)
  323. kwargs['cwd'] = context.env_dir
  324. kwargs['executable'] = context.env_exec_cmd
  325. subprocess.check_output(args, **kwargs)
  326. def _setup_pip(self, context):
  327. """Installs or upgrades pip in a virtual environment"""
  328. self._call_new_python(context, '-m', 'ensurepip', '--upgrade',
  329. '--default-pip', stderr=subprocess.STDOUT)
  330. def setup_scripts(self, context):
  331. """
  332. Set up scripts into the created environment from a directory.
  333. This method installs the default scripts into the environment
  334. being created. You can prevent the default installation by overriding
  335. this method if you really need to, or if you need to specify
  336. a different location for the scripts to install. By default, the
  337. 'scripts' directory in the venv package is used as the source of
  338. scripts to install.
  339. """
  340. path = os.path.abspath(os.path.dirname(__file__))
  341. path = os.path.join(path, 'scripts')
  342. self.install_scripts(context, path)
  343. def post_setup(self, context):
  344. """
  345. Hook for post-setup modification of the venv. Subclasses may install
  346. additional packages or scripts here, add activation shell scripts, etc.
  347. :param context: The information for the environment creation request
  348. being processed.
  349. """
  350. pass
  351. def replace_variables(self, text, context):
  352. """
  353. Replace variable placeholders in script text with context-specific
  354. variables.
  355. Return the text passed in , but with variables replaced.
  356. :param text: The text in which to replace placeholder variables.
  357. :param context: The information for the environment creation request
  358. being processed.
  359. """
  360. text = text.replace('__VENV_DIR__', context.env_dir)
  361. text = text.replace('__VENV_NAME__', context.env_name)
  362. text = text.replace('__VENV_PROMPT__', context.prompt)
  363. text = text.replace('__VENV_BIN_NAME__', context.bin_name)
  364. text = text.replace('__VENV_PYTHON__', context.env_exe)
  365. return text
  366. def install_scripts(self, context, path):
  367. """
  368. Install scripts into the created environment from a directory.
  369. :param context: The information for the environment creation request
  370. being processed.
  371. :param path: Absolute pathname of a directory containing script.
  372. Scripts in the 'common' subdirectory of this directory,
  373. and those in the directory named for the platform
  374. being run on, are installed in the created environment.
  375. Placeholder variables are replaced with environment-
  376. specific values.
  377. """
  378. binpath = context.bin_path
  379. plen = len(path)
  380. for root, dirs, files in os.walk(path):
  381. if root == path: # at top-level, remove irrelevant dirs
  382. for d in dirs[:]:
  383. if d not in ('common', os.name):
  384. dirs.remove(d)
  385. continue # ignore files in top level
  386. for f in files:
  387. if (os.name == 'nt' and f.startswith('python')
  388. and f.endswith(('.exe', '.pdb'))):
  389. continue
  390. srcfile = os.path.join(root, f)
  391. suffix = root[plen:].split(os.sep)[2:]
  392. if not suffix:
  393. dstdir = binpath
  394. else:
  395. dstdir = os.path.join(binpath, *suffix)
  396. if not os.path.exists(dstdir):
  397. os.makedirs(dstdir)
  398. dstfile = os.path.join(dstdir, f)
  399. with open(srcfile, 'rb') as f:
  400. data = f.read()
  401. if not srcfile.endswith(('.exe', '.pdb')):
  402. try:
  403. data = data.decode('utf-8')
  404. data = self.replace_variables(data, context)
  405. data = data.encode('utf-8')
  406. except UnicodeError as e:
  407. data = None
  408. logger.warning('unable to copy script %r, '
  409. 'may be binary: %s', srcfile, e)
  410. if data is not None:
  411. with open(dstfile, 'wb') as f:
  412. f.write(data)
  413. shutil.copymode(srcfile, dstfile)
  414. def upgrade_dependencies(self, context):
  415. logger.debug(
  416. f'Upgrading {CORE_VENV_DEPS} packages in {context.bin_path}'
  417. )
  418. self._call_new_python(context, '-m', 'pip', 'install', '--upgrade',
  419. *CORE_VENV_DEPS)
  420. def create(env_dir, system_site_packages=False, clear=False,
  421. symlinks=False, with_pip=False, prompt=None, upgrade_deps=False):
  422. """Create a virtual environment in a directory."""
  423. builder = EnvBuilder(system_site_packages=system_site_packages,
  424. clear=clear, symlinks=symlinks, with_pip=with_pip,
  425. prompt=prompt, upgrade_deps=upgrade_deps)
  426. builder.create(env_dir)
  427. def main(args=None):
  428. import argparse
  429. parser = argparse.ArgumentParser(prog=__name__,
  430. description='Creates virtual Python '
  431. 'environments in one or '
  432. 'more target '
  433. 'directories.',
  434. epilog='Once an environment has been '
  435. 'created, you may wish to '
  436. 'activate it, e.g. by '
  437. 'sourcing an activate script '
  438. 'in its bin directory.')
  439. parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
  440. help='A directory to create the environment in.')
  441. parser.add_argument('--system-site-packages', default=False,
  442. action='store_true', dest='system_site',
  443. help='Give the virtual environment access to the '
  444. 'system site-packages dir.')
  445. if os.name == 'nt':
  446. use_symlinks = False
  447. else:
  448. use_symlinks = True
  449. group = parser.add_mutually_exclusive_group()
  450. group.add_argument('--symlinks', default=use_symlinks,
  451. action='store_true', dest='symlinks',
  452. help='Try to use symlinks rather than copies, '
  453. 'when symlinks are not the default for '
  454. 'the platform.')
  455. group.add_argument('--copies', default=not use_symlinks,
  456. action='store_false', dest='symlinks',
  457. help='Try to use copies rather than symlinks, '
  458. 'even when symlinks are the default for '
  459. 'the platform.')
  460. parser.add_argument('--clear', default=False, action='store_true',
  461. dest='clear', help='Delete the contents of the '
  462. 'environment directory if it '
  463. 'already exists, before '
  464. 'environment creation.')
  465. parser.add_argument('--upgrade', default=False, action='store_true',
  466. dest='upgrade', help='Upgrade the environment '
  467. 'directory to use this version '
  468. 'of Python, assuming Python '
  469. 'has been upgraded in-place.')
  470. parser.add_argument('--without-pip', dest='with_pip',
  471. default=True, action='store_false',
  472. help='Skips installing or upgrading pip in the '
  473. 'virtual environment (pip is bootstrapped '
  474. 'by default)')
  475. parser.add_argument('--prompt',
  476. help='Provides an alternative prompt prefix for '
  477. 'this environment.')
  478. parser.add_argument('--upgrade-deps', default=False, action='store_true',
  479. dest='upgrade_deps',
  480. help=f'Upgrade core dependencies ({", ".join(CORE_VENV_DEPS)}) '
  481. 'to the latest version in PyPI')
  482. options = parser.parse_args(args)
  483. if options.upgrade and options.clear:
  484. raise ValueError('you cannot supply --upgrade and --clear together.')
  485. builder = EnvBuilder(system_site_packages=options.system_site,
  486. clear=options.clear,
  487. symlinks=options.symlinks,
  488. upgrade=options.upgrade,
  489. with_pip=options.with_pip,
  490. prompt=options.prompt,
  491. upgrade_deps=options.upgrade_deps)
  492. for d in options.dirs:
  493. builder.create(d)
  494. if __name__ == '__main__':
  495. rc = 1
  496. try:
  497. main()
  498. rc = 0
  499. except Exception as e:
  500. print('Error: %s' % e, file=sys.stderr)
  501. sys.exit(rc)