~pythonregexp2.7/python/issue2636-09-01+10

« back to all changes in this revision

Viewing changes to Lib/site.py

  • Committer: Jeffrey C. "The TimeHorse" Jacobs
  • Date: 2008-05-24 18:56:40 UTC
  • mfrom: (39055.1.22 Regexp-2.6)
  • Revision ID: darklord@timehorse.com-20080524185640-59vz6l1f7qgixgal
Merged in changes from the Single-Loop Engine branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
62
62
import os
63
63
import __builtin__
64
64
 
 
65
# Prefixes for site-packages; add additional prefixes like /usr/local here
 
66
PREFIXES = [sys.prefix, sys.exec_prefix]
 
67
# Enable per user site-packages directory
 
68
# set it to False to disable the feature or True to force the feature
 
69
ENABLE_USER_SITE = None
 
70
# for distutils.commands.install
 
71
USER_SITE = None
 
72
USER_BASE = None
 
73
 
65
74
 
66
75
def makepath(*paths):
67
76
    dir = os.path.abspath(os.path.join(*paths))
68
77
    return dir, os.path.normcase(dir)
69
78
 
 
79
 
70
80
def abs__file__():
71
81
    """Set all module' __file__ attribute to an absolute path"""
72
82
    for m in sys.modules.values():
77
87
        except AttributeError:
78
88
            continue
79
89
 
 
90
 
80
91
def removeduppaths():
81
92
    """ Remove duplicate entries from sys.path along with making them
82
93
    absolute"""
107
118
    s = os.path.join(os.path.dirname(sys.path[-1]), s)
108
119
    sys.path.append(s)
109
120
 
 
121
 
110
122
def _init_pathinfo():
111
123
    """Return a set containing all existing directory entries from sys.path"""
112
124
    d = set()
119
131
            continue
120
132
    return d
121
133
 
 
134
 
122
135
def addpackage(sitedir, name, known_paths):
123
136
    """Process a .pth file within the site-packages directory:
124
137
       For each line in the file, either combine it with sitedir to a path
134
147
        f = open(fullname, "rU")
135
148
    except IOError:
136
149
        return
137
 
    try:
 
150
    with f:
138
151
        for line in f:
139
152
            if line.startswith("#"):
140
153
                continue
141
 
            if line.startswith("import ") or line.startswith("import\t"):
 
154
            if line.startswith(("import ", "import\t")):
142
155
                exec line
143
156
                continue
144
157
            line = line.rstrip()
146
159
            if not dircase in known_paths and os.path.exists(dir):
147
160
                sys.path.append(dir)
148
161
                known_paths.add(dircase)
149
 
    finally:
150
 
        f.close()
151
162
    if reset:
152
163
        known_paths = None
153
164
    return known_paths
154
165
 
 
166
 
155
167
def addsitedir(sitedir, known_paths=None):
156
168
    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
157
169
    'sitedir'"""
167
179
        names = os.listdir(sitedir)
168
180
    except os.error:
169
181
        return
170
 
    names.sort()
171
 
    for name in names:
172
 
        if name.endswith(os.extsep + "pth"):
173
 
            addpackage(sitedir, name, known_paths)
 
182
    dotpth = os.extsep + "pth"
 
183
    names = [name for name in names if name.endswith(dotpth)]
 
184
    for name in sorted(names):
 
185
        addpackage(sitedir, name, known_paths)
174
186
    if reset:
175
187
        known_paths = None
176
188
    return known_paths
177
189
 
 
190
 
 
191
def check_enableusersite():
 
192
    """Check if user site directory is safe for inclusion
 
193
 
 
194
    The function tests for the command line flag (including environment var),
 
195
    process uid/gid equal to effective uid/gid.
 
196
 
 
197
    None: Disabled for security reasons
 
198
    False: Disabled by user (command line option)
 
199
    True: Safe and enabled
 
200
    """
 
201
    if sys.flags.no_user_site:
 
202
        return False
 
203
 
 
204
    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
 
205
        # check process uid == effective uid
 
206
        if os.geteuid() != os.getuid():
 
207
            return None
 
208
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
 
209
        # check process gid == effective gid
 
210
        if os.getegid() != os.getgid():
 
211
            return None
 
212
 
 
213
    return True
 
214
 
 
215
 
 
216
def addusersitepackages(known_paths):
 
217
    """Add a per user site-package to sys.path
 
218
 
 
219
    Each user has its own python directory with site-packages in the
 
220
    home directory.
 
221
 
 
222
    USER_BASE is the root directory for all Python versions
 
223
 
 
224
    USER_SITE is the user specific site-packages directory
 
225
 
 
226
    USER_SITE/.. can be used for data.
 
227
    """
 
228
    global USER_BASE, USER_SITE, ENABLE_USER_SITE
 
229
    env_base = os.environ.get("PYTHONUSERBASE", None)
 
230
 
 
231
    def joinuser(*args):
 
232
        return os.path.expanduser(os.path.join(*args))
 
233
 
 
234
    #if sys.platform in ('os2emx', 'riscos'):
 
235
    #    # Don't know what to put here
 
236
    #    USER_BASE = ''
 
237
    #    USER_SITE = ''
 
238
    if os.name == "nt":
 
239
        base = os.environ.get("APPDATA") or "~"
 
240
        USER_BASE = env_base if env_base else joinuser(base, "Python")
 
241
        USER_SITE = os.path.join(USER_BASE,
 
242
                                 "Python" + sys.version[0] + sys.version[2],
 
243
                                 "site-packages")
 
244
    else:
 
245
        USER_BASE = env_base if env_base else joinuser("~", ".local")
 
246
        USER_SITE = os.path.join(USER_BASE, "lib",
 
247
                                 "python" + sys.version[:3],
 
248
                                 "site-packages")
 
249
 
 
250
    if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
 
251
        addsitedir(USER_SITE, known_paths)
 
252
    return known_paths
 
253
 
 
254
 
178
255
def addsitepackages(known_paths):
179
256
    """Add site-packages (and possibly site-python) to sys.path"""
180
 
    prefixes = [sys.prefix]
181
 
    if sys.exec_prefix != sys.prefix:
182
 
        prefixes.append(sys.exec_prefix)
183
 
    for prefix in prefixes:
184
 
        if prefix:
185
 
            if sys.platform in ('os2emx', 'riscos'):
186
 
                sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
187
 
            elif os.sep == '/':
188
 
                sitedirs = [os.path.join(prefix,
189
 
                                         "lib",
190
 
                                         "python" + sys.version[:3],
191
 
                                         "site-packages"),
192
 
                            os.path.join(prefix, "lib", "site-python")]
193
 
            else:
194
 
                sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
195
 
            if sys.platform == 'darwin':
196
 
                # for framework builds *only* we add the standard Apple
197
 
                # locations. Currently only per-user, but /Library and
198
 
                # /Network/Library could be added too
199
 
                if 'Python.framework' in prefix:
200
 
                    home = os.environ.get('HOME')
201
 
                    if home:
202
 
                        sitedirs.append(
203
 
                            os.path.join(home,
204
 
                                         'Library',
205
 
                                         'Python',
206
 
                                         sys.version[:3],
207
 
                                         'site-packages'))
208
 
            for sitedir in sitedirs:
209
 
                if os.path.isdir(sitedir):
210
 
                    addsitedir(sitedir, known_paths)
211
 
    return None
 
257
    sitedirs = []
 
258
    seen = []
 
259
 
 
260
    for prefix in PREFIXES:
 
261
        if not prefix or prefix in seen:
 
262
            continue
 
263
        seen.append(prefix)
 
264
 
 
265
        if sys.platform in ('os2emx', 'riscos'):
 
266
            sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
 
267
        elif os.sep == '/':
 
268
            sitedirs.append(os.path.join(prefix, "lib",
 
269
                                        "python" + sys.version[:3],
 
270
                                        "site-packages"))
 
271
            sitedirs.append(os.path.join(prefix, "lib", "site-python"))
 
272
        else:
 
273
            sitedirs.append(prefix)
 
274
            sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
 
275
 
 
276
        if sys.platform == "darwin":
 
277
            # for framework builds *only* we add the standard Apple
 
278
            # locations. Currently only per-user, but /Library and
 
279
            # /Network/Library could be added too
 
280
            if 'Python.framework' in prefix:
 
281
                sitedirs.append(
 
282
                    os.path.expanduser(
 
283
                        os.path.join("~", "Library", "Python",
 
284
                                     sys.version[:3], "site-packages")))
 
285
 
 
286
    for sitedir in sitedirs:
 
287
        if os.path.isdir(sitedir):
 
288
            addsitedir(sitedir, known_paths)
 
289
 
 
290
    return known_paths
212
291
 
213
292
 
214
293
def setBEGINLIBPATH():
395
474
        pass
396
475
 
397
476
 
 
477
def execusercustomize():
 
478
    """Run custom user specific code, if available."""
 
479
    try:
 
480
        import usercustomize
 
481
    except ImportError:
 
482
        pass
 
483
 
 
484
 
398
485
def main():
 
486
    global ENABLE_USER_SITE
 
487
 
399
488
    abs__file__()
400
 
    paths_in_sys = removeduppaths()
 
489
    known_paths = removeduppaths()
401
490
    if (os.name == "posix" and sys.path and
402
491
        os.path.basename(sys.path[-1]) == "Modules"):
403
492
        addbuilddir()
404
 
    paths_in_sys = addsitepackages(paths_in_sys)
 
493
    if ENABLE_USER_SITE is None:
 
494
        ENABLE_USER_SITE = check_enableusersite()
 
495
    known_paths = addusersitepackages(known_paths)
 
496
    known_paths = addsitepackages(known_paths)
405
497
    if sys.platform == 'os2emx':
406
498
        setBEGINLIBPATH()
407
499
    setquit()
410
502
    aliasmbcs()
411
503
    setencoding()
412
504
    execsitecustomize()
 
505
    if ENABLE_USER_SITE:
 
506
        execusercustomize()
413
507
    # Remove sys.setdefaultencoding() so that users cannot change the
414
508
    # encoding after initialization.  The test for presence is needed when
415
509
    # this module is run as a script, because this code is executed twice.
418
512
 
419
513
main()
420
514
 
421
 
def _test():
422
 
    print "sys.path = ["
423
 
    for dir in sys.path:
424
 
        print "    %r," % (dir,)
425
 
    print "]"
 
515
def _script():
 
516
    help = """\
 
517
    %s [--user-base] [--user-site]
 
518
 
 
519
    Without arguments print some useful information
 
520
    With arguments print the value of USER_BASE and/or USER_SITE separated
 
521
    by '%s'.
 
522
 
 
523
    Exit codes with --user-base or --user-site:
 
524
      0 - user site directory is enabled
 
525
      1 - user site directory is disabled by user
 
526
      2 - uses site directory is disabled by super user
 
527
          or for security reasons
 
528
     >2 - unknown error
 
529
    """
 
530
    args = sys.argv[1:]
 
531
    if not args:
 
532
        print "sys.path = ["
 
533
        for dir in sys.path:
 
534
            print "    %r," % (dir,)
 
535
        print "]"
 
536
        print "USER_BASE: %r (%s)" % (USER_BASE,
 
537
            "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
 
538
        print "USER_SITE: %r (%s)" % (USER_SITE,
 
539
            "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
 
540
        print "ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE
 
541
        sys.exit(0)
 
542
 
 
543
    buffer = []
 
544
    if '--user-base' in args:
 
545
        buffer.append(USER_BASE)
 
546
    if '--user-site' in args:
 
547
        buffer.append(USER_SITE)
 
548
 
 
549
    if buffer:
 
550
        print os.pathsep.join(buffer)
 
551
        if ENABLE_USER_SITE:
 
552
            sys.exit(0)
 
553
        elif ENABLE_USER_SITE is False:
 
554
            sys.exit(1)
 
555
        elif ENABLE_USER_SITE is None:
 
556
            sys.exit(2)
 
557
        else:
 
558
            sys.exit(3)
 
559
    else:
 
560
        import textwrap
 
561
        print textwrap.dedent(help % (sys.argv[0], os.pathsep))
 
562
        sys.exit(10)
426
563
 
427
564
if __name__ == '__main__':
428
 
    _test()
 
565
    _script()