1"""Append module search paths for third-party packages to sys.path.
2
3****************************************************************
4* This module is automatically imported during initialization. *
5****************************************************************
6
7In earlier versions of Python (up to 1.5a3), scripts or modules that
8needed to use site-specific modules would place ``import site''
9somewhere near the top of their code.  Because of the automatic
10import, this is no longer necessary (but code that does it still
11works).
12
13This will append site-specific paths to the module search path.  On
14Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
15appends lib/python<version>/site-packages as well as lib/site-python.
16It also supports the Debian convention of
17lib/python<version>/dist-packages.  On other platforms (mainly Mac and
18Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
19but this is unlikely).  The resulting directories, if they exist, are
20appended to sys.path, and also inspected for path configuration files.
21
22FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
23Local addons go into /usr/local/lib/python<version>/site-packages
24(resp. /usr/local/lib/site-python), Debian addons install into
25/usr/{lib,share}/python<version>/dist-packages.
26
27A path configuration file is a file whose name has the form
28<package>.pth; its contents are additional directories (one per line)
29to be added to sys.path.  Non-existing directories (or
30non-directories) are never added to sys.path; no directory is added to
31sys.path more than once.  Blank lines and lines beginning with
32'#' are skipped. Lines starting with 'import' are executed.
33
34For example, suppose sys.prefix and sys.exec_prefix are set to
35/usr/local and there is a directory /usr/local/lib/python2.X/site-packages
36with three subdirectories, foo, bar and spam, and two path
37configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
38following:
39
40  # foo package configuration
41  foo
42  bar
43  bletch
44
45and bar.pth contains:
46
47  # bar package configuration
48  bar
49
50Then the following directories are added to sys.path, in this order:
51
52  /usr/local/lib/python2.X/site-packages/bar
53  /usr/local/lib/python2.X/site-packages/foo
54
55Note that bletch is omitted because it doesn't exist; bar precedes foo
56because bar.pth comes alphabetically before foo.pth; and spam is
57omitted because it is not mentioned in either path configuration file.
58
59After these path manipulations, an attempt is made to import a module
60named sitecustomize, which can perform arbitrary additional
61site-specific customizations.  If this import fails with an
62ImportError exception, it is silently ignored.
63
64"""
65
66import os
67import sys
68
69try:
70    import __builtin__ as builtins
71except ImportError:
72    import builtins
73try:
74    set
75except NameError:
76    from sets import Set as set
77
78# Prefixes for site-packages; add additional prefixes like /usr/local here
79PREFIXES = [sys.prefix, sys.exec_prefix]
80# Enable per user site-packages directory
81# set it to False to disable the feature or True to force the feature
82ENABLE_USER_SITE = None
83# for distutils.commands.install
84USER_SITE = None
85USER_BASE = None
86
87_is_64bit = (getattr(sys, "maxsize", None) or getattr(sys, "maxint")) > 2 ** 32
88_is_pypy = hasattr(sys, "pypy_version_info")
89
90
91def makepath(*paths):
92    dir = os.path.join(*paths)
93    dir = os.path.abspath(dir)
94    return dir, os.path.normcase(dir)
95
96
97def abs__file__():
98    """Set all module' __file__ attribute to an absolute path"""
99    for m in sys.modules.values():
100        f = getattr(m, "__file__", None)
101        if f is None:
102            continue
103        m.__file__ = os.path.abspath(f)
104
105
106def removeduppaths():
107    """ Remove duplicate entries from sys.path along with making them
108    absolute"""
109    # This ensures that the initial path provided by the interpreter contains
110    # only absolute pathnames, even if we're running from the build directory.
111    L = []
112    known_paths = set()
113    for dir in sys.path:
114        # Filter out duplicate paths (on case-insensitive file systems also
115        # if they only differ in case); turn relative paths into absolute
116        # paths.
117        dir, dircase = makepath(dir)
118        if not dircase in known_paths:
119            L.append(dir)
120            known_paths.add(dircase)
121    sys.path[:] = L
122    return known_paths
123
124
125# XXX This should not be part of site.py, since it is needed even when
126# using the -S option for Python.  See http://www.python.org/sf/586680
127def addbuilddir():
128    """Append ./build/lib.<platform> in case we're running in the build dir
129    (especially for Guido :-)"""
130    from distutils.util import get_platform
131
132    s = "build/lib.{}-{}.{}".format(get_platform(), *sys.version_info)
133    if hasattr(sys, "gettotalrefcount"):
134        s += "-pydebug"
135    s = os.path.join(os.path.dirname(sys.path[-1]), s)
136    sys.path.append(s)
137
138
139def _init_pathinfo():
140    """Return a set containing all existing directory entries from sys.path"""
141    d = set()
142    for dir in sys.path:
143        try:
144            if os.path.isdir(dir):
145                dir, dircase = makepath(dir)
146                d.add(dircase)
147        except TypeError:
148            continue
149    return d
150
151
152def addpackage(sitedir, name, known_paths):
153    """Add a new path to known_paths by combining sitedir and 'name' or execute
154    sitedir if it starts with 'import'"""
155    if known_paths is None:
156        _init_pathinfo()
157        reset = 1
158    else:
159        reset = 0
160    fullname = os.path.join(sitedir, name)
161    try:
162        f = open(fullname, "r")
163    except IOError:
164        return
165    try:
166        for line in f:
167            if line.startswith("#"):
168                continue
169            if line.startswith("import"):
170                exec(line)
171                continue
172            line = line.rstrip()
173            dir, dircase = makepath(sitedir, line)
174            if not dircase in known_paths and os.path.exists(dir):
175                sys.path.append(dir)
176                known_paths.add(dircase)
177    finally:
178        f.close()
179    if reset:
180        known_paths = None
181    return known_paths
182
183
184def addsitedir(sitedir, known_paths=None):
185    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
186    'sitedir'"""
187    if known_paths is None:
188        known_paths = _init_pathinfo()
189        reset = 1
190    else:
191        reset = 0
192    sitedir, sitedircase = makepath(sitedir)
193    if not sitedircase in known_paths:
194        sys.path.append(sitedir)  # Add path component
195    try:
196        names = os.listdir(sitedir)
197    except os.error:
198        return
199    names.sort()
200    for name in names:
201        if name.endswith(os.extsep + "pth"):
202            addpackage(sitedir, name, known_paths)
203    if reset:
204        known_paths = None
205    return known_paths
206
207
208def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
209    """Add site-packages (and possibly site-python) to sys.path"""
210    prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
211    if exec_prefix != sys_prefix:
212        prefixes.append(os.path.join(exec_prefix, "local"))
213
214    for prefix in prefixes:
215        if prefix:
216            if sys.platform in ("os2emx", "riscos"):
217                sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
218            elif _is_pypy:
219                sitedirs = [os.path.join(prefix, "site-packages")]
220            elif sys.platform == "darwin" and prefix == sys_prefix:
221
222                if prefix.startswith("/System/Library/Frameworks/"):  # Apple's Python
223
224                    sitedirs = [
225                        os.path.join("/Library/Python", "{}.{}".format(*sys.version_info), "site-packages"),
226                        os.path.join(prefix, "Extras", "lib", "python"),
227                    ]
228
229                else:  # any other Python distros on OSX work this way
230                    sitedirs = [os.path.join(prefix, "lib", "python{}.{}".format(*sys.version_info), "site-packages")]
231
232            elif os.sep == "/":
233                sitedirs = [
234                    os.path.join(prefix, "lib", "python{}.{}".format(*sys.version_info), "site-packages"),
235                    os.path.join(prefix, "lib", "site-python"),
236                    os.path.join(prefix, "python{}.{}".format(*sys.version_info), "lib-dynload"),
237                ]
238                lib64_dir = os.path.join(prefix, "lib64", "python{}.{}".format(*sys.version_info), "site-packages")
239                if os.path.exists(lib64_dir) and os.path.realpath(lib64_dir) not in [
240                    os.path.realpath(p) for p in sitedirs
241                ]:
242                    if _is_64bit:
243                        sitedirs.insert(0, lib64_dir)
244                    else:
245                        sitedirs.append(lib64_dir)
246                try:
247                    # sys.getobjects only available in --with-pydebug build
248                    sys.getobjects
249                    sitedirs.insert(0, os.path.join(sitedirs[0], "debug"))
250                except AttributeError:
251                    pass
252                # Debian-specific dist-packages directories:
253                sitedirs.append(
254                    os.path.join(prefix, "local/lib", "python{}.{}".format(*sys.version_info), "dist-packages")
255                )
256                if sys.version_info[0] == 2:
257                    sitedirs.append(
258                        os.path.join(prefix, "lib", "python{}.{}".format(*sys.version_info), "dist-packages")
259                    )
260                else:
261                    sitedirs.append(
262                        os.path.join(prefix, "lib", "python{}".format(sys.version_info[0]), "dist-packages")
263                    )
264                sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
265            else:
266                sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
267            if sys.platform == "darwin":
268                # for framework builds *only* we add the standard Apple
269                # locations. Currently only per-user, but /Library and
270                # /Network/Library could be added too
271                if "Python.framework" in prefix:
272                    home = os.environ.get("HOME")
273                    if home:
274                        sitedirs.append(
275                            os.path.join(home, "Library", "Python", "{}.{}".format(*sys.version_info), "site-packages")
276                        )
277            for sitedir in sitedirs:
278                if os.path.isdir(sitedir):
279                    addsitedir(sitedir, known_paths)
280    return None
281
282
283def check_enableusersite():
284    """Check if user site directory is safe for inclusion
285
286    The function tests for the command line flag (including environment var),
287    process uid/gid equal to effective uid/gid.
288
289    None: Disabled for security reasons
290    False: Disabled by user (command line option)
291    True: Safe and enabled
292    """
293    if hasattr(sys, "flags") and getattr(sys.flags, "no_user_site", False):
294        return False
295
296    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
297        # check process uid == effective uid
298        if os.geteuid() != os.getuid():
299            return None
300    if hasattr(os, "getgid") and hasattr(os, "getegid"):
301        # check process gid == effective gid
302        if os.getegid() != os.getgid():
303            return None
304
305    return True
306
307
308def addusersitepackages(known_paths):
309    """Add a per user site-package to sys.path
310
311    Each user has its own python directory with site-packages in the
312    home directory.
313
314    USER_BASE is the root directory for all Python versions
315
316    USER_SITE is the user specific site-packages directory
317
318    USER_SITE/.. can be used for data.
319    """
320    global USER_BASE, USER_SITE, ENABLE_USER_SITE
321    env_base = os.environ.get("PYTHONUSERBASE", None)
322
323    def joinuser(*args):
324        return os.path.expanduser(os.path.join(*args))
325
326    # if sys.platform in ('os2emx', 'riscos'):
327    #    # Don't know what to put here
328    #    USER_BASE = ''
329    #    USER_SITE = ''
330    if os.name == "nt":
331        base = os.environ.get("APPDATA") or "~"
332        if env_base:
333            USER_BASE = env_base
334        else:
335            USER_BASE = joinuser(base, "Python")
336        USER_SITE = os.path.join(USER_BASE, "Python{}{}".format(*sys.version_info), "site-packages")
337    else:
338        if env_base:
339            USER_BASE = env_base
340        else:
341            USER_BASE = joinuser("~", ".local")
342        USER_SITE = os.path.join(USER_BASE, "lib", "python{}.{}".format(*sys.version_info), "site-packages")
343
344    if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
345        addsitedir(USER_SITE, known_paths)
346    if ENABLE_USER_SITE:
347        for dist_libdir in ("lib", "local/lib"):
348            user_site = os.path.join(USER_BASE, dist_libdir, "python{}.{}".format(*sys.version_info), "dist-packages")
349            if os.path.isdir(user_site):
350                addsitedir(user_site, known_paths)
351    return known_paths
352
353
354def setBEGINLIBPATH():
355    """The OS/2 EMX port has optional extension modules that do double duty
356    as DLLs (and must use the .DLL file extension) for other extensions.
357    The library search path needs to be amended so these will be found
358    during module import.  Use BEGINLIBPATH so that these are at the start
359    of the library search path.
360
361    """
362    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
363    libpath = os.environ["BEGINLIBPATH"].split(";")
364    if libpath[-1]:
365        libpath.append(dllpath)
366    else:
367        libpath[-1] = dllpath
368    os.environ["BEGINLIBPATH"] = ";".join(libpath)
369
370
371def setquit():
372    """Define new built-ins 'quit' and 'exit'.
373    These are simply strings that display a hint on how to exit.
374
375    """
376    if os.sep == ":":
377        eof = "Cmd-Q"
378    elif os.sep == "\\":
379        eof = "Ctrl-Z plus Return"
380    else:
381        eof = "Ctrl-D (i.e. EOF)"
382
383    class Quitter(object):
384        def __init__(self, name):
385            self.name = name
386
387        def __repr__(self):
388            return "Use {}() or {} to exit".format(self.name, eof)
389
390        def __call__(self, code=None):
391            # Shells like IDLE catch the SystemExit, but listen when their
392            # stdin wrapper is closed.
393            try:
394                sys.stdin.close()
395            except:
396                pass
397            raise SystemExit(code)
398
399    builtins.quit = Quitter("quit")
400    builtins.exit = Quitter("exit")
401
402
403class _Printer(object):
404    """interactive prompt objects for printing the license text, a list of
405    contributors and the copyright notice."""
406
407    MAXLINES = 23
408
409    def __init__(self, name, data, files=(), dirs=()):
410        self.__name = name
411        self.__data = data
412        self.__files = files
413        self.__dirs = dirs
414        self.__lines = None
415
416    def __setup(self):
417        if self.__lines:
418            return
419        data = None
420        for dir in self.__dirs:
421            for filename in self.__files:
422                filename = os.path.join(dir, filename)
423                try:
424                    fp = open(filename, "r")
425                    data = fp.read()
426                    fp.close()
427                    break
428                except IOError:
429                    pass
430            if data:
431                break
432        if not data:
433            data = self.__data
434        self.__lines = data.split("\n")
435        self.__linecnt = len(self.__lines)
436
437    def __repr__(self):
438        self.__setup()
439        if len(self.__lines) <= self.MAXLINES:
440            return "\n".join(self.__lines)
441        else:
442            return "Type %s() to see the full %s text" % ((self.__name,) * 2)
443
444    def __call__(self):
445        self.__setup()
446        prompt = "Hit Return for more, or q (and Return) to quit: "
447        lineno = 0
448        while 1:
449            try:
450                for i in range(lineno, lineno + self.MAXLINES):
451                    print(self.__lines[i])
452            except IndexError:
453                break
454            else:
455                lineno += self.MAXLINES
456                key = None
457                while key is None:
458                    try:
459                        key = raw_input(prompt)
460                    except NameError:
461                        key = input(prompt)
462                    if key not in ("", "q"):
463                        key = None
464                if key == "q":
465                    break
466
467
468def setcopyright():
469    """Set 'copyright' and 'credits' in __builtin__"""
470    builtins.copyright = _Printer("copyright", sys.copyright)
471    if _is_pypy:
472        builtins.credits = _Printer("credits", "PyPy is maintained by the PyPy developers: http://pypy.org/")
473    else:
474        builtins.credits = _Printer(
475            "credits",
476            """\
477    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
478    for supporting Python development.  See www.python.org for more information.""",
479        )
480    here = os.path.dirname(os.__file__)
481    builtins.license = _Printer(
482        "license",
483        "See https://www.python.org/psf/license/",
484        ["LICENSE.txt", "LICENSE"],
485        [sys.prefix, os.path.join(here, os.pardir), here, os.curdir],
486    )
487
488
489class _Helper(object):
490    """Define the built-in 'help'.
491    This is a wrapper around pydoc.help (with a twist).
492
493    """
494
495    def __repr__(self):
496        return "Type help() for interactive help, " "or help(object) for help about object."
497
498    def __call__(self, *args, **kwds):
499        import pydoc
500
501        return pydoc.help(*args, **kwds)
502
503
504def sethelper():
505    builtins.help = _Helper()
506
507
508def aliasmbcs():
509    """On Windows, some default encodings are not provided by Python,
510    while they are always available as "mbcs" in each locale. Make
511    them usable by aliasing to "mbcs" in such a case."""
512    if sys.platform == "win32":
513        import locale, codecs
514
515        enc = locale.getdefaultlocale()[1]
516        if enc.startswith("cp"):  # "cp***" ?
517            try:
518                codecs.lookup(enc)
519            except LookupError:
520                import encodings
521
522                encodings._cache[enc] = encodings._unknown
523                encodings.aliases.aliases[enc] = "mbcs"
524
525
526def setencoding():
527    """Set the string encoding used by the Unicode implementation.  The
528    default is 'ascii', but if you're willing to experiment, you can
529    change this."""
530    encoding = "ascii"  # Default value set by _PyUnicode_Init()
531    if 0:
532        # Enable to support locale aware default string encodings.
533        import locale
534
535        loc = locale.getdefaultlocale()
536        if loc[1]:
537            encoding = loc[1]
538    if 0:
539        # Enable to switch off string to Unicode coercion and implicit
540        # Unicode to string conversion.
541        encoding = "undefined"
542    if encoding != "ascii":
543        # On Non-Unicode builds this will raise an AttributeError...
544        sys.setdefaultencoding(encoding)  # Needs Python Unicode build !
545
546
547def execsitecustomize():
548    """Run custom site specific code, if available."""
549    try:
550        import sitecustomize
551    except ImportError:
552        pass
553
554
555def virtual_install_main_packages():
556    f = open(os.path.join(os.path.dirname(__file__), "orig-prefix.txt"))
557    sys.real_prefix = f.read().strip()
558    f.close()
559    pos = 2
560    hardcoded_relative_dirs = []
561    if sys.path[0] == "":
562        pos += 1
563    if _is_pypy:
564        if sys.version_info > (3, 2):
565            cpyver = "%d" % sys.version_info[0]
566        elif sys.pypy_version_info >= (1, 5):
567            cpyver = "%d.%d" % sys.version_info[:2]
568        else:
569            cpyver = "%d.%d.%d" % sys.version_info[:3]
570        paths = [os.path.join(sys.real_prefix, "lib_pypy"), os.path.join(sys.real_prefix, "lib-python", cpyver)]
571        if sys.pypy_version_info < (1, 9):
572            paths.insert(1, os.path.join(sys.real_prefix, "lib-python", "modified-%s" % cpyver))
573        hardcoded_relative_dirs = paths[:]  # for the special 'darwin' case below
574        #
575        # This is hardcoded in the Python executable, but relative to sys.prefix:
576        for path in paths[:]:
577            plat_path = os.path.join(path, "plat-%s" % sys.platform)
578            if os.path.exists(plat_path):
579                paths.append(plat_path)
580    elif sys.platform == "win32":
581        paths = [os.path.join(sys.real_prefix, "Lib"), os.path.join(sys.real_prefix, "DLLs")]
582    else:
583        paths = [os.path.join(sys.real_prefix, "lib", "python{}.{}".format(*sys.version_info))]
584        hardcoded_relative_dirs = paths[:]  # for the special 'darwin' case below
585        lib64_path = os.path.join(sys.real_prefix, "lib64", "python{}.{}".format(*sys.version_info))
586        if os.path.exists(lib64_path):
587            if _is_64bit:
588                paths.insert(0, lib64_path)
589            else:
590                paths.append(lib64_path)
591        # This is hardcoded in the Python executable, but relative to
592        # sys.prefix.  Debian change: we need to add the multiarch triplet
593        # here, which is where the real stuff lives.  As per PEP 421, in
594        # Python 3.3+, this lives in sys.implementation, while in Python 2.7
595        # it lives in sys.
596        try:
597            arch = getattr(sys, "implementation", sys)._multiarch
598        except AttributeError:
599            # This is a non-multiarch aware Python.  Fallback to the old way.
600            arch = sys.platform
601        plat_path = os.path.join(sys.real_prefix, "lib", "python{}.{}".format(*sys.version_info), "plat-%s" % arch)
602        if os.path.exists(plat_path):
603            paths.append(plat_path)
604    # This is hardcoded in the Python executable, but
605    # relative to sys.prefix, so we have to fix up:
606    for path in list(paths):
607        tk_dir = os.path.join(path, "lib-tk")
608        if os.path.exists(tk_dir):
609            paths.append(tk_dir)
610
611    # These are hardcoded in the Apple's Python executable,
612    # but relative to sys.prefix, so we have to fix them up:
613    if sys.platform == "darwin":
614        hardcoded_paths = [
615            os.path.join(relative_dir, module)
616            for relative_dir in hardcoded_relative_dirs
617            for module in ("plat-darwin", "plat-mac", "plat-mac/lib-scriptpackages")
618        ]
619
620        for path in hardcoded_paths:
621            if os.path.exists(path):
622                paths.append(path)
623
624    sys.path.extend(paths)
625
626
627def force_global_eggs_after_local_site_packages():
628    """
629    Force easy_installed eggs in the global environment to get placed
630    in sys.path after all packages inside the virtualenv.  This
631    maintains the "least surprise" result that packages in the
632    virtualenv always mask global packages, never the other way
633    around.
634
635    """
636    egginsert = getattr(sys, "__egginsert", 0)
637    for i, path in enumerate(sys.path):
638        if i > egginsert and path.startswith(sys.prefix):
639            egginsert = i
640    sys.__egginsert = egginsert + 1
641
642
643def virtual_addsitepackages(known_paths):
644    force_global_eggs_after_local_site_packages()
645    return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
646
647
648def execusercustomize():
649    """Run custom user specific code, if available."""
650    try:
651        import usercustomize
652    except ImportError:
653        pass
654
655
656def enablerlcompleter():
657    """Enable default readline configuration on interactive prompts, by
658    registering a sys.__interactivehook__.
659    If the readline module can be imported, the hook will set the Tab key
660    as completion key and register ~/.python_history as history file.
661    This can be overridden in the sitecustomize or usercustomize module,
662    or in a PYTHONSTARTUP file.
663    """
664
665    def register_readline():
666        import atexit
667
668        try:
669            import readline
670            import rlcompleter
671        except ImportError:
672            return
673
674        # Reading the initialization (config) file may not be enough to set a
675        # completion key, so we set one first and then read the file.
676        readline_doc = getattr(readline, "__doc__", "")
677        if readline_doc is not None and "libedit" in readline_doc:
678            readline.parse_and_bind("bind ^I rl_complete")
679        else:
680            readline.parse_and_bind("tab: complete")
681
682        try:
683            readline.read_init_file()
684        except OSError:
685            # An OSError here could have many causes, but the most likely one
686            # is that there's no .inputrc file (or .editrc file in the case of
687            # Mac OS X + libedit) in the expected location.  In that case, we
688            # want to ignore the exception.
689            pass
690
691        if readline.get_current_history_length() == 0:
692            # If no history was loaded, default to .python_history.
693            # The guard is necessary to avoid doubling history size at
694            # each interpreter exit when readline was already configured
695            # through a PYTHONSTARTUP hook, see:
696            # http://bugs.python.org/issue5845#msg198636
697            history = os.path.join(os.path.expanduser("~"), ".python_history")
698            try:
699                readline.read_history_file(history)
700            except OSError:
701                pass
702
703            def write_history():
704                try:
705                    readline.write_history_file(history)
706                except (FileNotFoundError, PermissionError):
707                    # home directory does not exist or is not writable
708                    # https://bugs.python.org/issue19891
709                    pass
710
711            atexit.register(write_history)
712
713    sys.__interactivehook__ = register_readline
714
715
716if _is_pypy:
717
718    def import_builtin_stuff():
719        """PyPy specific: some built-in modules should be pre-imported because
720        some programs expect them to be in sys.modules on startup. This is ported
721        from PyPy's site.py.
722        """
723        import encodings
724
725        if "exceptions" in sys.builtin_module_names:
726            import exceptions
727
728        if "zipimport" in sys.builtin_module_names:
729            import zipimport
730
731
732def main():
733    global ENABLE_USER_SITE
734    virtual_install_main_packages()
735    if _is_pypy:
736        import_builtin_stuff()
737    abs__file__()
738    paths_in_sys = removeduppaths()
739    if os.name == "posix" and sys.path and os.path.basename(sys.path[-1]) == "Modules":
740        addbuilddir()
741    GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), "no-global-site-packages.txt"))
742    if not GLOBAL_SITE_PACKAGES:
743        ENABLE_USER_SITE = False
744    if ENABLE_USER_SITE is None:
745        ENABLE_USER_SITE = check_enableusersite()
746    paths_in_sys = addsitepackages(paths_in_sys)
747    paths_in_sys = addusersitepackages(paths_in_sys)
748    if GLOBAL_SITE_PACKAGES:
749        paths_in_sys = virtual_addsitepackages(paths_in_sys)
750    if sys.platform == "os2emx":
751        setBEGINLIBPATH()
752    setquit()
753    setcopyright()
754    sethelper()
755    if sys.version_info[0] == 3:
756        enablerlcompleter()
757    aliasmbcs()
758    setencoding()
759    execsitecustomize()
760    if ENABLE_USER_SITE:
761        execusercustomize()
762    # Remove sys.setdefaultencoding() so that users cannot change the
763    # encoding after initialization.  The test for presence is needed when
764    # this module is run as a script, because this code is executed twice.
765    if hasattr(sys, "setdefaultencoding"):
766        del sys.setdefaultencoding
767
768
769main()
770
771
772def _script():
773    help = """\
774    %s [--user-base] [--user-site]
775
776    Without arguments print some useful information
777    With arguments print the value of USER_BASE and/or USER_SITE separated
778    by '%s'.
779
780    Exit codes with --user-base or --user-site:
781      0 - user site directory is enabled
782      1 - user site directory is disabled by user
783      2 - uses site directory is disabled by super user
784          or for security reasons
785     >2 - unknown error
786    """
787    args = sys.argv[1:]
788    if not args:
789        print("sys.path = [")
790        for dir in sys.path:
791            print("    {!r},".format(dir))
792        print("]")
793
794        def exists(path):
795            if os.path.isdir(path):
796                return "exists"
797            else:
798                return "doesn't exist"
799
800        print("USER_BASE: {!r} ({})".format(USER_BASE, exists(USER_BASE)))
801        print("USER_SITE: {!r} ({})".format(USER_SITE, exists(USER_SITE)))
802        print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
803        sys.exit(0)
804
805    buffer = []
806    if "--user-base" in args:
807        buffer.append(USER_BASE)
808    if "--user-site" in args:
809        buffer.append(USER_SITE)
810
811    if buffer:
812        print(os.pathsep.join(buffer))
813        if ENABLE_USER_SITE:
814            sys.exit(0)
815        elif ENABLE_USER_SITE is False:
816            sys.exit(1)
817        elif ENABLE_USER_SITE is None:
818            sys.exit(2)
819        else:
820            sys.exit(3)
821    else:
822        import textwrap
823
824        print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
825        sys.exit(10)
826
827
828if __name__ == "__main__":
829    _script()
830