__init__.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. if basename.startswith('python'):
  194. scripts = sys.prefix
  195. else:
  196. scripts = os.path.join(os.path.dirname(__file__), "scripts", "nt")
  197. src = os.path.join(scripts, basename + ext)
  198. if not os.path.exists(src):
  199. if not bad_src:
  200. logger.warning('Unable to copy %r', src)
  201. return
  202. shutil.copyfile(src, dst)
  203. def setup_python(self, context):
  204. """
  205. Set up a Python executable in the environment.
  206. :param context: The information for the environment creation request
  207. being processed.
  208. """
  209. binpath = context.bin_path
  210. path = context.env_exe
  211. copier = self.symlink_or_copy
  212. copier(context.executable, path)
  213. dirname = context.python_dir
  214. if os.name != 'nt':
  215. if not os.path.islink(path):
  216. os.chmod(path, 0o755)
  217. for suffix in ('python', 'python3'):
  218. path = os.path.join(binpath, suffix)
  219. if not os.path.exists(path):
  220. # Issue 18807: make copies if
  221. # symlinks are not wanted
  222. copier(context.env_exe, path, relative_symlinks_ok=True)
  223. if not os.path.islink(path):
  224. os.chmod(path, 0o755)
  225. else:
  226. if self.symlinks:
  227. # For symlinking, we need a complete copy of the root directory
  228. # If symlinks fail, you'll get unnecessary copies of files, but
  229. # we assume that if you've opted into symlinks on Windows then
  230. # you know what you're doing.
  231. suffixes = [
  232. f for f in os.listdir(dirname) if
  233. os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
  234. ]
  235. if sysconfig.is_python_build(True):
  236. suffixes = [
  237. f for f in suffixes if
  238. os.path.normcase(f).startswith(('python', 'vcruntime'))
  239. ]
  240. else:
  241. suffixes = ['python.exe', 'python_d.exe', 'pythonw.exe',
  242. 'pythonw_d.exe']
  243. for suffix in suffixes:
  244. src = os.path.join(dirname, suffix)
  245. if os.path.lexists(src):
  246. copier(src, os.path.join(binpath, suffix))
  247. if sysconfig.is_python_build(True):
  248. # copy init.tcl
  249. for root, dirs, files in os.walk(context.python_dir):
  250. if 'init.tcl' in files:
  251. tcldir = os.path.basename(root)
  252. tcldir = os.path.join(context.env_dir, 'Lib', tcldir)
  253. if not os.path.exists(tcldir):
  254. os.makedirs(tcldir)
  255. src = os.path.join(root, 'init.tcl')
  256. dst = os.path.join(tcldir, 'init.tcl')
  257. shutil.copyfile(src, dst)
  258. break
  259. def _setup_pip(self, context):
  260. """Installs or upgrades pip in a virtual environment"""
  261. # We run ensurepip in isolated mode to avoid side effects from
  262. # environment vars, the current directory and anything else
  263. # intended for the global Python environment
  264. cmd = [context.env_exe, '-Im', 'ensurepip', '--upgrade',
  265. '--default-pip']
  266. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  267. def setup_scripts(self, context):
  268. """
  269. Set up scripts into the created environment from a directory.
  270. This method installs the default scripts into the environment
  271. being created. You can prevent the default installation by overriding
  272. this method if you really need to, or if you need to specify
  273. a different location for the scripts to install. By default, the
  274. 'scripts' directory in the venv package is used as the source of
  275. scripts to install.
  276. """
  277. path = os.path.abspath(os.path.dirname(__file__))
  278. path = os.path.join(path, 'scripts')
  279. self.install_scripts(context, path)
  280. def post_setup(self, context):
  281. """
  282. Hook for post-setup modification of the venv. Subclasses may install
  283. additional packages or scripts here, add activation shell scripts, etc.
  284. :param context: The information for the environment creation request
  285. being processed.
  286. """
  287. pass
  288. def replace_variables(self, text, context):
  289. """
  290. Replace variable placeholders in script text with context-specific
  291. variables.
  292. Return the text passed in , but with variables replaced.
  293. :param text: The text in which to replace placeholder variables.
  294. :param context: The information for the environment creation request
  295. being processed.
  296. """
  297. text = text.replace('__VENV_DIR__', context.env_dir)
  298. text = text.replace('__VENV_NAME__', context.env_name)
  299. text = text.replace('__VENV_PROMPT__', context.prompt)
  300. text = text.replace('__VENV_BIN_NAME__', context.bin_name)
  301. text = text.replace('__VENV_PYTHON__', context.env_exe)
  302. return text
  303. def install_scripts(self, context, path):
  304. """
  305. Install scripts into the created environment from a directory.
  306. :param context: The information for the environment creation request
  307. being processed.
  308. :param path: Absolute pathname of a directory containing script.
  309. Scripts in the 'common' subdirectory of this directory,
  310. and those in the directory named for the platform
  311. being run on, are installed in the created environment.
  312. Placeholder variables are replaced with environment-
  313. specific values.
  314. """
  315. binpath = context.bin_path
  316. plen = len(path)
  317. for root, dirs, files in os.walk(path):
  318. if root == path: # at top-level, remove irrelevant dirs
  319. for d in dirs[:]:
  320. if d not in ('common', os.name):
  321. dirs.remove(d)
  322. continue # ignore files in top level
  323. for f in files:
  324. if (os.name == 'nt' and f.startswith('python')
  325. and f.endswith(('.exe', '.pdb'))):
  326. continue
  327. srcfile = os.path.join(root, f)
  328. suffix = root[plen:].split(os.sep)[2:]
  329. if not suffix:
  330. dstdir = binpath
  331. else:
  332. dstdir = os.path.join(binpath, *suffix)
  333. if not os.path.exists(dstdir):
  334. os.makedirs(dstdir)
  335. dstfile = os.path.join(dstdir, f)
  336. with open(srcfile, 'rb') as f:
  337. data = f.read()
  338. if not srcfile.endswith(('.exe', '.pdb')):
  339. try:
  340. data = data.decode('utf-8')
  341. data = self.replace_variables(data, context)
  342. data = data.encode('utf-8')
  343. except UnicodeError as e:
  344. data = None
  345. logger.warning('unable to copy script %r, '
  346. 'may be binary: %s', srcfile, e)
  347. if data is not None:
  348. with open(dstfile, 'wb') as f:
  349. f.write(data)
  350. shutil.copymode(srcfile, dstfile)
  351. def create(env_dir, system_site_packages=False, clear=False,
  352. symlinks=False, with_pip=False, prompt=None):
  353. """Create a virtual environment in a directory."""
  354. builder = EnvBuilder(system_site_packages=system_site_packages,
  355. clear=clear, symlinks=symlinks, with_pip=with_pip,
  356. prompt=prompt)
  357. builder.create(env_dir)
  358. def main(args=None):
  359. compatible = True
  360. if sys.version_info < (3, 3):
  361. compatible = False
  362. elif not hasattr(sys, 'base_prefix'):
  363. compatible = False
  364. if not compatible:
  365. raise ValueError('This script is only for use with Python >= 3.3')
  366. else:
  367. import argparse
  368. parser = argparse.ArgumentParser(prog=__name__,
  369. description='Creates virtual Python '
  370. 'environments in one or '
  371. 'more target '
  372. 'directories.',
  373. epilog='Once an environment has been '
  374. 'created, you may wish to '
  375. 'activate it, e.g. by '
  376. 'sourcing an activate script '
  377. 'in its bin directory.')
  378. parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
  379. help='A directory to create the environment in.')
  380. parser.add_argument('--system-site-packages', default=False,
  381. action='store_true', dest='system_site',
  382. help='Give the virtual environment access to the '
  383. 'system site-packages dir.')
  384. if os.name == 'nt':
  385. use_symlinks = False
  386. else:
  387. use_symlinks = True
  388. group = parser.add_mutually_exclusive_group()
  389. group.add_argument('--symlinks', default=use_symlinks,
  390. action='store_true', dest='symlinks',
  391. help='Try to use symlinks rather than copies, '
  392. 'when symlinks are not the default for '
  393. 'the platform.')
  394. group.add_argument('--copies', default=not use_symlinks,
  395. action='store_false', dest='symlinks',
  396. help='Try to use copies rather than symlinks, '
  397. 'even when symlinks are the default for '
  398. 'the platform.')
  399. parser.add_argument('--clear', default=False, action='store_true',
  400. dest='clear', help='Delete the contents of the '
  401. 'environment directory if it '
  402. 'already exists, before '
  403. 'environment creation.')
  404. parser.add_argument('--upgrade', default=False, action='store_true',
  405. dest='upgrade', help='Upgrade the environment '
  406. 'directory to use this version '
  407. 'of Python, assuming Python '
  408. 'has been upgraded in-place.')
  409. parser.add_argument('--without-pip', dest='with_pip',
  410. default=True, action='store_false',
  411. help='Skips installing or upgrading pip in the '
  412. 'virtual environment (pip is bootstrapped '
  413. 'by default)')
  414. parser.add_argument('--prompt',
  415. help='Provides an alternative prompt prefix for '
  416. 'this environment.')
  417. options = parser.parse_args(args)
  418. if options.upgrade and options.clear:
  419. raise ValueError('you cannot supply --upgrade and --clear together.')
  420. builder = EnvBuilder(system_site_packages=options.system_site,
  421. clear=options.clear,
  422. symlinks=options.symlinks,
  423. upgrade=options.upgrade,
  424. with_pip=options.with_pip,
  425. prompt=options.prompt)
  426. for d in options.dirs:
  427. builder.create(d)
  428. if __name__ == '__main__':
  429. rc = 1
  430. try:
  431. main()
  432. rc = 0
  433. except Exception as e:
  434. print('Error: %s' % e, file=sys.stderr)
  435. sys.exit(rc)