__init__.py 26 KB

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