virtualenv/web/virtualenv.py
changeset 308 23f5e267cd1e
parent 274 e34d988f37a7
equal deleted inserted replaced
307:696f02ba0853 308:23f5e267cd1e
     1 #!/usr/bin/env python
     1 #!/usr/bin/env python
     2 """Create a "virtual" Python installation
     2 """Create a "virtual" Python installation"""
     3 """
     3 
     4 
     4 import os
     5 __version__ = "13.1.2"
     5 import sys
     6 virtualenv_version = __version__  # legacy
     6 
       
     7 # If we are running in a new interpreter to create a virtualenv,
       
     8 # we do NOT want paths from our existing location interfering with anything,
       
     9 # So we remove this file's directory from sys.path - most likely to be
       
    10 # the previous interpreter's site-packages. Solves #705, #763, #779
       
    11 if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
       
    12     for path in sys.path[:]:
       
    13         if os.path.realpath(os.path.dirname(__file__)) == os.path.realpath(path):
       
    14             sys.path.remove(path)
     7 
    15 
     8 import base64
    16 import base64
     9 import sys
       
    10 import os
       
    11 import codecs
    17 import codecs
    12 import optparse
    18 import optparse
    13 import re
    19 import re
    14 import shutil
    20 import shutil
    15 import logging
    21 import logging
    16 import tempfile
       
    17 import zlib
    22 import zlib
    18 import errno
    23 import errno
    19 import glob
    24 import glob
    20 import distutils.sysconfig
    25 import distutils.sysconfig
    21 from distutils.util import strtobool
       
    22 import struct
    26 import struct
    23 import subprocess
    27 import subprocess
    24 import tarfile
    28 import pkgutil
       
    29 import tempfile
       
    30 import textwrap
       
    31 from distutils.util import strtobool
       
    32 from os.path import join
       
    33 
       
    34 try:
       
    35     import ConfigParser
       
    36 except ImportError:
       
    37     import configparser as ConfigParser
       
    38 
       
    39 __version__ = "15.0.0"
       
    40 virtualenv_version = __version__  # legacy
    25 
    41 
    26 if sys.version_info < (2, 6):
    42 if sys.version_info < (2, 6):
    27     print('ERROR: %s' % sys.exc_info()[1])
    43     print('ERROR: %s' % sys.exc_info()[1])
    28     print('ERROR: this script requires Python 2.6 or greater.')
    44     print('ERROR: this script requires Python 2.6 or greater.')
    29     sys.exit(101)
    45     sys.exit(101)
    31 try:
    47 try:
    32     basestring
    48     basestring
    33 except NameError:
    49 except NameError:
    34     basestring = str
    50     basestring = str
    35 
    51 
    36 try:
       
    37     import ConfigParser
       
    38 except ImportError:
       
    39     import configparser as ConfigParser
       
    40 
       
    41 join = os.path.join
       
    42 py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
    52 py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
    43 
    53 
    44 is_jython = sys.platform.startswith('java')
    54 is_jython = sys.platform.startswith('java')
    45 is_pypy = hasattr(sys, 'pypy_version_info')
    55 is_pypy = hasattr(sys, 'pypy_version_info')
    46 is_win = (sys.platform == 'win32')
    56 is_win = (sys.platform == 'win32')
    74         import _winreg as winreg
    84         import _winreg as winreg
    75 
    85 
    76     def get_installed_pythons():
    86     def get_installed_pythons():
    77         try:
    87         try:
    78             python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,
    88             python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,
    79                     "Software\\Python\\PythonCore")
    89                                            "Software\\Python\\PythonCore")
    80         except WindowsError:
    90         except WindowsError:
    81             # No registered Python installations
    91             # No registered Python installations
    82             return {}
    92             return {}
    83         i = 0
    93         i = 0
    84         versions = []
    94         versions = []
   121     if minver >= 7:
   131     if minver >= 7:
   122         REQUIRED_MODULES.extend(['_weakrefset'])
   132         REQUIRED_MODULES.extend(['_weakrefset'])
   123 elif majver == 3:
   133 elif majver == 3:
   124     # Some extra modules are needed for Python 3, but different ones
   134     # Some extra modules are needed for Python 3, but different ones
   125     # for different versions.
   135     # for different versions.
   126     REQUIRED_MODULES.extend(['_abcoll', 'warnings', 'linecache', 'abc', 'io',
   136     REQUIRED_MODULES.extend([
   127                              '_weakrefset', 'copyreg', 'tempfile', 'random',
   137     	'_abcoll', 'warnings', 'linecache', 'abc', 'io', '_weakrefset',
   128                              '__future__', 'collections', 'keyword', 'tarfile',
   138     	'copyreg', 'tempfile', 'random', '__future__', 'collections',
   129                              'shutil', 'struct', 'copy', 'tokenize', 'token',
   139     	'keyword', 'tarfile', 'shutil', 'struct', 'copy', 'tokenize',
   130                              'functools', 'heapq', 'bisect', 'weakref',
   140     	'token', 'functools', 'heapq', 'bisect', 'weakref', 'reprlib'
   131                              'reprlib'])
   141     ])
   132     if minver >= 2:
   142     if minver >= 2:
   133         REQUIRED_FILES[-1] = 'config-%s' % majver
   143         REQUIRED_FILES[-1] = 'config-%s' % majver
   134     if minver >= 3:
   144     if minver >= 3:
   135         import sysconfig
   145         import sysconfig
   136         platdir = sysconfig.get_config_var('PLATDIR')
   146         platdir = sysconfig.get_config_var('PLATDIR')
   137         REQUIRED_FILES.append(platdir)
   147         REQUIRED_FILES.append(platdir)
   138         # The whole list of 3.3 modules is reproduced below - the current
       
   139         # uncommented ones are required for 3.3 as of now, but more may be
       
   140         # added as 3.3 development continues.
       
   141         REQUIRED_MODULES.extend([
   148         REQUIRED_MODULES.extend([
   142             #"aifc",
   149         	'base64', '_dummy_thread', 'hashlib', 'hmac',
   143             #"antigravity",
   150         	'imp', 'importlib', 'rlcompleter'
   144             #"argparse",
       
   145             #"ast",
       
   146             #"asynchat",
       
   147             #"asyncore",
       
   148             "base64",
       
   149             #"bdb",
       
   150             #"binhex",
       
   151             #"bisect",
       
   152             #"calendar",
       
   153             #"cgi",
       
   154             #"cgitb",
       
   155             #"chunk",
       
   156             #"cmd",
       
   157             #"codeop",
       
   158             #"code",
       
   159             #"colorsys",
       
   160             #"_compat_pickle",
       
   161             #"compileall",
       
   162             #"concurrent",
       
   163             #"configparser",
       
   164             #"contextlib",
       
   165             #"cProfile",
       
   166             #"crypt",
       
   167             #"csv",
       
   168             #"ctypes",
       
   169             #"curses",
       
   170             #"datetime",
       
   171             #"dbm",
       
   172             #"decimal",
       
   173             #"difflib",
       
   174             #"dis",
       
   175             #"doctest",
       
   176             #"dummy_threading",
       
   177             "_dummy_thread",
       
   178             #"email",
       
   179             #"filecmp",
       
   180             #"fileinput",
       
   181             #"formatter",
       
   182             #"fractions",
       
   183             #"ftplib",
       
   184             #"functools",
       
   185             #"getopt",
       
   186             #"getpass",
       
   187             #"gettext",
       
   188             #"glob",
       
   189             #"gzip",
       
   190             "hashlib",
       
   191             #"heapq",
       
   192             "hmac",
       
   193             #"html",
       
   194             #"http",
       
   195             #"idlelib",
       
   196             #"imaplib",
       
   197             #"imghdr",
       
   198             "imp",
       
   199             "importlib",
       
   200             #"inspect",
       
   201             #"json",
       
   202             #"lib2to3",
       
   203             #"logging",
       
   204             #"macpath",
       
   205             #"macurl2path",
       
   206             #"mailbox",
       
   207             #"mailcap",
       
   208             #"_markupbase",
       
   209             #"mimetypes",
       
   210             #"modulefinder",
       
   211             #"multiprocessing",
       
   212             #"netrc",
       
   213             #"nntplib",
       
   214             #"nturl2path",
       
   215             #"numbers",
       
   216             #"opcode",
       
   217             #"optparse",
       
   218             #"os2emxpath",
       
   219             #"pdb",
       
   220             #"pickle",
       
   221             #"pickletools",
       
   222             #"pipes",
       
   223             #"pkgutil",
       
   224             #"platform",
       
   225             #"plat-linux2",
       
   226             #"plistlib",
       
   227             #"poplib",
       
   228             #"pprint",
       
   229             #"profile",
       
   230             #"pstats",
       
   231             #"pty",
       
   232             #"pyclbr",
       
   233             #"py_compile",
       
   234             #"pydoc_data",
       
   235             #"pydoc",
       
   236             #"_pyio",
       
   237             #"queue",
       
   238             #"quopri",
       
   239             #"reprlib",
       
   240             "rlcompleter",
       
   241             #"runpy",
       
   242             #"sched",
       
   243             #"shelve",
       
   244             #"shlex",
       
   245             #"smtpd",
       
   246             #"smtplib",
       
   247             #"sndhdr",
       
   248             #"socket",
       
   249             #"socketserver",
       
   250             #"sqlite3",
       
   251             #"ssl",
       
   252             #"stringprep",
       
   253             #"string",
       
   254             #"_strptime",
       
   255             #"subprocess",
       
   256             #"sunau",
       
   257             #"symbol",
       
   258             #"symtable",
       
   259             #"sysconfig",
       
   260             #"tabnanny",
       
   261             #"telnetlib",
       
   262             #"test",
       
   263             #"textwrap",
       
   264             #"this",
       
   265             #"_threading_local",
       
   266             #"threading",
       
   267             #"timeit",
       
   268             #"tkinter",
       
   269             #"tokenize",
       
   270             #"token",
       
   271             #"traceback",
       
   272             #"trace",
       
   273             #"tty",
       
   274             #"turtledemo",
       
   275             #"turtle",
       
   276             #"unittest",
       
   277             #"urllib",
       
   278             #"uuid",
       
   279             #"uu",
       
   280             #"wave",
       
   281             #"weakref",
       
   282             #"webbrowser",
       
   283             #"wsgiref",
       
   284             #"xdrlib",
       
   285             #"xml",
       
   286             #"xmlrpc",
       
   287             #"zipfile",
       
   288         ])
   151         ])
   289     if minver >= 4:
   152     if minver >= 4:
   290         REQUIRED_MODULES.extend([
   153         REQUIRED_MODULES.extend([
   291             'operator',
   154             'operator',
   292             '_collections_abc',
   155             '_collections_abc',
   296 if is_pypy:
   159 if is_pypy:
   297     # these are needed to correctly display the exceptions that may happen
   160     # these are needed to correctly display the exceptions that may happen
   298     # during the bootstrap
   161     # during the bootstrap
   299     REQUIRED_MODULES.extend(['traceback', 'linecache'])
   162     REQUIRED_MODULES.extend(['traceback', 'linecache'])
   300 
   163 
       
   164 
   301 class Logger(object):
   165 class Logger(object):
   302 
   166 
   303     """
   167     """
   304     Logging object for use in command-line script.  Allows ranges of
   168     Logging object for use in command-line script.  Allows ranges of
   305     levels, to avoid some redundancy of displayed information.
   169     levels, to avoid some redundancy of displayed information.
   320         self.in_progress = None
   184         self.in_progress = None
   321         self.in_progress_hanging = False
   185         self.in_progress_hanging = False
   322 
   186 
   323     def debug(self, msg, *args, **kw):
   187     def debug(self, msg, *args, **kw):
   324         self.log(self.DEBUG, msg, *args, **kw)
   188         self.log(self.DEBUG, msg, *args, **kw)
       
   189 
   325     def info(self, msg, *args, **kw):
   190     def info(self, msg, *args, **kw):
   326         self.log(self.INFO, msg, *args, **kw)
   191         self.log(self.INFO, msg, *args, **kw)
       
   192 
   327     def notify(self, msg, *args, **kw):
   193     def notify(self, msg, *args, **kw):
   328         self.log(self.NOTIFY, msg, *args, **kw)
   194         self.log(self.NOTIFY, msg, *args, **kw)
       
   195 
   329     def warn(self, msg, *args, **kw):
   196     def warn(self, msg, *args, **kw):
   330         self.log(self.WARN, msg, *args, **kw)
   197         self.log(self.WARN, msg, *args, **kw)
       
   198 
   331     def error(self, msg, *args, **kw):
   199     def error(self, msg, *args, **kw):
   332         self.log(self.ERROR, msg, *args, **kw)
   200         self.log(self.ERROR, msg, *args, **kw)
       
   201 
   333     def fatal(self, msg, *args, **kw):
   202     def fatal(self, msg, *args, **kw):
   334         self.log(self.FATAL, msg, *args, **kw)
   203         self.log(self.FATAL, msg, *args, **kw)
       
   204 
   335     def log(self, level, msg, *args, **kw):
   205     def log(self, level, msg, *args, **kw):
   336         if args:
   206         if args:
   337             if kw:
   207             if kw:
   338                 raise TypeError(
   208                 raise TypeError(
   339                     "You may give positional or keyword arguments, not both")
   209                     "You may give positional or keyword arguments, not both")
   482         copyfileordir(src, dest, symlink)
   352         copyfileordir(src, dest, symlink)
   483 
   353 
   484 def writefile(dest, content, overwrite=True):
   354 def writefile(dest, content, overwrite=True):
   485     if not os.path.exists(dest):
   355     if not os.path.exists(dest):
   486         logger.info('Writing %s', dest)
   356         logger.info('Writing %s', dest)
   487         f = open(dest, 'wb')
   357         with open(dest, 'wb') as f:
   488         f.write(content.encode('utf-8'))
   358             f.write(content.encode('utf-8'))
   489         f.close()
       
   490         return
   359         return
   491     else:
   360     else:
   492         f = open(dest, 'rb')
   361         with open(dest, 'rb') as f:
   493         c = f.read()
   362             c = f.read()
   494         f.close()
       
   495         if c != content.encode("utf-8"):
   363         if c != content.encode("utf-8"):
   496             if not overwrite:
   364             if not overwrite:
   497                 logger.notify('File %s exists with different content; not overwriting', dest)
   365                 logger.notify('File %s exists with different content; not overwriting', dest)
   498                 return
   366                 return
   499             logger.notify('Overwriting %s with new content', dest)
   367             logger.notify('Overwriting %s with new content', dest)
   500             f = open(dest, 'wb')
   368             with open(dest, 'wb') as f:
   501             f.write(content.encode('utf-8'))
   369                 f.write(content.encode('utf-8'))
   502             f.close()
       
   503         else:
   370         else:
   504             logger.info('Content %s already in place', dest)
   371             logger.info('Content %s already in place', dest)
   505 
   372 
   506 def rmtree(dir):
   373 def rmtree(dir):
   507     if os.path.exists(dir):
   374     if os.path.exists(dir):
   712 
   579 
   713     parser.add_option(
   580     parser.add_option(
   714         '--no-setuptools',
   581         '--no-setuptools',
   715         dest='no_setuptools',
   582         dest='no_setuptools',
   716         action='store_true',
   583         action='store_true',
   717         help='Do not install setuptools (or pip) in the new virtualenv.')
   584         help='Do not install setuptools in the new virtualenv.')
   718 
   585 
   719     parser.add_option(
   586     parser.add_option(
   720         '--no-pip',
   587         '--no-pip',
   721         dest='no_pip',
   588         dest='no_pip',
   722         action='store_true',
   589         action='store_true',
   737         default=default_search_dirs,
   604         default=default_search_dirs,
   738         help="Directory to look for setuptools/pip distributions in. "
   605         help="Directory to look for setuptools/pip distributions in. "
   739               "This option can be used multiple times.")
   606               "This option can be used multiple times.")
   740 
   607 
   741     parser.add_option(
   608     parser.add_option(
       
   609         "--download",
       
   610         dest="download",
       
   611         default=True,
       
   612         action="store_true",
       
   613         help="Download preinstalled packages from PyPI.",
       
   614     )
       
   615 
       
   616     parser.add_option(
       
   617         "--no-download",
   742         '--never-download',
   618         '--never-download',
   743         dest="never_download",
   619         dest="download",
   744         action="store_true",
   620         action="store_false",
   745         default=True,
   621         help="Do not download preinstalled packages from PyPI.",
   746         help="DEPRECATED. Retained only for backward compatibility. This option has no effect. "
   622     )
   747               "Virtualenv never downloads pip or setuptools.")
       
   748 
   623 
   749     parser.add_option(
   624     parser.add_option(
   750         '--prompt',
   625         '--prompt',
   751         dest='prompt',
   626         dest='prompt',
   752         help='Provides an alternative prompt prefix for this environment.')
   627         help='Provides an alternative prompt prefix for this environment.')
   813 
   688 
   814     if options.relocatable:
   689     if options.relocatable:
   815         make_environment_relocatable(home_dir)
   690         make_environment_relocatable(home_dir)
   816         return
   691         return
   817 
   692 
   818     if not options.never_download:
       
   819         logger.warn('The --never-download option is for backward compatibility only.')
       
   820         logger.warn('Setting it to false is no longer supported, and will be ignored.')
       
   821 
       
   822     create_environment(home_dir,
   693     create_environment(home_dir,
   823                        site_packages=options.system_site_packages,
   694                        site_packages=options.system_site_packages,
   824                        clear=options.clear,
   695                        clear=options.clear,
   825                        unzip_setuptools=options.unzip_setuptools,
   696                        unzip_setuptools=options.unzip_setuptools,
   826                        prompt=options.prompt,
   697                        prompt=options.prompt,
   827                        search_dirs=options.search_dirs,
   698                        search_dirs=options.search_dirs,
   828                        never_download=True,
   699                        download=options.download,
   829                        no_setuptools=options.no_setuptools,
   700                        no_setuptools=options.no_setuptools,
   830                        no_pip=options.no_pip,
   701                        no_pip=options.no_pip,
   831                        no_wheel=options.no_wheel,
   702                        no_wheel=options.no_wheel,
   832                        symlink=options.symlink)
   703                        symlink=options.symlink)
   833     if 'after_install' in globals():
   704     if 'after_install' in globals():
   834         after_install(options, home_dir)
   705         after_install(options, home_dir)
   835 
   706 
   836 def call_subprocess(cmd, show_stdout=True,
   707 def call_subprocess(cmd, show_stdout=True,
   837                     filter_stdout=None, cwd=None,
   708                     filter_stdout=None, cwd=None,
   838                     raise_on_returncode=True, extra_env=None,
   709                     raise_on_returncode=True, extra_env=None,
   839                     remove_from_env=None):
   710                     remove_from_env=None, stdin=None):
   840     cmd_parts = []
   711     cmd_parts = []
   841     for part in cmd:
   712     for part in cmd:
   842         if len(part) > 45:
   713         if len(part) > 45:
   843             part = part[:20]+"..."+part[-20:]
   714             part = part[:20]+"..."+part[-20:]
   844         if ' ' in part or '\n' in part or '"' in part or "'" in part:
   715         if ' ' in part or '\n' in part or '"' in part or "'" in part:
   864                 env.pop(varname, None)
   735                 env.pop(varname, None)
   865     else:
   736     else:
   866         env = None
   737         env = None
   867     try:
   738     try:
   868         proc = subprocess.Popen(
   739         proc = subprocess.Popen(
   869             cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
   740             cmd, stderr=subprocess.STDOUT,
       
   741             stdin=None if stdin is None else subprocess.PIPE,
       
   742             stdout=stdout,
   870             cwd=cwd, env=env)
   743             cwd=cwd, env=env)
   871     except Exception:
   744     except Exception:
   872         e = sys.exc_info()[1]
   745         e = sys.exc_info()[1]
   873         logger.fatal(
   746         logger.fatal(
   874             "Error %s while executing command %s" % (e, cmd_desc))
   747             "Error %s while executing command %s" % (e, cmd_desc))
   875         raise
   748         raise
   876     all_output = []
   749     all_output = []
   877     if stdout is not None:
   750     if stdout is not None:
       
   751         if stdin is not None:
       
   752             proc.stdin.write(stdin)
       
   753             proc.stdin.close()
       
   754 
   878         stdout = proc.stdout
   755         stdout = proc.stdout
   879         encoding = sys.getdefaultencoding()
   756         encoding = sys.getdefaultencoding()
   880         fs_encoding = sys.getfilesystemencoding()
   757         fs_encoding = sys.getfilesystemencoding()
   881         while 1:
   758         while 1:
   882             line = stdout.readline()
   759             line = stdout.readline()
   896                 if not logger.stdout_level_matches(level):
   773                 if not logger.stdout_level_matches(level):
   897                     logger.show_progress()
   774                     logger.show_progress()
   898             else:
   775             else:
   899                 logger.info(line)
   776                 logger.info(line)
   900     else:
   777     else:
   901         proc.communicate()
   778         proc.communicate(stdin)
   902     proc.wait()
   779     proc.wait()
   903     if proc.returncode:
   780     if proc.returncode:
   904         if raise_on_returncode:
   781         if raise_on_returncode:
   905             if all_output:
   782             if all_output:
   906                 logger.notify('Complete output from command %s:' % cmd_desc)
   783                 logger.notify('Complete output from command %s:' % cmd_desc)
   942             # We're out of luck, so quit with a suitable error
   819             # We're out of luck, so quit with a suitable error
   943             logger.fatal('Cannot find a wheel for %s' % (project,))
   820             logger.fatal('Cannot find a wheel for %s' % (project,))
   944 
   821 
   945     return wheels
   822     return wheels
   946 
   823 
   947 def install_wheel(project_names, py_executable, search_dirs=None):
   824 def install_wheel(project_names, py_executable, search_dirs=None,
       
   825                   download=False):
   948     if search_dirs is None:
   826     if search_dirs is None:
   949         search_dirs = file_search_dirs()
   827         search_dirs = file_search_dirs()
   950 
   828 
   951     wheels = find_wheels(['setuptools', 'pip'], search_dirs)
   829     wheels = find_wheels(['setuptools', 'pip'], search_dirs)
   952     pythonpath = os.pathsep.join(wheels)
   830     pythonpath = os.pathsep.join(wheels)
   953     findlinks = ' '.join(search_dirs)
   831 
   954 
   832     # PIP_FIND_LINKS uses space as the path separator and thus cannot have paths
   955     cmd = [
   833     # with spaces in them. Convert any of those to local file:// URL form.
   956         py_executable, '-c',
   834     try:
   957         'import sys, pip; sys.exit(pip.main(["install", "--ignore-installed"] + sys.argv[1:]))',
   835         from urlparse import urljoin
   958     ] + project_names
   836         from urllib import pathname2url
       
   837     except ImportError:
       
   838         from urllib.parse import urljoin
       
   839         from urllib.request import pathname2url
       
   840     def space_path2url(p):
       
   841         if ' ' not in p:
       
   842             return p
       
   843         return urljoin('file:', pathname2url(os.path.abspath(p)))
       
   844     findlinks = ' '.join(space_path2url(d) for d in search_dirs)
       
   845 
       
   846     SCRIPT = textwrap.dedent("""
       
   847         import sys
       
   848         import pkgutil
       
   849         import tempfile
       
   850         import os
       
   851 
       
   852         import pip
       
   853 
       
   854         cert_data = pkgutil.get_data("pip._vendor.requests", "cacert.pem")
       
   855         if cert_data is not None:
       
   856             cert_file = tempfile.NamedTemporaryFile(delete=False)
       
   857             cert_file.write(cert_data)
       
   858             cert_file.close()
       
   859         else:
       
   860             cert_file = None
       
   861 
       
   862         try:
       
   863             args = ["install", "--ignore-installed"]
       
   864             if cert_file is not None:
       
   865                 args += ["--cert", cert_file.name]
       
   866             args += sys.argv[1:]
       
   867 
       
   868             sys.exit(pip.main(args))
       
   869         finally:
       
   870             if cert_file is not None:
       
   871                 os.remove(cert_file.name)
       
   872     """).encode("utf8")
       
   873 
       
   874     cmd = [py_executable, '-'] + project_names
   959     logger.start_progress('Installing %s...' % (', '.join(project_names)))
   875     logger.start_progress('Installing %s...' % (', '.join(project_names)))
   960     logger.indent += 2
   876     logger.indent += 2
       
   877 
       
   878     env = {
       
   879         "PYTHONPATH": pythonpath,
       
   880         "JYTHONPATH": pythonpath,  # for Jython < 3.x
       
   881         "PIP_FIND_LINKS": findlinks,
       
   882         "PIP_USE_WHEEL": "1",
       
   883         "PIP_ONLY_BINARY": ":all:",
       
   884         "PIP_PRE": "1",
       
   885         "PIP_USER": "0",
       
   886     }
       
   887 
       
   888     if not download:
       
   889         env["PIP_NO_INDEX"] = "1"
       
   890 
   961     try:
   891     try:
   962         call_subprocess(cmd, show_stdout=False,
   892         call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
   963             extra_env = {
       
   964                 'PYTHONPATH': pythonpath,
       
   965                 'JYTHONPATH': pythonpath,  # for Jython < 3.x
       
   966                 'PIP_FIND_LINKS': findlinks,
       
   967                 'PIP_USE_WHEEL': '1',
       
   968                 'PIP_PRE': '1',
       
   969                 'PIP_NO_INDEX': '1'
       
   970             }
       
   971         )
       
   972     finally:
   893     finally:
   973         logger.indent -= 2
   894         logger.indent -= 2
   974         logger.end_progress()
   895         logger.end_progress()
   975 
   896 
       
   897 
   976 def create_environment(home_dir, site_packages=False, clear=False,
   898 def create_environment(home_dir, site_packages=False, clear=False,
   977                        unzip_setuptools=False,
   899                        unzip_setuptools=False,
   978                        prompt=None, search_dirs=None, never_download=False,
   900                        prompt=None, search_dirs=None, download=False,
   979                        no_setuptools=False, no_pip=False, no_wheel=False,
   901                        no_setuptools=False, no_pip=False, no_wheel=False,
   980                        symlink=True):
   902                        symlink=True):
   981     """
   903     """
   982     Creates a new environment in ``home_dir``.
   904     Creates a new environment in ``home_dir``.
   983 
   905 
   993         home_dir, lib_dir, inc_dir, bin_dir,
   915         home_dir, lib_dir, inc_dir, bin_dir,
   994         site_packages=site_packages, clear=clear, symlink=symlink))
   916         site_packages=site_packages, clear=clear, symlink=symlink))
   995 
   917 
   996     install_distutils(home_dir)
   918     install_distutils(home_dir)
   997 
   919 
       
   920     to_install = []
       
   921 
   998     if not no_setuptools:
   922     if not no_setuptools:
   999         to_install = ['setuptools']
   923         to_install.append('setuptools')
  1000         if not no_pip:
   924 
  1001             to_install.append('pip')
   925     if not no_pip:
  1002         if not no_wheel:
   926         to_install.append('pip')
  1003             to_install.append('wheel')
   927 
  1004         install_wheel(to_install, py_executable, search_dirs)
   928     if not no_wheel:
       
   929         to_install.append('wheel')
       
   930 
       
   931     if to_install:
       
   932         install_wheel(
       
   933             to_install,
       
   934             py_executable,
       
   935             search_dirs,
       
   936             download=download,
       
   937         )
  1005 
   938 
  1006     install_activate(home_dir, bin_dir, prompt)
   939     install_activate(home_dir, bin_dir, prompt)
       
   940 
       
   941     install_python_config(home_dir, bin_dir, prompt)
  1007 
   942 
  1008 def is_executable_file(fpath):
   943 def is_executable_file(fpath):
  1009     return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
   944     return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  1010 
   945 
  1011 def path_locations(home_dir):
   946 def path_locations(home_dir):
  1012     """Return the path locations for the environment (where libraries are,
   947     """Return the path locations for the environment (where libraries are,
  1013     where scripts go, etc)"""
   948     where scripts go, etc)"""
       
   949     home_dir = os.path.abspath(home_dir)
  1014     # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
   950     # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
  1015     # prefix arg is broken: http://bugs.python.org/issue3386
   951     # prefix arg is broken: http://bugs.python.org/issue3386
  1016     if is_win:
   952     if is_win:
  1017         # Windows has lots of problems with executables with spaces in
   953         # Windows has lots of problems with executables with spaces in
  1018         # the name; this function will remove them (using the ~1
   954         # the name; this function will remove them (using the ~1
  1045         lib_dir = home_dir
   981         lib_dir = home_dir
  1046         inc_dir = join(home_dir, 'include')
   982         inc_dir = join(home_dir, 'include')
  1047         bin_dir = join(home_dir, 'bin')
   983         bin_dir = join(home_dir, 'bin')
  1048     elif not is_win:
   984     elif not is_win:
  1049         lib_dir = join(home_dir, 'lib', py_version)
   985         lib_dir = join(home_dir, 'lib', py_version)
  1050         multiarch_exec = '/usr/bin/multiarch-platform'
   986         inc_dir = join(home_dir, 'include', py_version + abiflags)
  1051         if is_executable_file(multiarch_exec):
       
  1052             # In Mageia (2) and Mandriva distros the include dir must be like:
       
  1053             # virtualenv/include/multiarch-x86_64-linux/python2.7
       
  1054             # instead of being virtualenv/include/python2.7
       
  1055             p = subprocess.Popen(multiarch_exec, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
       
  1056             stdout, stderr = p.communicate()
       
  1057             # stdout.strip is needed to remove newline character
       
  1058             inc_dir = join(home_dir, 'include', stdout.strip(), py_version + abiflags)
       
  1059         else:
       
  1060             inc_dir = join(home_dir, 'include', py_version + abiflags)
       
  1061         bin_dir = join(home_dir, 'bin')
   987         bin_dir = join(home_dir, 'bin')
  1062     return home_dir, lib_dir, inc_dir, bin_dir
   988     return home_dir, lib_dir, inc_dir, bin_dir
  1063 
   989 
  1064 
   990 
  1065 def change_prefix(filename, dst_prefix):
   991 def change_prefix(filename, dst_prefix):
  1082     prefixes = list(map(os.path.expanduser, prefixes))
  1008     prefixes = list(map(os.path.expanduser, prefixes))
  1083     prefixes = list(map(os.path.abspath, prefixes))
  1009     prefixes = list(map(os.path.abspath, prefixes))
  1084     # Check longer prefixes first so we don't split in the middle of a filename
  1010     # Check longer prefixes first so we don't split in the middle of a filename
  1085     prefixes = sorted(prefixes, key=len, reverse=True)
  1011     prefixes = sorted(prefixes, key=len, reverse=True)
  1086     filename = os.path.abspath(filename)
  1012     filename = os.path.abspath(filename)
       
  1013     # On Windows, make sure drive letter is uppercase
       
  1014     if is_win and filename[0] in 'abcdefghijklmnopqrstuvwxyz':
       
  1015         filename = filename[0].upper() + filename[1:]
       
  1016     for i, prefix in enumerate(prefixes):
       
  1017         if is_win and prefix[0] in 'abcdefghijklmnopqrstuvwxyz':
       
  1018             prefixes[i] = prefix[0].upper() + prefix[1:]
  1087     for src_prefix in prefixes:
  1019     for src_prefix in prefixes:
  1088         if filename.startswith(src_prefix):
  1020         if filename.startswith(src_prefix):
  1089             _, relpath = filename.split(src_prefix, 1)
  1021             _, relpath = filename.split(src_prefix, 1)
  1090             if src_prefix != os.sep: # sys.prefix == "/"
  1022             if src_prefix != os.sep: # sys.prefix == "/"
  1091                 assert relpath[0] == os.sep
  1023                 assert relpath[0] == os.sep
  1094     assert False, "Filename %s does not start with any of these prefixes: %s" % \
  1026     assert False, "Filename %s does not start with any of these prefixes: %s" % \
  1095         (filename, prefixes)
  1027         (filename, prefixes)
  1096 
  1028 
  1097 def copy_required_modules(dst_prefix, symlink):
  1029 def copy_required_modules(dst_prefix, symlink):
  1098     import imp
  1030     import imp
  1099     # If we are running under -p, we need to remove the current
  1031 
  1100     # directory from sys.path temporarily here, so that we
  1032     for modname in REQUIRED_MODULES:
  1101     # definitely get the modules from the site directory of
  1033         if modname in sys.builtin_module_names:
  1102     # the interpreter we are running under, not the one
  1034             logger.info("Ignoring built-in bootstrap module: %s" % modname)
  1103     # virtualenv.py is installed under (which might lead to py2/py3
  1035             continue
  1104     # incompatibility issues)
  1036         try:
  1105     _prev_sys_path = sys.path
  1037             f, filename, _ = imp.find_module(modname)
  1106     if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
  1038         except ImportError:
  1107         sys.path = sys.path[1:]
  1039             logger.info("Cannot import bootstrap module: %s" % modname)
  1108     try:
  1040         else:
  1109         for modname in REQUIRED_MODULES:
  1041             if f is not None:
  1110             if modname in sys.builtin_module_names:
  1042                 f.close()
  1111                 logger.info("Ignoring built-in bootstrap module: %s" % modname)
  1043             # special-case custom readline.so on OS X, but not for pypy:
  1112                 continue
  1044             if modname == 'readline' and sys.platform == 'darwin' and not (
  1113             try:
  1045                     is_pypy or filename.endswith(join('lib-dynload', 'readline.so'))):
  1114                 f, filename, _ = imp.find_module(modname)
  1046                 dst_filename = join(dst_prefix, 'lib', 'python%s' % sys.version[:3], 'readline.so')
  1115             except ImportError:
  1047             elif modname == 'readline' and sys.platform == 'win32':
  1116                 logger.info("Cannot import bootstrap module: %s" % modname)
  1048                 # special-case for Windows, where readline is not a
       
  1049                 # standard module, though it may have been installed in
       
  1050                 # site-packages by a third-party package
       
  1051                 pass
  1117             else:
  1052             else:
  1118                 if f is not None:
  1053                 dst_filename = change_prefix(filename, dst_prefix)
  1119                     f.close()
  1054             copyfile(filename, dst_filename, symlink)
  1120                 # special-case custom readline.so on OS X, but not for pypy:
  1055             if filename.endswith('.pyc'):
  1121                 if modname == 'readline' and sys.platform == 'darwin' and not (
  1056                 pyfile = filename[:-1]
  1122                         is_pypy or filename.endswith(join('lib-dynload', 'readline.so'))):
  1057                 if os.path.exists(pyfile):
  1123                     dst_filename = join(dst_prefix, 'lib', 'python%s' % sys.version[:3], 'readline.so')
  1058                     copyfile(pyfile, dst_filename[:-1], symlink)
  1124                 elif modname == 'readline' and sys.platform == 'win32':
       
  1125                     # special-case for Windows, where readline is not a
       
  1126                     # standard module, though it may have been installed in
       
  1127                     # site-packages by a third-party package
       
  1128                     pass
       
  1129                 else:
       
  1130                     dst_filename = change_prefix(filename, dst_prefix)
       
  1131                 copyfile(filename, dst_filename, symlink)
       
  1132                 if filename.endswith('.pyc'):
       
  1133                     pyfile = filename[:-1]
       
  1134                     if os.path.exists(pyfile):
       
  1135                         copyfile(pyfile, dst_filename[:-1], symlink)
       
  1136     finally:
       
  1137         sys.path = _prev_sys_path
       
  1138 
  1059 
  1139 
  1060 
  1140 def subst_path(prefix_path, prefix, home_dir):
  1061 def subst_path(prefix_path, prefix, home_dir):
  1141     prefix_path = os.path.normpath(prefix_path)
  1062     prefix_path = os.path.normpath(prefix_path)
  1142     prefix = os.path.normpath(prefix)
  1063     prefix = os.path.normpath(prefix)
  1193     finally:
  1114     finally:
  1194         logger.indent -= 2
  1115         logger.indent -= 2
  1195     mkdir(join(lib_dir, 'site-packages'))
  1116     mkdir(join(lib_dir, 'site-packages'))
  1196     import site
  1117     import site
  1197     site_filename = site.__file__
  1118     site_filename = site.__file__
  1198     if site_filename.endswith('.pyc'):
  1119     if site_filename.endswith('.pyc') or site_filename.endswith('.pyo'):
  1199         site_filename = site_filename[:-1]
  1120         site_filename = site_filename[:-1]
  1200     elif site_filename.endswith('$py.class'):
  1121     elif site_filename.endswith('$py.class'):
  1201         site_filename = site_filename.replace('$py.class', '.py')
  1122         site_filename = site_filename.replace('$py.class', '.py')
  1202     site_filename_dst = change_prefix(site_filename, home_dir)
  1123     site_filename_dst = change_prefix(site_filename, home_dir)
  1203     site_dir = os.path.dirname(site_filename_dst)
  1124     site_dir = os.path.dirname(site_filename_dst)
  1488 
  1409 
  1489     return py_executable
  1410     return py_executable
  1490 
  1411 
  1491 
  1412 
  1492 def install_activate(home_dir, bin_dir, prompt=None):
  1413 def install_activate(home_dir, bin_dir, prompt=None):
  1493     home_dir = os.path.abspath(home_dir)
       
  1494     if is_win or is_jython and os._name == 'nt':
  1414     if is_win or is_jython and os._name == 'nt':
  1495         files = {
  1415         files = {
  1496             'activate.bat': ACTIVATE_BAT,
  1416             'activate.bat': ACTIVATE_BAT,
  1497             'deactivate.bat': DEACTIVATE_BAT,
  1417             'deactivate.bat': DEACTIVATE_BAT,
  1498             'activate.ps1': ACTIVATE_PS,
  1418             'activate.ps1': ACTIVATE_PS,
  1516 
  1436 
  1517         # same for csh/tcsh support...
  1437         # same for csh/tcsh support...
  1518         files['activate.csh'] = ACTIVATE_CSH
  1438         files['activate.csh'] = ACTIVATE_CSH
  1519 
  1439 
  1520     files['activate_this.py'] = ACTIVATE_THIS
  1440     files['activate_this.py'] = ACTIVATE_THIS
       
  1441 
       
  1442     install_files(home_dir, bin_dir, prompt, files)
       
  1443 
       
  1444 def install_files(home_dir, bin_dir, prompt, files):
  1521     if hasattr(home_dir, 'decode'):
  1445     if hasattr(home_dir, 'decode'):
  1522         home_dir = home_dir.decode(sys.getfilesystemencoding())
  1446         home_dir = home_dir.decode(sys.getfilesystemencoding())
  1523     vname = os.path.basename(home_dir)
  1447     vname = os.path.basename(home_dir)
  1524     for name, content in files.items():
  1448     for name, content in files.items():
  1525         content = content.replace('__VIRTUAL_PROMPT__', prompt or '')
  1449         content = content.replace('__VIRTUAL_PROMPT__', prompt or '')
  1526         content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname)
  1450         content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname)
  1527         content = content.replace('__VIRTUAL_ENV__', home_dir)
  1451         content = content.replace('__VIRTUAL_ENV__', home_dir)
  1528         content = content.replace('__VIRTUAL_NAME__', vname)
  1452         content = content.replace('__VIRTUAL_NAME__', vname)
  1529         content = content.replace('__BIN_NAME__', os.path.basename(bin_dir))
  1453         content = content.replace('__BIN_NAME__', os.path.basename(bin_dir))
  1530         writefile(os.path.join(bin_dir, name), content)
  1454         writefile(os.path.join(bin_dir, name), content)
       
  1455 
       
  1456 def install_python_config(home_dir, bin_dir, prompt=None):
       
  1457     if sys.platform == 'win32' or is_jython and os._name == 'nt':
       
  1458         files = {}
       
  1459     else:
       
  1460         files = {'python-config': PYTHON_CONFIG}
       
  1461     install_files(home_dir, bin_dir, prompt, files)
       
  1462     for name, content in files.items():
       
  1463         make_exe(os.path.join(bin_dir, name))
  1531 
  1464 
  1532 def install_distutils(home_dir):
  1465 def install_distutils(home_dir):
  1533     distutils_path = change_prefix(distutils.__path__[0], home_dir)
  1466     distutils_path = change_prefix(distutils.__path__[0], home_dir)
  1534     mkdir(distutils_path)
  1467     mkdir(distutils_path)
  1535     ## FIXME: maybe this prefix setting should only be put in place if
  1468     ## FIXME: maybe this prefix setting should only be put in place if
  1564     """
  1497     """
  1565     Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
  1498     Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
  1566     instead of lib/pythonX.Y.  If this is such a platform we'll just create a
  1499     instead of lib/pythonX.Y.  If this is such a platform we'll just create a
  1567     symlink so lib64 points to lib
  1500     symlink so lib64 points to lib
  1568     """
  1501     """
  1569     if [p for p in distutils.sysconfig.get_config_vars().values()
  1502     # PyPy's library path scheme is not affected by this.
  1570         if isinstance(p, basestring) and 'lib64' in p]:
  1503     # Return early or we will die on the following assert.
  1571         # PyPy's library path scheme is not affected by this.
  1504     if is_pypy:
  1572         # Return early or we will die on the following assert.
  1505         logger.debug('PyPy detected, skipping lib64 symlinking')
  1573         if is_pypy:
  1506         return
  1574             logger.debug('PyPy detected, skipping lib64 symlinking')
  1507     # Check we have a lib64 library path
  1575             return
  1508     if not [p for p in distutils.sysconfig.get_config_vars().values()
  1576 
  1509             if isinstance(p, basestring) and 'lib64' in p]:
  1577         logger.debug('This system uses lib64; symlinking lib64 to lib')
  1510         return
  1578 
  1511 
  1579         assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
  1512     logger.debug('This system uses lib64; symlinking lib64 to lib')
  1580             "Unexpected python lib dir: %r" % lib_dir)
  1513 
  1581         lib_parent = os.path.dirname(lib_dir)
  1514     assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
  1582         top_level = os.path.dirname(lib_parent)
  1515         "Unexpected python lib dir: %r" % lib_dir)
  1583         lib_dir = os.path.join(top_level, 'lib')
  1516     lib_parent = os.path.dirname(lib_dir)
  1584         lib64_link = os.path.join(top_level, 'lib64')
  1517     top_level = os.path.dirname(lib_parent)
  1585         assert os.path.basename(lib_parent) == 'lib', (
  1518     lib_dir = os.path.join(top_level, 'lib')
  1586             "Unexpected parent dir: %r" % lib_parent)
  1519     lib64_link = os.path.join(top_level, 'lib64')
  1587         if os.path.lexists(lib64_link):
  1520     assert os.path.basename(lib_parent) == 'lib', (
  1588             return
  1521         "Unexpected parent dir: %r" % lib_parent)
  1589         if symlink:
  1522     if os.path.lexists(lib64_link):
  1590             os.symlink('lib', lib64_link)
  1523         return
  1591         else:
  1524     if symlink:
  1592             copyfile('lib', lib64_link)
  1525         os.symlink('lib', lib64_link)
       
  1526     else:
       
  1527         copyfile('lib', lib64_link)
  1593 
  1528 
  1594 def resolve_interpreter(exe):
  1529 def resolve_interpreter(exe):
  1595     """
  1530     """
  1596     If the executable given isn't an absolute path, search $PATH for the interpreter
  1531     If the executable given isn't an absolute path, search $PATH for the interpreter
  1597     """
  1532     """
  1602         exe = python_versions[exe]
  1537         exe = python_versions[exe]
  1603 
  1538 
  1604     if os.path.abspath(exe) != exe:
  1539     if os.path.abspath(exe) != exe:
  1605         paths = os.environ.get('PATH', '').split(os.pathsep)
  1540         paths = os.environ.get('PATH', '').split(os.pathsep)
  1606         for path in paths:
  1541         for path in paths:
  1607             if os.path.exists(os.path.join(path, exe)):
  1542             if os.path.exists(join(path, exe)):
  1608                 exe = os.path.join(path, exe)
  1543                 exe = join(path, exe)
  1609                 break
  1544                 break
  1610     if not os.path.exists(exe):
  1545     if not os.path.exists(exe):
  1611         logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe))
  1546         logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe))
  1612         raise SystemExit(3)
  1547         raise SystemExit(3)
  1613     if not is_executable(exe):
  1548     if not is_executable(exe):
  1658     for filename in os.listdir(bin_dir):
  1593     for filename in os.listdir(bin_dir):
  1659         filename = os.path.join(bin_dir, filename)
  1594         filename = os.path.join(bin_dir, filename)
  1660         if not os.path.isfile(filename):
  1595         if not os.path.isfile(filename):
  1661             # ignore subdirs, e.g. .svn ones.
  1596             # ignore subdirs, e.g. .svn ones.
  1662             continue
  1597             continue
  1663         f = open(filename, 'rb')
  1598         lines = None
  1664         try:
  1599         with open(filename, 'rb') as f:
  1665             try:
  1600             try:
  1666                 lines = f.read().decode('utf-8').splitlines()
  1601                 lines = f.read().decode('utf-8').splitlines()
  1667             except UnicodeDecodeError:
  1602             except UnicodeDecodeError:
  1668                 # This is probably a binary program instead
  1603                 # This is probably a binary program instead
  1669                 # of a script, so just ignore it.
  1604                 # of a script, so just ignore it.
  1670                 continue
  1605                 continue
  1671         finally:
       
  1672             f.close()
       
  1673         if not lines:
  1606         if not lines:
  1674             logger.warn('Script %s is an empty file' % filename)
  1607             logger.warn('Script %s is an empty file' % filename)
  1675             continue
  1608             continue
  1676 
  1609 
  1677         old_shebang = lines[0].strip()
  1610         old_shebang = lines[0].strip()
  1686                 logger.warn('Script %s cannot be made relative (it\'s not a normal script that starts with %s)'
  1619                 logger.warn('Script %s cannot be made relative (it\'s not a normal script that starts with %s)'
  1687                             % (filename, shebang))
  1620                             % (filename, shebang))
  1688             continue
  1621             continue
  1689         logger.notify('Making script %s relative' % filename)
  1622         logger.notify('Making script %s relative' % filename)
  1690         script = relative_script([new_shebang] + lines[1:])
  1623         script = relative_script([new_shebang] + lines[1:])
  1691         f = open(filename, 'wb')
  1624         with open(filename, 'wb') as f:
  1692         f.write('\n'.join(script).encode('utf-8'))
  1625             f.write('\n'.join(script).encode('utf-8'))
  1693         f.close()
  1626 
  1694 
  1627 
  1695 def relative_script(lines):
  1628 def relative_script(lines):
  1696     "Return a script that'll work in a relocatable environment."
  1629     "Return a script that'll work in a relocatable environment."
  1697     activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this"
  1630     activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this"
  1698     # Find the last future statement in the script. If we insert the activation
  1631     # Find the last future statement in the script. If we insert the activation
  1735                     fixup_egg_link(filename)
  1668                     fixup_egg_link(filename)
  1736 
  1669 
  1737 def fixup_pth_file(filename):
  1670 def fixup_pth_file(filename):
  1738     lines = []
  1671     lines = []
  1739     prev_lines = []
  1672     prev_lines = []
  1740     f = open(filename)
  1673     with open(filename) as f:
  1741     prev_lines = f.readlines()
  1674         prev_lines = f.readlines()
  1742     f.close()
       
  1743     for line in prev_lines:
  1675     for line in prev_lines:
  1744         line = line.strip()
  1676         line = line.strip()
  1745         if (not line or line.startswith('#') or line.startswith('import ')
  1677         if (not line or line.startswith('#') or line.startswith('import ')
  1746             or os.path.abspath(line) != line):
  1678             or os.path.abspath(line) != line):
  1747             lines.append(line)
  1679             lines.append(line)
  1752             lines.append(new_value)
  1684             lines.append(new_value)
  1753     if lines == prev_lines:
  1685     if lines == prev_lines:
  1754         logger.info('No changes to .pth file %s' % filename)
  1686         logger.info('No changes to .pth file %s' % filename)
  1755         return
  1687         return
  1756     logger.notify('Making paths in .pth file %s relative' % filename)
  1688     logger.notify('Making paths in .pth file %s relative' % filename)
  1757     f = open(filename, 'w')
  1689     with open(filename, 'w') as f:
  1758     f.write('\n'.join(lines) + '\n')
  1690         f.write('\n'.join(lines) + '\n')
  1759     f.close()
       
  1760 
  1691 
  1761 def fixup_egg_link(filename):
  1692 def fixup_egg_link(filename):
  1762     f = open(filename)
  1693     with open(filename) as f:
  1763     link = f.readline().strip()
  1694         link = f.readline().strip()
  1764     f.close()
       
  1765     if os.path.abspath(link) != link:
  1695     if os.path.abspath(link) != link:
  1766         logger.debug('Link in %s already relative' % filename)
  1696         logger.debug('Link in %s already relative' % filename)
  1767         return
  1697         return
  1768     new_link = make_relative_path(filename, link)
  1698     new_link = make_relative_path(filename, link)
  1769     logger.notify('Rewriting link %s in %s as %s' % (link, filename, new_link))
  1699     logger.notify('Rewriting link %s in %s as %s' % (link, filename, new_link))
  1770     f = open(filename, 'w')
  1700     with open(filename, 'w') as f:
  1771     f.write(new_link)
  1701         f.write(new_link)
  1772     f.close()
       
  1773 
  1702 
  1774 def make_relative_path(source, dest, dest_is_directory=True):
  1703 def make_relative_path(source, dest, dest_is_directory=True):
  1775     """
  1704     """
  1776     Make a filename relative, where the filename is dest, and it is
  1705     Make a filename relative, where the filename is dest, and it is
  1777     being referred to from the filename source.
  1706     being referred to from the filename source.
  1850     be run with a particular Python version.
  1779     be run with a particular Python version.
  1851     """
  1780     """
  1852     filename = __file__
  1781     filename = __file__
  1853     if filename.endswith('.pyc'):
  1782     if filename.endswith('.pyc'):
  1854         filename = filename[:-1]
  1783         filename = filename[:-1]
  1855     f = codecs.open(filename, 'r', encoding='utf-8')
  1784     with codecs.open(filename, 'r', encoding='utf-8') as f:
  1856     content = f.read()
  1785         content = f.read()
  1857     f.close()
       
  1858     py_exe = 'python%s' % python_version
  1786     py_exe = 'python%s' % python_version
  1859     content = (('#!/usr/bin/env %s\n' % py_exe)
  1787     content = (('#!/usr/bin/env %s\n' % py_exe)
  1860                + '## WARNING: This file is generated\n'
  1788                + '## WARNING: This file is generated\n'
  1861                + content)
  1789                + content)
  1862     return content.replace('##EXT' 'END##', extra_text)
  1790     return content.replace('##EXT' 'END##', extra_text)
  2012 AVijEPwfucjncQ==
  1940 AVijEPwfucjncQ==
  2013 """)
  1941 """)
  2014 
  1942 
  2015 ##file activate.sh
  1943 ##file activate.sh
  2016 ACTIVATE_SH = convert("""
  1944 ACTIVATE_SH = convert("""
  2017 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
  1958 VzsV75usvTdYef+57v5n1b225qhXfwEmxHEs
  2031 5v+njPpPGPP/OeL/dbwfGu1Utz87Sp7q
       
  2032 """)
  1959 """)
  2033 
  1960 
  2034 ##file activate.fish
  1961 ##file activate.fish
  2035 ACTIVATE_FISH = convert("""
  1962 ACTIVATE_FISH = convert("""
  2036 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
  1977 uEtpcBj2Z1wjrqGReJBHrY6/go21NA==
  2051 32XS1ITj/qLjN72ob0hc5C9bzw8MhfmL
       
  2052 """)
  1978 """)
  2053 
  1979 
  2054 ##file activate.csh
  1980 ##file activate.csh
  2055 ACTIVATE_CSH = convert("""
  1981 ACTIVATE_CSH = convert("""
  2056 eJx9VG1P2zAQ/u5fcYQKNgTNPtN1WxlIQ4KCUEGaxuQ6yYVYSuzKdhqVX7+zk3bpy5YPUXL3PPfc
  1982 eJx1U2FP2zAQ/e5f8TAV3Soo+0zXbYUiDQkKQgVp2ibjJNfFUuIg22nVf885SVFLO3+I7Lt3fr6X
  2057 ne98DLNCWshliVDV1kGCUFvMoJGugMjq2qQIiVSxSJ1cCofD1BYRnOVGV0CfZ0N2DD91DalQSjsw
  1983 d8eY58ZjYQpCWfuAhFB7yrAyIYf0Ve1SQmLsuU6DWepAw9TnEoOFq0rwdjAUx/hV1Ui1tVWAqy1M
  2058 tQLpIJMGU1euvPe7QeJlkKzgWixlhnAt4aoUVsLnLBiy5NtbJWQ5THX1ZciYKKWwkOFaE04dUm6D
  1984 QGYcpaFYx+yVI67LkKwx1UuTEaYGl4X2Bl+zJpAlP/6V2hTDtCq/DYXQhdEeGW040Q/Eb+t9V/e3
  2059 r/zh7pq/3D7Nnid3/HEy+wFHY/gEJydg0aFaQrBFgz1c5DG1IhTs+UZgsBC2GMFBlaeH+8dZXwcW
  1985 U/V88zh/mtyqh8n8J47G+IKTE3gKZJdoYrK3h5MRU1tGYS83gqNc+3yEgyyP93cP820evHLvr2H8
  2060 VPvCjXdlAvCfQsE7al0+07XjZvrSCUevR5dnkVeKlFYZmUztG4BdzL2u9KyLVabTU0bdfg7a0hgs
  1986 kaYB/peoyY7aVHzpJnE9e+6I5Z+ji4GMTNJWNuOQq6MA1N25p8pW9HWdVWlfsNpPDbdxjgpaahuw
  2061 cSmUg6UwUiQl2iHrcbcVGNvPCiLOe7+cRwG13z9qRGgx2z6DHjfm/Op2yqeT+xvOLzs0PTKHDz2V
  1987 1M7opCA/FFu1uwxC7L8KUqmto1KyQe3rx0I0Eovdf7BVe67U5c1MzSZ310pddGheZoFPWyytRkzU
  2062 tkckFHoQfQRXoGJAj9el0FyJCmEMhzgMS4sB7KPOE2ExoLcSieYwDvR+cP8cg11gKkVJc2wRcm1g
  1988 aCA/I+RkBXhFXr5aWV0SxjhUI6jwdAj8kmhPzX7nTfJFkM3MImp2VdVFFq1vLHSU5szYQK4Ri+Jd
  2063 QhYFlXiTaTfO2ki0fQoiFM4tLuO4aZrhOzqR4dIPcWx17hphMBY+Srwh7RTyN83XOWkcSPh1Pg/k
  1989 xlW2JBtOGcyYVW7SnB3v6RS91g3gKapZ0oWxbHVteYIIq3iv7QeuSrUj6KSqQ+yqsxDj1ivNQxKF
  2064 TXX/jbJTbMtUmcxZ+/bbqOsy82suFQg/BhdSOTRhMNBHlUarCpU7JzBhmkKmRejKOQzayQe6MWoa
  1990 YON10Q+NH/ARS95i5Tuqq2Vxfvc23f/FO6zrtXXmJr+ZtMY9/A15ZXFWtmch2rEQ4g1ryVHH
  2065 n1wqWmuh6LZAaHxcdeqIlVLhIBJdO9/kbl0It2oEXQj+eGjJOuvOIR/YGRqvFhttUB2XTvLXYN2H
       
  2066 37CBdbW2W7j2r2+VsCn0doVWcFG1/4y1VwBjfwAyoZhD
       
  2067 """)
  1991 """)
  2068 
  1992 
  2069 ##file activate.bat
  1993 ##file activate.bat
  2070 ACTIVATE_BAT = convert("""
  1994 ACTIVATE_BAT = convert("""
  2071 eJx9UdEKgjAUfW6wfxjiIH+hEDKUFHSKLCMI7kNOEkIf9P9pTJ3OLJ/03HPPPed4Es9XS9qqwqgT
  1995 eJx9Ul9LhEAQfxf8DoOclI/dYyFkaCmcq4gZQTBUrincuZFbff12T133TM+nnd35/Zvxlr7XDFhV
  2072 PbGKKOdXL4aAFS7A4gvAwgijuiKlqOpGlATS2NeMLE+TjJM9RkQ+SmqAXLrBo1LLIeLdiWlD6jZt
  1996 mUZHOVhFlOWP3g4DUriIWoVomYZpNBWUtGpaWgImO191pFkSpzlcmgaI70jVX7n2Qp8tuByg+46O
  2073 r7VNubWkndkXaxg5GO3UaOOKS6drO3luDDiO5my3iA0YAKGzPRV1ack8cOdhysI0CYzIPzjSiH5X
  1997 CMHbMq64T+nmlJt082D1T44muCDk2prgEHF4mdI9RaS/QwSt3zSyIAaftRccvqVTBziD1x/WlPD5
  2074 0QcvC8Lfaj0emsVKYF2rhL5L3fCkVjV76kShi59NHwDniAHzkgDgqBcwOgTMx+gDQQqXCw==
  1998 xd729NDBb8Nr4DU9QNMKsJeH9pkhPedhQsIkDuCDCa6A+NF9IevVFAohkqizdHetg/tkWvPoftWJ
       
  1999 MCqnOxv7/x7Np6yv9P2Ker5dmX8yNyCkkWnbZy3N5LarczlqL8htx2EM9rQ/2H5BvIsIEi8OEG8U
       
  2000 +g8CsNTr
  2075 """)
  2001 """)
  2076 
  2002 
  2077 ##file deactivate.bat
  2003 ##file deactivate.bat
  2078 DEACTIVATE_BAT = convert("""
  2004 DEACTIVATE_BAT = convert("""
  2079 eJxzSE3OyFfIT0vj4ipOLVEI8wwKCXX0iXf1C7Pl4spMU0hJTcvMS01RiPf3cYmHyQYE+fsGhCho
  2005 eJyFkN0KgkAUhO8F32EQpHqFQEjQUPAPMaErqVxzId3IrV6/XST/UDx3c86c4WMO5FYysKJQFVVp
  2080 cCkAAUibEkTEVhWLMlUlLk6QGixStlyaeCyJDPHw9/Pw93VFsQguim4ZXAJoIUw5DhX47XUM8UCx
  2006 CEfqxsnJ9DI7SA25i20fFqs3HO+GYLsDZ7h8GM3xfLHrg1QNvpSX4CWpQGvokZk4uqrQAjXjyElB
  2081 EchHtwsohN1bILUgw61c/Vy4AJYPYm4=
  2007 a5IjCz0r+2dHcehHCe5MZNmB5R7TdqMqECMptHZh6DN/utb7Zs6Cej8OXYE5J04YOKFvD4GkHuJ0
       
  2008 pilSd1jG6n87tDZ+BUwUOepI6CGSkFMYWf0ihvT33Qj1A+tCkSI=
  2082 """)
  2009 """)
  2083 
  2010 
  2084 ##file activate.ps1
  2011 ##file activate.ps1
  2085 ACTIVATE_PS = convert("""
  2012 ACTIVATE_PS = convert("""
  2086 eJylWdmO41hyfW+g/0FTU7C7IXeJIqmtB/3AnZRIStxF2kaBm7gv4ipyMF/mB3+Sf8GXVGVl1tLT
  2013 eJylWdmO41hyfW+g/0FTU7C7IXeJIqmtB/3AnZRIStxF2kaBm7gv4ipyMF/mB3+Sf8GXVGVl1tLT
  2218 m8eg6WYWqR6SL5OjKMGfSrYt/6kxxQtOpeAgj1LXBNmpE2ElmCSIy5H0zFd8gJ924HWijWhb2hRC
  2145 m8eg6WYWqR6SL5OjKMGfSrYt/6kxxQtOpeAgj1LXBNmpE2ElmCSIy5H0zFd8gJ924HWijWhb2hRC
  2219 6wNEm1QdDZtuSZcEprIUBo/XRNcbQe1OUbQ/r3hPTaPJJDNtFLu8KHV5XoNr3Eo6h6YtOKw8e8yw
  2146 6wNEm1QdDZtuSZcEprIUBo/XRNcbQe1OUbQ/r3hPTaPJJDNtFLu8KHV5XoNr3Eo6h6YtOKw8e8yw
  2220 VF5PnJ+ts3a9/Mz38RpG/AUSzYUW
  2147 VF5PnJ+ts3a9/Mz38RpG/AUSzYUW
  2221 """)
  2148 """)
  2222 
  2149 
       
  2150 ##file python-config
       
  2151 PYTHON_CONFIG = convert("""
       
  2152 eJyNVV1P2zAUfc+v8ODBiSABxlulTipbO6p1LWqBgVhlhcZpPYUkctzSivHfd6+dpGloGH2Ja/ue
       
  2153 e+65Hz78xNhtf3x90xmw7vCWsRPGLvpDNuz87MKfdKMWSWxZ4ilNpCLZJiuWc66SVFUOZkkcirll
       
  2154 rfxIBAzOMtImDzSVPBRrekwoX/OZu/0r4lm0DHiG60g86u8sjPw5rCyy86NRkB8QuuBRSqfAKESn
       
  2155 3orLTCQxE3GYkC9tYp8fk89OSwNsmXgizrhUtnumeSgeo5GbLUMk49Rv+2nK48Cm/qMwfp333J2/
       
  2156 dVcAGE0CIQHBsgIeEr4Wij0LtWDLzJ9ze5YEvH2WI6CHTAVcSu9ZCsXtgxu81CIvp6/k4eXsdfo7
       
  2157 PvDCRD75yi41QitfzlcPp1OI7i/1/iQitqnr0iMgQ+A6wa+IKwwdxyk9IiXNAzgquTFU8NIxAVjM
       
  2158 osm1Zz526e+shQ4hKRVci69nPC3Kw4NQEmkQ65E7OodxorSvxjvpBjQHDmWFIQ1mlmzlS5vedseT
       
  2159 /mgIEsMJ7Lxz2bLAF9M5xeLEhdbHxpWOw0GdkJApMVBRF1y+a0z3c9WZPAXGFcFrJgCIB+024uad
       
  2160 0CrzmEoRa3Ub4swNIHPGf7QDV+2uj2OiFWsChgCwjKqN6rp5izpbH6Wc1O1TclQTP/XVwi6anTr1
       
  2161 1sbubjZLI1+VptPSdCfwnFBrB1jvebrTA9uUhU2/9gad7xPqeFkaQcnnLbCViZK8d7R1kxzFrIJV
       
  2162 8EaLYmKYpvGVkig+3C5HCXbM1jGCGekiM2pRCVPyRyXYdPf6kcbWEQ36F5V4Gq9N7icNNw+JHwRE
       
  2163 LTgxRXACpvnQv/PuT0xCCAywY/K4hE6Now2qDwaSE5FB+1agsoUveYDepS83qFcF1NufvULD3fTl
       
  2164 g6Hgf7WBt6lzMeiyyWVn3P1WVbwaczHmTzE9A5SyItTVgFYyvs/L/fXlaNgbw8v3azT+0eikVlWD
       
  2165 /vBHbzQumP23uBCjsYdrL9OWARwxs/nuLOzeXbPJTa/Xv6sUmQir5pC1YRLz3eA+CD8Z0XpcW8v9
       
  2166 MZWF36ryyXXf3yBIz6nzqz8Muyz0m5Qj7OexfYo/Ph3LqvkHUg7AuA==
       
  2167 """)
       
  2168 
  2223 MH_MAGIC = 0xfeedface
  2169 MH_MAGIC = 0xfeedface
  2224 MH_CIGAM = 0xcefaedfe
  2170 MH_CIGAM = 0xcefaedfe
  2225 MH_MAGIC_64 = 0xfeedfacf
  2171 MH_MAGIC_64 = 0xfeedfacf
  2226 MH_CIGAM_64 = 0xcffaedfe
  2172 MH_CIGAM_64 = 0xcffaedfe
  2227 FAT_MAGIC = 0xcafebabe
  2173 FAT_MAGIC = 0xcafebabe
  2354             do_macho(file, 64, BIG_ENDIAN)
  2300             do_macho(file, 64, BIG_ENDIAN)
  2355         elif magic == MH_CIGAM_64:
  2301         elif magic == MH_CIGAM_64:
  2356             do_macho(file, 64, LITTLE_ENDIAN)
  2302             do_macho(file, 64, LITTLE_ENDIAN)
  2357 
  2303 
  2358     assert(len(what) >= len(value))
  2304     assert(len(what) >= len(value))
  2359     do_file(open(path, 'r+b'))
  2305 
       
  2306     with open(path, 'r+b') as f:
       
  2307         do_file(f)
  2360 
  2308 
  2361 
  2309 
  2362 if __name__ == '__main__':
  2310 if __name__ == '__main__':
  2363     main()
  2311     main()
  2364 
  2312 
  2365 ## TODO:
  2313 # TODO:
  2366 ## Copy python.exe.manifest
  2314 # Copy python.exe.manifest
  2367 ## Monkeypatch distutils.sysconfig
  2315 # Monkeypatch distutils.sysconfig