source: trunk/essentials/dev-lang/python/Demo/imputil/importers.py@ 3226

Last change on this file since 3226 was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 7.6 KB
Line 
1#
2# importers.py
3#
4# Demonstration subclasses of imputil.Importer
5#
6
7# There should be consideration for the imports below if it is desirable
8# to have "all" modules be imported through the imputil system.
9
10# these are C extensions
11import sys
12import imp
13import struct
14import marshal
15
16# these are .py modules
17import imputil
18import os
19
20######################################################################
21
22_TupleType = type(())
23_StringType = type('')
24
25######################################################################
26
27# byte-compiled file suffic character
28_suffix_char = __debug__ and 'c' or 'o'
29
30# byte-compiled file suffix
31_suffix = '.py' + _suffix_char
32
33# the C_EXTENSION suffixes
34_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())
35
36def _timestamp(pathname):
37 "Return the file modification time as a Long."
38 try:
39 s = os.stat(pathname)
40 except OSError:
41 return None
42 return long(s[8])
43
44def _fs_import(dir, modname, fqname):
45 "Fetch a module from the filesystem."
46
47 pathname = os.path.join(dir, modname)
48 if os.path.isdir(pathname):
49 values = { '__pkgdir__' : pathname, '__path__' : [ pathname ] }
50 ispkg = 1
51 pathname = os.path.join(pathname, '__init__')
52 else:
53 values = { }
54 ispkg = 0
55
56 # look for dynload modules
57 for desc in _c_suffixes:
58 file = pathname + desc[0]
59 try:
60 fp = open(file, desc[1])
61 except IOError:
62 pass
63 else:
64 module = imp.load_module(fqname, fp, file, desc)
65 values['__file__'] = file
66 return 0, module, values
67
68 t_py = _timestamp(pathname + '.py')
69 t_pyc = _timestamp(pathname + _suffix)
70 if t_py is None and t_pyc is None:
71 return None
72 code = None
73 if t_py is None or (t_pyc is not None and t_pyc >= t_py):
74 file = pathname + _suffix
75 f = open(file, 'rb')
76 if f.read(4) == imp.get_magic():
77 t = struct.unpack('<I', f.read(4))[0]
78 if t == t_py:
79 code = marshal.load(f)
80 f.close()
81 if code is None:
82 file = pathname + '.py'
83 code = _compile(file, t_py)
84
85 values['__file__'] = file
86 return ispkg, code, values
87