__init__.py 21 KB

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