__init__.py 23 KB

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