Statistics
| Revision:

root / tags / v1_0_2_Build_904 / extensions / extScripting / scripts / jython / Lib / site.py @ 10724

History | View | Annotate | Download (8.83 KB)

1
"""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 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
On other platforms (mainly Mac and Windows), it uses just sys.prefix
17
\(and sys.exec_prefix, if different, but this is unlikely).  The
18
resulting directories, if they exist, are appended to sys.path, and
19
also inspected for path configuration files.
20

21
A path configuration file is a file whose name has the form
22
<package>.pth; its contents are additional directories (one per line)
23
to be added to sys.path.  Non-existing directories (or
24
non-directories) are never added to sys.path; no directory is added to
25
sys.path more than once.  Blank lines and lines beginning with
26
\code{#} are skipped. Lines starting with \code{import} are executed.
27

28
For example, suppose sys.prefix and sys.exec_prefix are set to
29
/usr/local and there is a directory /usr/local/lib/python1.5/site-packages
30
with three subdirectories, foo, bar and spam, and two path
31
configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
32
following:
33

34
  # foo package configuration
35
  foo
36
  bar
37
  bletch
38

39
and bar.pth contains:
40

41
  # bar package configuration
42
  bar
43

44
Then the following directories are added to sys.path, in this order:
45

46
  /usr/local/lib/python1.5/site-packages/bar
47
  /usr/local/lib/python1.5/site-packages/foo
48

49
Note that bletch is omitted because it doesn't exist; bar precedes foo
50
because bar.pth comes alphabetically before foo.pth; and spam is
51
omitted because it is not mentioned in either path configuration file.
52

53
After these path manipulations, an attempt is made to import a module
54
named sitecustomize, which can perform arbitrary additional
55
site-specific customizations.  If this import fails with an
56
ImportError exception, it is silently ignored.
57

58
"""
59

    
60
import sys, os
61

    
62
if os.sep==".":
63
    endsep = "/"
64
else:
65
    endsep = "."
66

    
67

    
68
def makepath(*paths):
69
    dir = os.path.abspath(os.path.join(*paths))
70
    return dir, os.path.normcase(dir)
71

    
72
for m in sys.modules.values():
73
    if hasattr(m, "__file__") and m.__file__:
74
        m.__file__ = os.path.abspath(m.__file__)
75
del m
76

    
77
# This ensures that the initial path provided by the interpreter contains
78
# only absolute pathnames, even if we're running from the build directory.
79
L = []
80
dirs_in_sys_path = {}
81
for dir in sys.path:
82
    dir, dircase = makepath(dir)
83
    if not dirs_in_sys_path.has_key(dircase):
84
        L.append(dir)
85
        dirs_in_sys_path[dircase] = 1
86
sys.path[:] = L
87
del dir, L
88

    
89
# Append ./build/lib.<platform> in case we're running in the build dir
90
# (especially for Guido :-)
91
if os.name == "posix" and os.path.basename(sys.path[-1]) == "Modules":
92
    from distutils.util import get_platform
93
    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
94
    s = os.path.join(os.path.dirname(sys.path[-1]), s)
95
    sys.path.append(s)
96
    del get_platform, s
97

    
98
def addsitedir(sitedir):
99
    sitedir, sitedircase = makepath(sitedir)
100
    if not dirs_in_sys_path.has_key(sitedircase):
101
        sys.path.append(sitedir)        # Add path component
102
    try:
103
        names = os.listdir(sitedir)
104
    except os.error:
105
        return
106
    names.sort()
107
    for name in names:
108
        if name[-4:] == endsep + "pth":
109
            addpackage(sitedir, name)
110

    
111
def addpackage(sitedir, name):
112
    fullname = os.path.join(sitedir, name)
113
    try:
114
        f = open(fullname)
115
    except IOError:
116
        return
117
    while 1:
118
        dir = f.readline()
119
        if not dir:
120
            break
121
        if dir[0] == '#':
122
            continue
123
        if dir.startswith("import"):
124
            exec dir
125
            continue
126
        if dir[-1] == '\n':
127
            dir = dir[:-1]
128
        dir, dircase = makepath(sitedir, dir)
129
        if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir):
130
            sys.path.append(dir)
131
            dirs_in_sys_path[dircase] = 1
132

    
133
prefixes = [sys.prefix]
134
if sys.exec_prefix != sys.prefix:
135
    prefixes.append(sys.exec_prefix)
136
for prefix in prefixes:
137
    if prefix:
138
        if os.sep == '/':
139
            sitedirs = [os.path.join(prefix,
140
                                     "lib",
141
                                     "python" + sys.version[:3],
142
                                     "site-packages"),
143
                        os.path.join(prefix, "lib", "site-python")]
144
        elif os.sep == ':':
145
            sitedirs = [os.path.join(prefix, "lib", "site-packages")]
146
        else:
147
            sitedirs = [prefix]
148
        for sitedir in sitedirs:
149
            if os.path.isdir(sitedir):
150
                addsitedir(sitedir)
151

    
152

    
153
# Define new built-ins 'quit' and 'exit'.
154
# These are simply strings that display a hint on how to exit.
155
if os.sep == ':':
156
    exit = 'Use Cmd-Q to quit.'
157
elif os.sep == '\\':
158
    exit = 'Use Ctrl-Z plus Return to exit.'
159
else:
160
    exit = 'Use Ctrl-D (i.e. EOF) to exit.'
161
import __builtin__
162
__builtin__.quit = __builtin__.exit = exit
163
del exit
164

    
165
# interactive prompt objects for printing the license text, a list of
166
# contributors and the copyright notice.
167
class _Printer:
168
    MAXLINES = 23
169

    
170
    def __init__(self, name, data, files=(), dirs=()):
171
        self.__name = name
172
        self.__data = data
173
        self.__files = files
174
        self.__dirs = dirs
175
        self.__lines = None
176

    
177
    def __setup(self):
178
        if self.__lines:
179
            return
180
        data = None
181
        for dir in self.__dirs:
182
            for file in self.__files:
183
                file = os.path.join(dir, file)
184
                try:
185
                    fp = open(file)
186
                    data = fp.read()
187
                    fp.close()
188
                    break
189
                except IOError:
190
                    pass
191
            if data:
192
                break
193
        if not data:
194
            data = self.__data
195
        self.__lines = data.split('\n')
196
        self.__linecnt = len(self.__lines)
197

    
198
    def __repr__(self):
199
        self.__setup()
200
        if len(self.__lines) <= self.MAXLINES:
201
            return "\n".join(self.__lines)
202
        else:
203
            return "Type %s() to see the full %s text" % ((self.__name,)*2)
204

    
205
    def __call__(self):
206
        self.__setup()
207
        prompt = 'Hit Return for more, or q (and Return) to quit: '
208
        lineno = 0
209
        while 1:
210
            try:
211
                for i in range(lineno, lineno + self.MAXLINES):
212
                    print self.__lines[i]
213
            except IndexError:
214
                break
215
            else:
216
                lineno += self.MAXLINES
217
                key = None
218
                while key is None:
219
                    key = raw_input(prompt)
220
                    if key not in ('', 'q'):
221
                        key = None
222
                if key == 'q':
223
                    break
224

    
225
__builtin__.copyright = _Printer("copyright", sys.copyright)
226
if sys.platform[:4] == 'java':
227
    __builtin__.credits = _Printer(
228
        "credits",
229
        "Jython is maintained by the Jython developers (www.jython.org).")
230
else:
231
    __builtin__.credits = _Printer("credits", """\
232
Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands
233
for supporting Python development.  See www.python.org for more information.""")
234
here = os.path.dirname(os.__file__)
235
__builtin__.license = _Printer(
236
    "license", "See http://www.pythonlabs.com/products/python2.0/license.html",
237
    ["LICENSE.txt", "LICENSE"],
238
    [os.path.join(here, os.pardir), here, os.curdir])
239

    
240

    
241
# Set the string encoding used by the Unicode implementation.  The
242
# default is 'ascii', but if you're willing to experiment, you can
243
# change this.
244

    
245
encoding = "ascii" # Default value set by _PyUnicode_Init()
246

    
247
if 0:
248
    # Enable to support locale aware default string encodings.
249
    import locale
250
    loc = locale.getdefaultlocale()
251
    if loc[1]:
252
        encoding = loc[1]
253

    
254
if 0:
255
    # Enable to switch off string to Unicode coercion and implicit
256
    # Unicode to string conversion.
257
    encoding = "undefined"
258

    
259
if encoding != "ascii":
260
    sys.setdefaultencoding(encoding)
261

    
262
#
263
# Run custom site specific code, if available.
264
#
265
try:
266
    import sitecustomize
267
except ImportError:
268
    pass
269

    
270
#
271
# Remove sys.setdefaultencoding() so that users cannot change the
272
# encoding after initialization.  The test for presence is needed when
273
# this module is run as a script, because this code is executed twice.
274
#
275
if hasattr(sys, "setdefaultencoding"):
276
    del sys.setdefaultencoding
277

    
278
def _test():
279
    print "sys.path = ["
280
    for dir in sys.path:
281
        print "    %s," % `dir`
282
    print "]"
283

    
284
if __name__ == '__main__':
285
    _test()