Project

General

Profile

Statistics
| Branch: | Revision:

root / env / lib / python2.7 / site.py @ 1a305335

History | View | Annotate | Download (25.7 KB)

1 1a305335 officers
"""Append module search paths for third-party packages to sys.path.
2

3
****************************************************************
4
* This module is automatically imported during initialization. *
5
****************************************************************
6

7
In earlier versions of Python (up to 1.5a3), scripts or modules that
8
needed to use site-specific modules would place ``import site''
9
somewhere near the top of their code.  Because of the automatic
10
import, this is no longer necessary (but code that does it still
11
works).
12

13
This will append site-specific paths to the module search path.  On
14
Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
15
appends lib/python<version>/site-packages as well as lib/site-python.
16
It also supports the Debian convention of
17
lib/python<version>/dist-packages.  On other platforms (mainly Mac and
18
Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
19
but this is unlikely).  The resulting directories, if they exist, are
20
appended to sys.path, and also inspected for path configuration files.
21

22
FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
23
Local 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

27
A path configuration file is a file whose name has the form
28
<package>.pth; its contents are additional directories (one per line)
29
to be added to sys.path.  Non-existing directories (or
30
non-directories) are never added to sys.path; no directory is added to
31
sys.path more than once.  Blank lines and lines beginning with
32
'#' are skipped. Lines starting with 'import' are executed.
33

34
For 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
36
with three subdirectories, foo, bar and spam, and two path
37
configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
38
following:
39

40
  # foo package configuration
41
  foo
42
  bar
43
  bletch
44

45
and bar.pth contains:
46

47
  # bar package configuration
48
  bar
49

50
Then 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

55
Note that bletch is omitted because it doesn't exist; bar precedes foo
56
because bar.pth comes alphabetically before foo.pth; and spam is
57
omitted because it is not mentioned in either path configuration file.
58

59
After these path manipulations, an attempt is made to import a module
60
named sitecustomize, which can perform arbitrary additional
61
site-specific customizations.  If this import fails with an
62
ImportError exception, it is silently ignored.
63

64
"""
65
66
import sys
67
import os
68
try:
69
    import __builtin__ as builtins
70
except ImportError:
71
    import builtins
72
try:
73
    set
74
except NameError:
75
    from sets import Set as set
76
77
# Prefixes for site-packages; add additional prefixes like /usr/local here
78
PREFIXES = [sys.prefix, sys.exec_prefix]
79
# Enable per user site-packages directory
80
# set it to False to disable the feature or True to force the feature
81
ENABLE_USER_SITE = None
82
# for distutils.commands.install
83
USER_SITE = None
84
USER_BASE = None
85
86
_is_pypy = hasattr(sys, 'pypy_version_info')
87
_is_jython = sys.platform[:4] == 'java'
88
if _is_jython:
89
    ModuleType = type(os)
90
91
def makepath(*paths):
92
    dir = os.path.join(*paths)
93
    if _is_jython and (dir == '__classpath__' or
94
                       dir.startswith('__pyclasspath__')):
95
        return dir, dir
96
    dir = os.path.abspath(dir)
97
    return dir, os.path.normcase(dir)
98
99
def abs__file__():
100
    """Set all module' __file__ attribute to an absolute path"""
101
    for m in sys.modules.values():
102
        if ((_is_jython and not isinstance(m, ModuleType)) or
103
            hasattr(m, '__loader__')):
104
            # only modules need the abspath in Jython. and don't mess
105
            # with a PEP 302-supplied __file__
106
            continue
107
        f = getattr(m, '__file__', None)
108
        if f is None:
109
            continue
110
        m.__file__ = os.path.abspath(f)
111
112
def removeduppaths():
113
    """ Remove duplicate entries from sys.path along with making them
114
    absolute"""
115
    # This ensures that the initial path provided by the interpreter contains
116
    # only absolute pathnames, even if we're running from the build directory.
117
    L = []
118
    known_paths = set()
119
    for dir in sys.path:
120
        # Filter out duplicate paths (on case-insensitive file systems also
121
        # if they only differ in case); turn relative paths into absolute
122
        # paths.
123
        dir, dircase = makepath(dir)
124
        if not dircase in known_paths:
125
            L.append(dir)
126
            known_paths.add(dircase)
127
    sys.path[:] = L
128
    return known_paths
129
130
# XXX This should not be part of site.py, since it is needed even when
131
# using the -S option for Python.  See http://www.python.org/sf/586680
132
def addbuilddir():
133
    """Append ./build/lib.<platform> in case we're running in the build dir
134
    (especially for Guido :-)"""
135
    from distutils.util import get_platform
136
    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
137
    if hasattr(sys, 'gettotalrefcount'):
138
        s += '-pydebug'
139
    s = os.path.join(os.path.dirname(sys.path[-1]), s)
140
    sys.path.append(s)
141
142
def _init_pathinfo():
143
    """Return a set containing all existing directory entries from sys.path"""
144
    d = set()
145
    for dir in sys.path:
146
        try:
147
            if os.path.isdir(dir):
148
                dir, dircase = makepath(dir)
149
                d.add(dircase)
150
        except TypeError:
151
            continue
152
    return d
153
154
def addpackage(sitedir, name, known_paths):
155
    """Add a new path to known_paths by combining sitedir and 'name' or execute
156
    sitedir if it starts with 'import'"""
157
    if known_paths is None:
158
        _init_pathinfo()
159
        reset = 1
160
    else:
161
        reset = 0
162
    fullname = os.path.join(sitedir, name)
163
    try:
164
        f = open(fullname, "rU")
165
    except IOError:
166
        return
167
    try:
168
        for line in f:
169
            if line.startswith("#"):
170
                continue
171
            if line.startswith("import"):
172
                exec(line)
173
                continue
174
            line = line.rstrip()
175
            dir, dircase = makepath(sitedir, line)
176
            if not dircase in known_paths and os.path.exists(dir):
177
                sys.path.append(dir)
178
                known_paths.add(dircase)
179
    finally:
180
        f.close()
181
    if reset:
182
        known_paths = None
183
    return known_paths
184
185
def addsitedir(sitedir, known_paths=None):
186
    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
187
    'sitedir'"""
188
    if known_paths is None:
189
        known_paths = _init_pathinfo()
190
        reset = 1
191
    else:
192
        reset = 0
193
    sitedir, sitedircase = makepath(sitedir)
194
    if not sitedircase in known_paths:
195
        sys.path.append(sitedir)        # Add path component
196
    try:
197
        names = os.listdir(sitedir)
198
    except os.error:
199
        return
200
    names.sort()
201
    for name in names:
202
        if name.endswith(os.extsep + "pth"):
203
            addpackage(sitedir, name, known_paths)
204
    if reset:
205
        known_paths = None
206
    return known_paths
207
208
def 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') or _is_jython:
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 = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
225
                                os.path.join(prefix, "Extras", "lib", "python")]
226
227
                else: # any other Python distros on OSX work this way
228
                    sitedirs = [os.path.join(prefix, "lib",
229
                                             "python" + sys.version[:3], "site-packages")]
230
231
            elif os.sep == '/':
232
                sitedirs = [os.path.join(prefix,
233
                                         "lib",
234
                                         "python" + sys.version[:3],
235
                                         "site-packages"),
236
                            os.path.join(prefix, "lib", "site-python"),
237
                            os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
238
                lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
239
                if (os.path.exists(lib64_dir) and 
240
                    os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
241
                    sitedirs.append(lib64_dir)
242
                try:
243
                    # sys.getobjects only available in --with-pydebug build
244
                    sys.getobjects
245
                    sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
246
                except AttributeError:
247
                    pass
248
                # Debian-specific dist-packages directories:
249
                sitedirs.append(os.path.join(prefix, "lib",
250
                                             "python" + sys.version[:3],
251
                                             "dist-packages"))
252
                sitedirs.append(os.path.join(prefix, "local/lib",
253
                                             "python" + sys.version[:3],
254
                                             "dist-packages"))
255
                sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
256
            else:
257
                sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
258
            if sys.platform == 'darwin':
259
                # for framework builds *only* we add the standard Apple
260
                # locations. Currently only per-user, but /Library and
261
                # /Network/Library could be added too
262
                if 'Python.framework' in prefix:
263
                    home = os.environ.get('HOME')
264
                    if home:
265
                        sitedirs.append(
266
                            os.path.join(home,
267
                                         'Library',
268
                                         'Python',
269
                                         sys.version[:3],
270
                                         'site-packages'))
271
            for sitedir in sitedirs:
272
                if os.path.isdir(sitedir):
273
                    addsitedir(sitedir, known_paths)
274
    return None
275
276
def check_enableusersite():
277
    """Check if user site directory is safe for inclusion
278

279
    The function tests for the command line flag (including environment var),
280
    process uid/gid equal to effective uid/gid.
281

282
    None: Disabled for security reasons
283
    False: Disabled by user (command line option)
284
    True: Safe and enabled
285
    """
286
    if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
287
        return False
288
289
    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
290
        # check process uid == effective uid
291
        if os.geteuid() != os.getuid():
292
            return None
293
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
294
        # check process gid == effective gid
295
        if os.getegid() != os.getgid():
296
            return None
297
298
    return True
299
300
def addusersitepackages(known_paths):
301
    """Add a per user site-package to sys.path
302

303
    Each user has its own python directory with site-packages in the
304
    home directory.
305

306
    USER_BASE is the root directory for all Python versions
307

308
    USER_SITE is the user specific site-packages directory
309

310
    USER_SITE/.. can be used for data.
311
    """
312
    global USER_BASE, USER_SITE, ENABLE_USER_SITE
313
    env_base = os.environ.get("PYTHONUSERBASE", None)
314
315
    def joinuser(*args):
316
        return os.path.expanduser(os.path.join(*args))
317
318
    #if sys.platform in ('os2emx', 'riscos'):
319
    #    # Don't know what to put here
320
    #    USER_BASE = ''
321
    #    USER_SITE = ''
322
    if os.name == "nt":
323
        base = os.environ.get("APPDATA") or "~"
324
        if env_base:
325
            USER_BASE = env_base
326
        else:
327
            USER_BASE = joinuser(base, "Python")
328
        USER_SITE = os.path.join(USER_BASE,
329
                                 "Python" + sys.version[0] + sys.version[2],
330
                                 "site-packages")
331
    else:
332
        if env_base:
333
            USER_BASE = env_base
334
        else:
335
            USER_BASE = joinuser("~", ".local")
336
        USER_SITE = os.path.join(USER_BASE, "lib",
337
                                 "python" + sys.version[:3],
338
                                 "site-packages")
339
340
    if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
341
        addsitedir(USER_SITE, known_paths)
342
    if ENABLE_USER_SITE:
343
        for dist_libdir in ("lib", "local/lib"):
344
            user_site = os.path.join(USER_BASE, dist_libdir,
345
                                     "python" + sys.version[:3],
346
                                     "dist-packages")
347
            if os.path.isdir(user_site):
348
                addsitedir(user_site, known_paths)
349
    return known_paths
350
351
352
353
def setBEGINLIBPATH():
354
    """The OS/2 EMX port has optional extension modules that do double duty
355
    as DLLs (and must use the .DLL file extension) for other extensions.
356
    The library search path needs to be amended so these will be found
357
    during module import.  Use BEGINLIBPATH so that these are at the start
358
    of the library search path.
359

360
    """
361
    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
362
    libpath = os.environ['BEGINLIBPATH'].split(';')
363
    if libpath[-1]:
364
        libpath.append(dllpath)
365
    else:
366
        libpath[-1] = dllpath
367
    os.environ['BEGINLIBPATH'] = ';'.join(libpath)
368
369
370
def setquit():
371
    """Define new built-ins 'quit' and 'exit'.
372
    These are simply strings that display a hint on how to exit.
373

374
    """
375
    if os.sep == ':':
376
        eof = 'Cmd-Q'
377
    elif os.sep == '\\':
378
        eof = 'Ctrl-Z plus Return'
379
    else:
380
        eof = 'Ctrl-D (i.e. EOF)'
381
382
    class Quitter(object):
383
        def __init__(self, name):
384
            self.name = name
385
        def __repr__(self):
386
            return 'Use %s() or %s to exit' % (self.name, eof)
387
        def __call__(self, code=None):
388
            # Shells like IDLE catch the SystemExit, but listen when their
389
            # stdin wrapper is closed.
390
            try:
391
                sys.stdin.close()
392
            except:
393
                pass
394
            raise SystemExit(code)
395
    builtins.quit = Quitter('quit')
396
    builtins.exit = Quitter('exit')
397
398
399
class _Printer(object):
400
    """interactive prompt objects for printing the license text, a list of
401
    contributors and the copyright notice."""
402
403
    MAXLINES = 23
404
405
    def __init__(self, name, data, files=(), dirs=()):
406
        self.__name = name
407
        self.__data = data
408
        self.__files = files
409
        self.__dirs = dirs
410
        self.__lines = None
411
412
    def __setup(self):
413
        if self.__lines:
414
            return
415
        data = None
416
        for dir in self.__dirs:
417
            for filename in self.__files:
418
                filename = os.path.join(dir, filename)
419
                try:
420
                    fp = file(filename, "rU")
421
                    data = fp.read()
422
                    fp.close()
423
                    break
424
                except IOError:
425
                    pass
426
            if data:
427
                break
428
        if not data:
429
            data = self.__data
430
        self.__lines = data.split('\n')
431
        self.__linecnt = len(self.__lines)
432
433
    def __repr__(self):
434
        self.__setup()
435
        if len(self.__lines) <= self.MAXLINES:
436
            return "\n".join(self.__lines)
437
        else:
438
            return "Type %s() to see the full %s text" % ((self.__name,)*2)
439
440
    def __call__(self):
441
        self.__setup()
442
        prompt = 'Hit Return for more, or q (and Return) to quit: '
443
        lineno = 0
444
        while 1:
445
            try:
446
                for i in range(lineno, lineno + self.MAXLINES):
447
                    print(self.__lines[i])
448
            except IndexError:
449
                break
450
            else:
451
                lineno += self.MAXLINES
452
                key = None
453
                while key is None:
454
                    try:
455
                        key = raw_input(prompt)
456
                    except NameError:
457
                        key = input(prompt)
458
                    if key not in ('', 'q'):
459
                        key = None
460
                if key == 'q':
461
                    break
462
463
def setcopyright():
464
    """Set 'copyright' and 'credits' in __builtin__"""
465
    builtins.copyright = _Printer("copyright", sys.copyright)
466
    if _is_jython:
467
        builtins.credits = _Printer(
468
            "credits",
469
            "Jython is maintained by the Jython developers (www.jython.org).")
470
    elif _is_pypy:
471
        builtins.credits = _Printer(
472
            "credits",
473
            "PyPy is maintained by the PyPy developers: http://codespeak.net/pypy")
474
    else:
475
        builtins.credits = _Printer("credits", """\
476
    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
477
    for supporting Python development.  See www.python.org for more information.""")
478
    here = os.path.dirname(os.__file__)
479
    builtins.license = _Printer(
480
        "license", "See http://www.python.org/%.3s/license.html" % sys.version,
481
        ["LICENSE.txt", "LICENSE"],
482
        [os.path.join(here, os.pardir), here, os.curdir])
483
484
485
class _Helper(object):
486
    """Define the built-in 'help'.
487
    This is a wrapper around pydoc.help (with a twist).
488

489
    """
490
491
    def __repr__(self):
492
        return "Type help() for interactive help, " \
493
               "or help(object) for help about object."
494
    def __call__(self, *args, **kwds):
495
        import pydoc
496
        return pydoc.help(*args, **kwds)
497
498
def sethelper():
499
    builtins.help = _Helper()
500
501
def aliasmbcs():
502
    """On Windows, some default encodings are not provided by Python,
503
    while they are always available as "mbcs" in each locale. Make
504
    them usable by aliasing to "mbcs" in such a case."""
505
    if sys.platform == 'win32':
506
        import locale, codecs
507
        enc = locale.getdefaultlocale()[1]
508
        if enc.startswith('cp'):            # "cp***" ?
509
            try:
510
                codecs.lookup(enc)
511
            except LookupError:
512
                import encodings
513
                encodings._cache[enc] = encodings._unknown
514
                encodings.aliases.aliases[enc] = 'mbcs'
515
516
def setencoding():
517
    """Set the string encoding used by the Unicode implementation.  The
518
    default is 'ascii', but if you're willing to experiment, you can
519
    change this."""
520
    encoding = "ascii" # Default value set by _PyUnicode_Init()
521
    if 0:
522
        # Enable to support locale aware default string encodings.
523
        import locale
524
        loc = locale.getdefaultlocale()
525
        if loc[1]:
526
            encoding = loc[1]
527
    if 0:
528
        # Enable to switch off string to Unicode coercion and implicit
529
        # Unicode to string conversion.
530
        encoding = "undefined"
531
    if encoding != "ascii":
532
        # On Non-Unicode builds this will raise an AttributeError...
533
        sys.setdefaultencoding(encoding) # Needs Python Unicode build !
534
535
536
def execsitecustomize():
537
    """Run custom site specific code, if available."""
538
    try:
539
        import sitecustomize
540
    except ImportError:
541
        pass
542
543
def virtual_install_main_packages():
544
    f = open(os.path.join(os.path.dirname(__file__), 'orig-prefix.txt'))
545
    sys.real_prefix = f.read().strip()
546
    f.close()
547
    pos = 2
548
    hardcoded_relative_dirs = []
549
    if sys.path[0] == '':
550
        pos += 1
551
    if sys.platform == 'win32':
552
        paths = [os.path.join(sys.real_prefix, 'Lib'), os.path.join(sys.real_prefix, 'DLLs')]
553
    elif _is_jython:
554
        paths = [os.path.join(sys.real_prefix, 'Lib')]
555
    elif _is_pypy:
556
        if sys.pypy_version_info >= (1, 5):
557
            cpyver = '%d.%d' % sys.version_info[:2]
558
        else:
559
            cpyver = '%d.%d.%d' % sys.version_info[:3]
560
        paths = [os.path.join(sys.real_prefix, 'lib_pypy'),
561
                 os.path.join(sys.real_prefix, 'lib-python', 'modified-%s' % cpyver),
562
                 os.path.join(sys.real_prefix, 'lib-python', cpyver)]
563
        hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
564
        #
565
        # This is hardcoded in the Python executable, but relative to sys.prefix:
566
        for path in paths[:]:
567
            plat_path = os.path.join(path, 'plat-%s' % sys.platform)
568
            if os.path.exists(plat_path):
569
                paths.append(plat_path)
570
    else:
571
        paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3])]
572
        hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
573
        lib64_path = os.path.join(sys.real_prefix, 'lib64', 'python'+sys.version[:3])
574
        if os.path.exists(lib64_path):
575
            paths.append(lib64_path)
576
        # This is hardcoded in the Python executable, but relative to sys.prefix:
577
        plat_path = os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3],
578
                                 'plat-%s' % sys.platform)
579
        if os.path.exists(plat_path):
580
            paths.append(plat_path)
581
    # This is hardcoded in the Python executable, but
582
    # relative to sys.prefix, so we have to fix up:
583
    for path in list(paths):
584
        tk_dir = os.path.join(path, 'lib-tk')
585
        if os.path.exists(tk_dir):
586
            paths.append(tk_dir)
587
588
    # These are hardcoded in the Apple's Python executable,
589
    # but relative to sys.prefix, so we have to fix them up:
590
    if sys.platform == 'darwin':
591
        hardcoded_paths = [os.path.join(relative_dir, module)
592
                           for relative_dir in hardcoded_relative_dirs
593
                           for module in ('plat-darwin', 'plat-mac', 'plat-mac/lib-scriptpackages')]
594
595
        for path in hardcoded_paths:
596
            if os.path.exists(path):
597
                paths.append(path)
598
599
    sys.path.extend(paths)
600
601
def force_global_eggs_after_local_site_packages():
602
    """
603
    Force easy_installed eggs in the global environment to get placed
604
    in sys.path after all packages inside the virtualenv.  This
605
    maintains the "least surprise" result that packages in the
606
    virtualenv always mask global packages, never the other way
607
    around.
608
    
609
    """
610
    egginsert = getattr(sys, '__egginsert', 0)
611
    for i, path in enumerate(sys.path):
612
        if i > egginsert and path.startswith(sys.prefix):
613
            egginsert = i
614
    sys.__egginsert = egginsert + 1
615
    
616
def virtual_addsitepackages(known_paths):
617
    force_global_eggs_after_local_site_packages()
618
    return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
619
620
def fixclasspath():
621
    """Adjust the special classpath sys.path entries for Jython. These
622
    entries should follow the base virtualenv lib directories.
623
    """
624
    paths = []
625
    classpaths = []
626
    for path in sys.path:
627
        if path == '__classpath__' or path.startswith('__pyclasspath__'):
628
            classpaths.append(path)
629
        else:
630
            paths.append(path)
631
    sys.path = paths
632
    sys.path.extend(classpaths)
633
634
def execusercustomize():
635
    """Run custom user specific code, if available."""
636
    try:
637
        import usercustomize
638
    except ImportError:
639
        pass
640
641
642
def main():
643
    global ENABLE_USER_SITE
644
    virtual_install_main_packages()
645
    abs__file__()
646
    paths_in_sys = removeduppaths()
647
    if (os.name == "posix" and sys.path and
648
        os.path.basename(sys.path[-1]) == "Modules"):
649
        addbuilddir()
650
    if _is_jython:
651
        fixclasspath()
652
    GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), 'no-global-site-packages.txt'))
653
    if not GLOBAL_SITE_PACKAGES:
654
        ENABLE_USER_SITE = False
655
    if ENABLE_USER_SITE is None:
656
        ENABLE_USER_SITE = check_enableusersite()
657
    paths_in_sys = addsitepackages(paths_in_sys)
658
    paths_in_sys = addusersitepackages(paths_in_sys)
659
    if GLOBAL_SITE_PACKAGES:
660
        paths_in_sys = virtual_addsitepackages(paths_in_sys)
661
    if sys.platform == 'os2emx':
662
        setBEGINLIBPATH()
663
    setquit()
664
    setcopyright()
665
    sethelper()
666
    aliasmbcs()
667
    setencoding()
668
    execsitecustomize()
669
    if ENABLE_USER_SITE:
670
        execusercustomize()
671
    # Remove sys.setdefaultencoding() so that users cannot change the
672
    # encoding after initialization.  The test for presence is needed when
673
    # this module is run as a script, because this code is executed twice.
674
    if hasattr(sys, "setdefaultencoding"):
675
        del sys.setdefaultencoding
676
677
main()
678
679
def _script():
680
    help = """\
681
    %s [--user-base] [--user-site]
682

683
    Without arguments print some useful information
684
    With arguments print the value of USER_BASE and/or USER_SITE separated
685
    by '%s'.
686

687
    Exit codes with --user-base or --user-site:
688
      0 - user site directory is enabled
689
      1 - user site directory is disabled by user
690
      2 - uses site directory is disabled by super user
691
          or for security reasons
692
     >2 - unknown error
693
    """
694
    args = sys.argv[1:]
695
    if not args:
696
        print("sys.path = [")
697
        for dir in sys.path:
698
            print("    %r," % (dir,))
699
        print("]")
700
        def exists(path):
701
            if os.path.isdir(path):
702
                return "exists"
703
            else:
704
                return "doesn't exist"
705
        print("USER_BASE: %r (%s)" % (USER_BASE, exists(USER_BASE)))
706
        print("USER_SITE: %r (%s)" % (USER_SITE, exists(USER_BASE)))
707
        print("ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE)
708
        sys.exit(0)
709
710
    buffer = []
711
    if '--user-base' in args:
712
        buffer.append(USER_BASE)
713
    if '--user-site' in args:
714
        buffer.append(USER_SITE)
715
716
    if buffer:
717
        print(os.pathsep.join(buffer))
718
        if ENABLE_USER_SITE:
719
            sys.exit(0)
720
        elif ENABLE_USER_SITE is False:
721
            sys.exit(1)
722
        elif ENABLE_USER_SITE is None:
723
            sys.exit(2)
724
        else:
725
            sys.exit(3)
726
    else:
727
        import textwrap
728
        print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
729
        sys.exit(10)
730
731
if __name__ == '__main__':
732
    _script()