2 /* Module definition and import implementation */
26 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
29 /* Magic word to reject .pyc files generated by other Python versions */
30 /* Change for each incompatible change */
31 /* The value of CR and LF is incorporated so if you ever read or write
32 a .pyc file in text mode the magic number will be wrong; also, the
33 Apple MPW compiler swaps their values, botching string constants */
34 /* XXX Perhaps the magic number should be frozen and a version field
35 added to the .pyc file header? */
36 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
37 #define MAGIC (60717 | ((long)'\r'<<16) | ((long)'\n'<<24))
39 /* Magic word as global; note that _PyImport_Init() can change the
40 value of this global to accommodate for alterations of how the
41 compiler works which are enabled by command line switches. */
42 static long pyc_magic
= MAGIC
;
44 /* See _PyImport_FixupExtension() below */
45 static PyObject
*extensions
= NULL
;
47 /* This table is defined in config.c: */
48 extern struct _inittab _PyImport_Inittab
[];
50 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
52 /* these tables define the module suffixes that Python recognizes */
53 struct filedescr
* _PyImport_Filetab
= NULL
;
56 static const struct filedescr _PyImport_StandardFiletab
[] = {
57 {"/py", "r", PY_SOURCE
},
58 {"/pyc", "rb", PY_COMPILED
},
62 static const struct filedescr _PyImport_StandardFiletab
[] = {
63 {".py", "r", PY_SOURCE
},
65 {".pyw", "r", PY_SOURCE
},
67 {".pyc", "rb", PY_COMPILED
},
72 /* Initialize things */
77 const struct filedescr
*scan
;
78 struct filedescr
*filetab
;
82 /* prepare _PyImport_Filetab: copy entries from
83 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
85 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
87 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
89 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
90 memcpy(filetab
, _PyImport_DynLoadFiletab
,
91 countD
* sizeof(struct filedescr
));
92 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
93 countS
* sizeof(struct filedescr
));
94 filetab
[countD
+ countS
].suffix
= NULL
;
96 _PyImport_Filetab
= filetab
;
98 if (Py_OptimizeFlag
) {
99 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
100 for (; filetab
->suffix
!= NULL
; filetab
++) {
102 if (strcmp(filetab
->suffix
, ".pyc") == 0)
103 filetab
->suffix
= ".pyo";
105 if (strcmp(filetab
->suffix
, "/pyc") == 0)
106 filetab
->suffix
= "/pyo";
111 if (Py_UnicodeFlag
) {
112 /* Fix the pyc_magic so that byte compiled code created
113 using the all-Unicode method doesn't interfere with
114 code created in normal operation mode. */
115 pyc_magic
= MAGIC
+ 1;
122 Py_XDECREF(extensions
);
124 PyMem_DEL(_PyImport_Filetab
);
125 _PyImport_Filetab
= NULL
;
129 /* Locking primitives to prevent parallel imports of the same module
130 in different threads to return with a partially loaded module.
131 These calls are serialized by the global interpreter lock. */
135 #include "pythread.h"
137 static PyThread_type_lock import_lock
= 0;
138 static long import_lock_thread
= -1;
139 static int import_lock_level
= 0;
144 long me
= PyThread_get_thread_ident();
146 return; /* Too bad */
147 if (import_lock
== NULL
)
148 import_lock
= PyThread_allocate_lock();
149 if (import_lock_thread
== me
) {
153 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0)) {
154 PyThreadState
*tstate
= PyEval_SaveThread();
155 PyThread_acquire_lock(import_lock
, 1);
156 PyEval_RestoreThread(tstate
);
158 import_lock_thread
= me
;
159 import_lock_level
= 1;
165 long me
= PyThread_get_thread_ident();
167 return; /* Too bad */
168 if (import_lock_thread
!= me
)
169 Py_FatalError("unlock_import: not holding the import lock");
171 if (import_lock_level
== 0) {
172 import_lock_thread
= -1;
173 PyThread_release_lock(import_lock
);
179 #define lock_import()
180 #define unlock_import()
185 imp_lock_held(PyObject
*self
, PyObject
*args
)
187 if (!PyArg_ParseTuple(args
, ":lock_held"))
190 return PyInt_FromLong(import_lock_thread
!= -1);
192 return PyInt_FromLong(0);
199 PyImport_GetModuleDict(void)
201 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
202 if (interp
->modules
== NULL
)
203 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
204 return interp
->modules
;
208 /* List of names to clear in sys */
209 static char* sys_deletes
[] = {
210 "path", "argv", "ps1", "ps2", "exitfunc",
211 "exc_type", "exc_value", "exc_traceback",
212 "last_type", "last_value", "last_traceback",
216 static char* sys_files
[] = {
217 "stdin", "__stdin__",
218 "stdout", "__stdout__",
219 "stderr", "__stderr__",
224 /* Un-initialize things, as good as we can */
227 PyImport_Cleanup(void)
231 PyObject
*key
, *value
, *dict
;
232 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
233 PyObject
*modules
= interp
->modules
;
236 return; /* Already done */
238 /* Delete some special variables first. These are common
239 places where user values hide and people complain when their
240 destructors fail. Since the modules containing them are
241 deleted *last* of all, they would come too late in the normal
242 destruction order. Sigh. */
244 value
= PyDict_GetItemString(modules
, "__builtin__");
245 if (value
!= NULL
&& PyModule_Check(value
)) {
246 dict
= PyModule_GetDict(value
);
248 PySys_WriteStderr("# clear __builtin__._\n");
249 PyDict_SetItemString(dict
, "_", Py_None
);
251 value
= PyDict_GetItemString(modules
, "sys");
252 if (value
!= NULL
&& PyModule_Check(value
)) {
255 dict
= PyModule_GetDict(value
);
256 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
258 PySys_WriteStderr("# clear sys.%s\n", *p
);
259 PyDict_SetItemString(dict
, *p
, Py_None
);
261 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
263 PySys_WriteStderr("# restore sys.%s\n", *p
);
264 v
= PyDict_GetItemString(dict
, *(p
+1));
267 PyDict_SetItemString(dict
, *p
, v
);
271 /* First, delete __main__ */
272 value
= PyDict_GetItemString(modules
, "__main__");
273 if (value
!= NULL
&& PyModule_Check(value
)) {
275 PySys_WriteStderr("# cleanup __main__\n");
276 _PyModule_Clear(value
);
277 PyDict_SetItemString(modules
, "__main__", Py_None
);
280 /* The special treatment of __builtin__ here is because even
281 when it's not referenced as a module, its dictionary is
282 referenced by almost every module's __builtins__. Since
283 deleting a module clears its dictionary (even if there are
284 references left to it), we need to delete the __builtin__
285 module last. Likewise, we don't delete sys until the very
286 end because it is implicitly referenced (e.g. by print).
288 Also note that we 'delete' modules by replacing their entry
289 in the modules dict with None, rather than really deleting
290 them; this avoids a rehash of the modules dictionary and
291 also marks them as "non existent" so they won't be
294 /* Next, repeatedly delete modules with a reference count of
295 one (skipping __builtin__ and sys) and delete them */
299 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
300 if (value
->ob_refcnt
!= 1)
302 if (PyString_Check(key
) && PyModule_Check(value
)) {
303 name
= PyString_AS_STRING(key
);
304 if (strcmp(name
, "__builtin__") == 0)
306 if (strcmp(name
, "sys") == 0)
310 "# cleanup[1] %s\n", name
);
311 _PyModule_Clear(value
);
312 PyDict_SetItem(modules
, key
, Py_None
);
318 /* Next, delete all modules (still skipping __builtin__ and sys) */
320 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
321 if (PyString_Check(key
) && PyModule_Check(value
)) {
322 name
= PyString_AS_STRING(key
);
323 if (strcmp(name
, "__builtin__") == 0)
325 if (strcmp(name
, "sys") == 0)
328 PySys_WriteStderr("# cleanup[2] %s\n", name
);
329 _PyModule_Clear(value
);
330 PyDict_SetItem(modules
, key
, Py_None
);
334 /* Next, delete sys and __builtin__ (in that order) */
335 value
= PyDict_GetItemString(modules
, "sys");
336 if (value
!= NULL
&& PyModule_Check(value
)) {
338 PySys_WriteStderr("# cleanup sys\n");
339 _PyModule_Clear(value
);
340 PyDict_SetItemString(modules
, "sys", Py_None
);
342 value
= PyDict_GetItemString(modules
, "__builtin__");
343 if (value
!= NULL
&& PyModule_Check(value
)) {
345 PySys_WriteStderr("# cleanup __builtin__\n");
346 _PyModule_Clear(value
);
347 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
350 /* Finally, clear and delete the modules directory */
351 PyDict_Clear(modules
);
352 interp
->modules
= NULL
;
357 /* Helper for pythonrun.c -- return magic number */
360 PyImport_GetMagicNumber(void)
366 /* Magic for extension modules (built-in as well as dynamically
367 loaded). To prevent initializing an extension module more than
368 once, we keep a static dictionary 'extensions' keyed by module name
369 (for built-in modules) or by filename (for dynamically loaded
370 modules), containing these modules. A copy of the module's
371 dictionary is stored by calling _PyImport_FixupExtension()
372 immediately after the module initialization function succeeds. A
373 copy can be retrieved from there by calling
374 _PyImport_FindExtension(). */
377 _PyImport_FixupExtension(char *name
, char *filename
)
379 PyObject
*modules
, *mod
, *dict
, *copy
;
380 if (extensions
== NULL
) {
381 extensions
= PyDict_New();
382 if (extensions
== NULL
)
385 modules
= PyImport_GetModuleDict();
386 mod
= PyDict_GetItemString(modules
, name
);
387 if (mod
== NULL
|| !PyModule_Check(mod
)) {
388 PyErr_Format(PyExc_SystemError
,
389 "_PyImport_FixupExtension: module %.200s not loaded", name
);
392 dict
= PyModule_GetDict(mod
);
395 copy
= PyObject_CallMethod(dict
, "copy", "");
398 PyDict_SetItemString(extensions
, filename
, copy
);
404 _PyImport_FindExtension(char *name
, char *filename
)
406 PyObject
*dict
, *mod
, *mdict
, *result
;
407 if (extensions
== NULL
)
409 dict
= PyDict_GetItemString(extensions
, filename
);
412 mod
= PyImport_AddModule(name
);
415 mdict
= PyModule_GetDict(mod
);
418 result
= PyObject_CallMethod(mdict
, "update", "O", dict
);
423 PySys_WriteStderr("import %s # previously loaded (%s)\n",
429 /* Get the module object corresponding to a module name.
430 First check the modules dictionary if there's one there,
431 if not, create a new one and insert in in the modules dictionary.
432 Because the former action is most common, THIS DOES NOT RETURN A
436 PyImport_AddModule(char *name
)
438 PyObject
*modules
= PyImport_GetModuleDict();
441 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
444 m
= PyModule_New(name
);
447 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
451 Py_DECREF(m
); /* Yes, it still exists, in modules! */
457 /* Execute a code object in a module and return the module object
458 WITH INCREMENTED REFERENCE COUNT */
461 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
463 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
467 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
469 PyObject
*modules
= PyImport_GetModuleDict();
472 m
= PyImport_AddModule(name
);
475 d
= PyModule_GetDict(m
);
476 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
477 if (PyDict_SetItemString(d
, "__builtins__",
478 PyEval_GetBuiltins()) != 0)
481 /* Remember the filename as the __file__ attribute */
483 if (pathname
!= NULL
) {
484 v
= PyString_FromString(pathname
);
489 v
= ((PyCodeObject
*)co
)->co_filename
;
492 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
493 PyErr_Clear(); /* Not important enough to report */
496 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
501 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
502 PyErr_Format(PyExc_ImportError
,
503 "Loaded module %.200s not found in sys.modules",
514 /* Given a pathname for a Python source file, fill a buffer with the
515 pathname for the corresponding compiled file. Return the pathname
516 for the compiled file, or NULL if there's no space in the buffer.
517 Doesn't set an exception. */
520 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
522 size_t len
= strlen(pathname
);
527 /* Treat .pyw as if it were .py. The case of ".pyw" must match
528 that used in _PyImport_StandardFiletab. */
529 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
530 --len
; /* pretend 'w' isn't there */
532 memcpy(buf
, pathname
, len
);
533 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
540 /* Given a pathname for a Python source file, its time of last
541 modification, and a pathname for a compiled file, check whether the
542 compiled file represents the same version of the source. If so,
543 return a FILE pointer for the compiled file, positioned just after
544 the header; if not, return NULL.
545 Doesn't set an exception. */
548 check_compiled_module(char *pathname
, long mtime
, char *cpathname
)
554 fp
= fopen(cpathname
, "rb");
557 magic
= PyMarshal_ReadLongFromFile(fp
);
558 if (magic
!= pyc_magic
) {
560 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
564 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
565 if (pyc_mtime
!= mtime
) {
567 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
572 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
577 /* Read a code object from a file and check it for validity */
579 static PyCodeObject
*
580 read_compiled_module(char *cpathname
, FILE *fp
)
584 co
= PyMarshal_ReadLastObjectFromFile(fp
);
585 /* Ugly: rd_object() may return NULL with or without error */
586 if (co
== NULL
|| !PyCode_Check(co
)) {
587 if (!PyErr_Occurred())
588 PyErr_Format(PyExc_ImportError
,
589 "Non-code object in %.200s", cpathname
);
593 return (PyCodeObject
*)co
;
597 /* Load a module from a compiled file, execute it, and return its
598 module object WITH INCREMENTED REFERENCE COUNT */
601 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
607 magic
= PyMarshal_ReadLongFromFile(fp
);
608 if (magic
!= pyc_magic
) {
609 PyErr_Format(PyExc_ImportError
,
610 "Bad magic number in %.200s", cpathname
);
613 (void) PyMarshal_ReadLongFromFile(fp
);
614 co
= read_compiled_module(cpathname
, fp
);
618 PySys_WriteStderr("import %s # precompiled from %s\n",
620 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
626 /* Parse a source file and return the corresponding code object */
628 static PyCodeObject
*
629 parse_source_module(char *pathname
, FILE *fp
)
634 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
637 co
= PyNode_Compile(n
, pathname
);
644 /* Helper to open a bytecode file for writing in exclusive mode */
647 open_exclusive(char *filename
)
649 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
650 /* Use O_EXCL to avoid a race condition when another process tries to
651 write the same file. When that happens, our open() call fails,
652 which is just fine (since it's only a cache).
653 XXX If the file exists and is writable but the directory is not
654 writable, the file will never be written. Oh well.
657 (void) unlink(filename
);
658 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
660 |O_BINARY
/* necessary for Windows */
666 return fdopen(fd
, "wb");
668 /* Best we can do -- on Windows this can't happen anyway */
669 return fopen(filename
, "wb");
674 /* Write a compiled module to a file, placing the time of last
675 modification of its source into the header.
676 Errors are ignored, if a write error occurs an attempt is made to
680 write_compiled_module(PyCodeObject
*co
, char *cpathname
, long mtime
)
684 fp
= open_exclusive(cpathname
);
688 "# can't create %s\n", cpathname
);
691 PyMarshal_WriteLongToFile(pyc_magic
, fp
);
692 /* First write a 0 for mtime */
693 PyMarshal_WriteLongToFile(0L, fp
);
694 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
697 PySys_WriteStderr("# can't write %s\n", cpathname
);
698 /* Don't keep partial file */
700 (void) unlink(cpathname
);
703 /* Now write the true mtime */
705 PyMarshal_WriteLongToFile(mtime
, fp
);
709 PySys_WriteStderr("# wrote %s\n", cpathname
);
711 PyMac_setfiletype(cpathname
, 'Pyth', 'PYC ');
716 /* Load a source module from a given file and return its module
717 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
718 byte-compiled file, use that instead. */
721 load_source_module(char *name
, char *pathname
, FILE *fp
)
725 char buf
[MAXPATHLEN
+1];
730 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
731 if (mtime
== (time_t)(-1))
733 #if SIZEOF_TIME_T > 4
734 /* Python's .pyc timestamp handling presumes that the timestamp fits
735 in 4 bytes. This will be fine until sometime in the year 2038,
736 when a 4-byte signed time_t will overflow.
739 PyErr_SetString(PyExc_OverflowError
,
740 "modification time overflows a 4 byte field");
744 cpathname
= make_compiled_pathname(pathname
, buf
,
745 (size_t)MAXPATHLEN
+ 1);
746 if (cpathname
!= NULL
&&
747 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
748 co
= read_compiled_module(cpathname
, fpc
);
753 PySys_WriteStderr("import %s # precompiled from %s\n",
755 pathname
= cpathname
;
758 co
= parse_source_module(pathname
, fp
);
762 PySys_WriteStderr("import %s # from %s\n",
764 write_compiled_module(co
, cpathname
, mtime
);
766 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
774 static PyObject
*load_module(char *, FILE *, char *, int);
775 static struct filedescr
*find_module(char *, PyObject
*,
776 char *, size_t, FILE **);
777 static struct _frozen
*find_frozen(char *name
);
779 /* Load a package and return its module object WITH INCREMENTED
783 load_package(char *name
, char *pathname
)
785 PyObject
*m
, *d
, *file
, *path
;
787 char buf
[MAXPATHLEN
+1];
789 struct filedescr
*fdp
;
791 m
= PyImport_AddModule(name
);
795 PySys_WriteStderr("import %s # directory %s\n",
797 d
= PyModule_GetDict(m
);
798 file
= PyString_FromString(pathname
);
801 path
= Py_BuildValue("[O]", file
);
806 err
= PyDict_SetItemString(d
, "__file__", file
);
808 err
= PyDict_SetItemString(d
, "__path__", path
);
814 fdp
= find_module("__init__", path
, buf
, sizeof(buf
), &fp
);
816 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
823 m
= load_module(name
, fp
, buf
, fdp
->type
);
833 /* Helper to test for built-in module */
836 is_builtin(char *name
)
839 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
840 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
841 if (PyImport_Inittab
[i
].initfunc
== NULL
)
851 /* Search the path (default sys.path) for a module. Return the
852 corresponding filedescr struct, and (via return arguments) the
853 pathname and an open file. Return NULL if the module is not found. */
856 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
860 static int case_ok(char *, int, int, char *);
861 static int find_init_module(char *); /* Forward */
863 static struct filedescr
*
864 find_module(char *realname
, PyObject
*path
, char *buf
, size_t buflen
,
870 struct filedescr
*fdp
= NULL
;
875 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
876 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
877 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
878 char name
[MAXPATHLEN
+1];
880 if (strlen(realname
) > MAXPATHLEN
) {
881 PyErr_SetString(PyExc_OverflowError
, "module name is too long");
884 strcpy(name
, realname
);
886 if (path
!= NULL
&& PyString_Check(path
)) {
887 /* Submodule of "frozen" package:
888 Set name to the fullname, path to NULL
889 and continue as "usual" */
890 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
891 PyErr_SetString(PyExc_ImportError
,
892 "full frozen module name too long");
895 strcpy(buf
, PyString_AsString(path
));
902 if (is_builtin(name
)) {
906 if ((f
= find_frozen(name
)) != NULL
) {
912 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
918 path
= PySys_GetObject("path");
920 if (path
== NULL
|| !PyList_Check(path
)) {
921 PyErr_SetString(PyExc_ImportError
,
922 "sys.path must be a list of directory names");
925 npath
= PyList_Size(path
);
926 namelen
= strlen(name
);
927 for (i
= 0; i
< npath
; i
++) {
928 PyObject
*v
= PyList_GetItem(path
, i
);
929 if (!PyString_Check(v
))
931 len
= PyString_Size(v
);
932 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
)
933 continue; /* Too long */
934 strcpy(buf
, PyString_AsString(v
));
935 if (strlen(buf
) != len
)
936 continue; /* v contains '\0' */
938 #ifdef INTERN_STRINGS
940 ** Speedup: each sys.path item is interned, and
941 ** FindResourceModule remembers which items refer to
942 ** folders (so we don't have to bother trying to look
943 ** into them for resources).
945 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
946 v
= PyList_GET_ITEM(path
, i
);
948 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
949 static struct filedescr resfiledescr
=
950 {"", "", PY_RESOURCE
};
952 return &resfiledescr
;
954 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
955 static struct filedescr resfiledescr
=
956 {"", "", PY_CODERESOURCE
};
958 return &resfiledescr
;
961 if (len
> 0 && buf
[len
-1] != SEP
963 && buf
[len
-1] != ALTSEP
967 strcpy(buf
+len
, name
);
970 /* Check for package import (buf holds a directory name,
971 and there's an __init__ module in that directory */
973 if (stat(buf
, &statbuf
) == 0 && /* it exists */
974 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
975 find_init_module(buf
) && /* it has __init__.py */
976 case_ok(buf
, len
, namelen
, name
)) /* and case matches */
979 /* XXX How are you going to test for directories? */
982 static struct filedescr fd
= {"", "", PKG_DIRECTORY
};
984 if (find_init_module(buf
))
991 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
994 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
995 strcpy(buf
+len
, fdp
->suffix
);
996 if (Py_VerboseFlag
> 1)
997 PySys_WriteStderr("# trying %s\n", buf
);
998 #endif /* !macintosh */
999 fp
= fopen(buf
, fdp
->mode
);
1001 if (case_ok(buf
, len
, namelen
, name
))
1003 else { /* continue search */
1013 PyErr_Format(PyExc_ImportError
,
1014 "No module named %.200s", name
);
1021 /* case_ok(char* buf, int len, int namelen, char* name)
1022 * The arguments here are tricky, best shown by example:
1023 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1025 * |--------------------- buf ---------------------|
1026 * |------------------- len ------------------|
1027 * |------ name -------|
1028 * |----- namelen -----|
1029 * buf is the full path, but len only counts up to (& exclusive of) the
1030 * extension. name is the module name, also exclusive of extension.
1032 * We've already done a successful stat() or fopen() on buf, so know that
1033 * there's some match, possibly case-insensitive.
1035 * case_ok() is to return 1 if there's a case-sensitive match for
1036 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1039 * case_ok() is used to implement case-sensitive import semantics even
1040 * on platforms with case-insensitive filesystems. It's trivial to implement
1041 * for case-sensitive filesystems. It's pretty much a cross-platform
1042 * nightmare for systems with case-insensitive filesystems.
1045 /* First we may need a pile of platform-specific header files; the sequence
1046 * of #if's here should match the sequence in the body of case_ok().
1048 #if defined(MS_WIN32) || defined(__CYGWIN__)
1049 #include <windows.h>
1051 #include <sys/cygwin.h>
1054 #elif defined(DJGPP)
1057 #elif defined(macintosh)
1058 #include <TextUtils.h>
1060 #include "TFileSpec.h" /* for Path2FSSpec() */
1063 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1064 #include <sys/types.h>
1070 case_ok(char *buf
, int len
, int namelen
, char *name
)
1072 /* Pick a platform-specific implementation; the sequence of #if's here should
1073 * match the sequence just above.
1076 /* MS_WIN32 || __CYGWIN__ */
1077 #if defined(MS_WIN32) || defined(__CYGWIN__)
1078 WIN32_FIND_DATA data
;
1081 char tempbuf
[MAX_PATH
];
1084 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1088 cygwin32_conv_to_win32_path(buf
, tempbuf
);
1089 h
= FindFirstFile(tempbuf
, &data
);
1091 h
= FindFirstFile(buf
, &data
);
1093 if (h
== INVALID_HANDLE_VALUE
) {
1094 PyErr_Format(PyExc_NameError
,
1095 "Can't find file for module %.100s\n(filename %.300s)",
1100 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1103 #elif defined(DJGPP)
1107 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1110 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1112 PyErr_Format(PyExc_NameError
,
1113 "Can't find file for module %.100s\n(filename %.300s)",
1117 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1120 #elif defined(macintosh)
1124 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1128 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1130 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1131 the way, which is fine for all directories, but here we need
1132 the original name of the alias file (say, Dlg.ppc.slb, not
1133 toolboxmodules.ppc.slb). */
1135 err
= Path2FSSpec(buf
, &fss
);
1137 colon
= strrchr(buf
, ':'); /* find filename */
1139 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1140 Pstring(colon
+1), &fss
);
1142 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1147 PyErr_Format(PyExc_NameError
,
1148 "Can't find file for module %.100s\n(filename %.300s)",
1152 return fss
.name
[0] >= namelen
&&
1153 strncmp(name
, (char *)fss
.name
+1, namelen
) == 0;
1155 /* new-fangled macintosh (macosx) */
1156 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1159 char dirname
[MAXPATHLEN
+ 1];
1160 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1162 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1165 /* Copy the dir component into dirname; substitute "." if empty */
1171 assert(dirlen
<= MAXPATHLEN
);
1172 memcpy(dirname
, buf
, dirlen
);
1173 dirname
[dirlen
] = '\0';
1175 /* Open the directory and search the entries for an exact match. */
1176 dirp
= opendir(dirname
);
1178 char *nameWithExt
= buf
+ len
- namelen
;
1179 while ((dp
= readdir(dirp
)) != NULL
) {
1181 #ifdef _DIRENT_HAVE_D_NAMELEN
1186 if (thislen
>= namelen
&&
1187 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1188 (void)closedir(dirp
);
1189 return 1; /* Found */
1192 (void)closedir(dirp
);
1194 return 0 ; /* Not found */
1196 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1205 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1207 find_init_module(char *buf
)
1209 const size_t save_len
= strlen(buf
);
1210 size_t i
= save_len
;
1211 char *pname
; /* pointer to start of __init__ */
1212 struct stat statbuf
;
1214 /* For calling case_ok(buf, len, namelen, name):
1215 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1217 * |--------------------- buf ---------------------|
1218 * |------------------- len ------------------|
1219 * |------ name -------|
1220 * |----- namelen -----|
1222 if (save_len
+ 13 >= MAXPATHLEN
)
1226 strcpy(pname
, "__init__.py");
1227 if (stat(buf
, &statbuf
) == 0) {
1229 save_len
+ 9, /* len("/__init__") */
1230 8, /* len("__init__") */
1232 buf
[save_len
] = '\0';
1237 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1238 if (stat(buf
, &statbuf
) == 0) {
1240 save_len
+ 9, /* len("/__init__") */
1241 8, /* len("__init__") */
1243 buf
[save_len
] = '\0';
1247 buf
[save_len
] = '\0';
1255 find_init_module(buf
)
1258 int save_len
= strlen(buf
);
1261 if (save_len
+ 13 >= MAXPATHLEN
)
1264 strcpy(buf
+i
, "__init__/py");
1266 buf
[save_len
] = '\0';
1270 if (Py_OptimizeFlag
)
1275 buf
[save_len
] = '\0';
1278 buf
[save_len
] = '\0';
1283 #endif /* HAVE_STAT */
1286 static int init_builtin(char *); /* Forward */
1288 /* Load an external module using the default search path and return
1289 its module object WITH INCREMENTED REFERENCE COUNT */
1292 load_module(char *name
, FILE *fp
, char *buf
, int type
)
1298 /* First check that there's an open file (if we need one) */
1303 PyErr_Format(PyExc_ValueError
,
1304 "file object required for import (type code %d)",
1313 m
= load_source_module(name
, buf
, fp
);
1317 m
= load_compiled_module(name
, buf
, fp
);
1320 #ifdef HAVE_DYNAMIC_LOADING
1322 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1328 m
= PyMac_LoadResourceModule(name
, buf
);
1330 case PY_CODERESOURCE
:
1331 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1336 m
= load_package(name
, buf
);
1341 if (buf
!= NULL
&& buf
[0] != '\0')
1343 if (type
== C_BUILTIN
)
1344 err
= init_builtin(name
);
1346 err
= PyImport_ImportFrozenModule(name
);
1350 PyErr_Format(PyExc_ImportError
,
1351 "Purported %s module %.200s not found",
1353 "builtin" : "frozen",
1357 modules
= PyImport_GetModuleDict();
1358 m
= PyDict_GetItemString(modules
, name
);
1362 "%s module %.200s not properly initialized",
1364 "builtin" : "frozen",
1372 PyErr_Format(PyExc_ImportError
,
1373 "Don't know how to import %.200s (type code %d)",
1383 /* Initialize a built-in module.
1384 Return 1 for succes, 0 if the module is not found, and -1 with
1385 an exception set if the initialization failed. */
1388 init_builtin(char *name
)
1393 if ((mod
= _PyImport_FindExtension(name
, name
)) != NULL
)
1396 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1397 if (strcmp(name
, p
->name
) == 0) {
1398 if (p
->initfunc
== NULL
) {
1399 PyErr_Format(PyExc_ImportError
,
1400 "Cannot re-init internal module %.200s",
1405 PySys_WriteStderr("import %s # builtin\n", name
);
1407 if (PyErr_Occurred())
1409 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1418 /* Frozen modules */
1420 static struct _frozen
*
1421 find_frozen(char *name
)
1425 for (p
= PyImport_FrozenModules
; ; p
++) {
1426 if (p
->name
== NULL
)
1428 if (strcmp(p
->name
, name
) == 0)
1435 get_frozen_object(char *name
)
1437 struct _frozen
*p
= find_frozen(name
);
1441 PyErr_Format(PyExc_ImportError
,
1442 "No such frozen object named %.200s",
1449 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1452 /* Initialize a frozen module.
1453 Return 1 for succes, 0 if the module is not found, and -1 with
1454 an exception set if the initialization failed.
1455 This function is also used from frozenmain.c */
1458 PyImport_ImportFrozenModule(char *name
)
1460 struct _frozen
*p
= find_frozen(name
);
1469 ispackage
= (size
< 0);
1473 PySys_WriteStderr("import %s # frozen%s\n",
1474 name
, ispackage
? " package" : "");
1475 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1478 if (!PyCode_Check(co
)) {
1480 PyErr_Format(PyExc_TypeError
,
1481 "frozen object %.200s is not a code object",
1486 /* Set __path__ to the package name */
1489 m
= PyImport_AddModule(name
);
1492 d
= PyModule_GetDict(m
);
1493 s
= PyString_InternFromString(name
);
1496 err
= PyDict_SetItemString(d
, "__path__", s
);
1501 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1510 /* Import a module, either built-in, frozen, or external, and return
1511 its module object WITH INCREMENTED REFERENCE COUNT */
1514 PyImport_ImportModule(char *name
)
1519 pname
= PyString_FromString(name
);
1520 result
= PyImport_Import(pname
);
1525 /* Forward declarations for helper routines */
1526 static PyObject
*get_parent(PyObject
*globals
, char *buf
, int *p_buflen
);
1527 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1528 char **p_name
, char *buf
, int *p_buflen
);
1529 static int mark_miss(char *name
);
1530 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1531 char *buf
, int buflen
, int recursive
);
1532 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1534 /* The Magnum Opus of dotted-name import :-) */
1537 import_module_ex(char *name
, PyObject
*globals
, PyObject
*locals
,
1540 char buf
[MAXPATHLEN
+1];
1542 PyObject
*parent
, *head
, *next
, *tail
;
1544 parent
= get_parent(globals
, buf
, &buflen
);
1548 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1555 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1564 if (fromlist
!= NULL
) {
1565 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1569 if (fromlist
== NULL
) {
1575 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1584 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
1589 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1595 get_parent(PyObject
*globals
, char *buf
, int *p_buflen
)
1597 static PyObject
*namestr
= NULL
;
1598 static PyObject
*pathstr
= NULL
;
1599 PyObject
*modname
, *modpath
, *modules
, *parent
;
1601 if (globals
== NULL
|| !PyDict_Check(globals
))
1604 if (namestr
== NULL
) {
1605 namestr
= PyString_InternFromString("__name__");
1606 if (namestr
== NULL
)
1609 if (pathstr
== NULL
) {
1610 pathstr
= PyString_InternFromString("__path__");
1611 if (pathstr
== NULL
)
1617 modname
= PyDict_GetItem(globals
, namestr
);
1618 if (modname
== NULL
|| !PyString_Check(modname
))
1621 modpath
= PyDict_GetItem(globals
, pathstr
);
1622 if (modpath
!= NULL
) {
1623 int len
= PyString_GET_SIZE(modname
);
1624 if (len
> MAXPATHLEN
) {
1625 PyErr_SetString(PyExc_ValueError
,
1626 "Module name too long");
1629 strcpy(buf
, PyString_AS_STRING(modname
));
1633 char *start
= PyString_AS_STRING(modname
);
1634 char *lastdot
= strrchr(start
, '.');
1636 if (lastdot
== NULL
)
1638 len
= lastdot
- start
;
1639 if (len
>= MAXPATHLEN
) {
1640 PyErr_SetString(PyExc_ValueError
,
1641 "Module name too long");
1644 strncpy(buf
, start
, len
);
1649 modules
= PyImport_GetModuleDict();
1650 parent
= PyDict_GetItemString(modules
, buf
);
1654 /* We expect, but can't guarantee, if parent != None, that:
1655 - parent.__name__ == buf
1656 - parent.__dict__ is globals
1657 If this is violated... Who cares? */
1660 /* altmod is either None or same as mod */
1662 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
1665 char *name
= *p_name
;
1666 char *dot
= strchr(name
, '.');
1680 PyErr_SetString(PyExc_ValueError
,
1681 "Empty module name");
1685 p
= buf
+ *p_buflen
;
1688 if (p
+len
-buf
>= MAXPATHLEN
) {
1689 PyErr_SetString(PyExc_ValueError
,
1690 "Module name too long");
1693 strncpy(p
, name
, len
);
1695 *p_buflen
= p
+len
-buf
;
1697 result
= import_submodule(mod
, p
, buf
);
1698 if (result
== Py_None
&& altmod
!= mod
) {
1700 /* Here, altmod must be None and mod must not be None */
1701 result
= import_submodule(altmod
, p
, p
);
1702 if (result
!= NULL
&& result
!= Py_None
) {
1703 if (mark_miss(buf
) != 0) {
1707 strncpy(buf
, name
, len
);
1715 if (result
== Py_None
) {
1717 PyErr_Format(PyExc_ImportError
,
1718 "No module named %.200s", name
);
1726 mark_miss(char *name
)
1728 PyObject
*modules
= PyImport_GetModuleDict();
1729 return PyDict_SetItemString(modules
, name
, Py_None
);
1733 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, int buflen
,
1738 if (!PyObject_HasAttrString(mod
, "__path__"))
1741 for (i
= 0; ; i
++) {
1742 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
1745 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1751 if (!PyString_Check(item
)) {
1752 PyErr_SetString(PyExc_TypeError
,
1753 "Item in ``from list'' not a string");
1757 if (PyString_AS_STRING(item
)[0] == '*') {
1760 /* See if the package defines __all__ */
1762 continue; /* Avoid endless recursion */
1763 all
= PyObject_GetAttrString(mod
, "__all__");
1767 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
1773 hasit
= PyObject_HasAttr(mod
, item
);
1775 char *subname
= PyString_AS_STRING(item
);
1778 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
1779 PyErr_SetString(PyExc_ValueError
,
1780 "Module name too long");
1787 submod
= import_submodule(mod
, subname
, buf
);
1789 if (submod
== NULL
) {
1801 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
1803 PyObject
*modules
= PyImport_GetModuleDict();
1804 PyObject
*m
, *res
= NULL
;
1807 if mod == None: subname == fullname
1808 else: mod.__name__ + "." + subname == fullname
1811 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
1816 char buf
[MAXPATHLEN
+1];
1817 struct filedescr
*fdp
;
1823 path
= PyObject_GetAttrString(mod
, "__path__");
1832 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1835 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
1841 m
= load_module(fullname
, fp
, buf
, fdp
->type
);
1844 if (mod
!= Py_None
) {
1845 /* Irrespective of the success of this load, make a
1846 reference to it in the parent package module.
1847 A copy gets saved in the modules dictionary
1848 under the full name, so get a reference from
1849 there, if need be. (The exception is when
1850 the load failed with a SyntaxError -- then
1851 there's no trace in sys.modules. In that case,
1852 of course, do nothing extra.) */
1855 res
= PyDict_GetItemString(modules
, fullname
);
1857 PyObject_SetAttrString(mod
, subname
, res
) < 0) {
1868 /* Re-import a module of any kind and return its module object, WITH
1869 INCREMENTED REFERENCE COUNT */
1872 PyImport_ReloadModule(PyObject
*m
)
1874 PyObject
*modules
= PyImport_GetModuleDict();
1875 PyObject
*path
= NULL
;
1876 char *name
, *subname
;
1877 char buf
[MAXPATHLEN
+1];
1878 struct filedescr
*fdp
;
1881 if (m
== NULL
|| !PyModule_Check(m
)) {
1882 PyErr_SetString(PyExc_TypeError
,
1883 "reload() argument must be module");
1886 name
= PyModule_GetName(m
);
1889 if (m
!= PyDict_GetItemString(modules
, name
)) {
1890 PyErr_Format(PyExc_ImportError
,
1891 "reload(): module %.200s not in sys.modules",
1895 subname
= strrchr(name
, '.');
1896 if (subname
== NULL
)
1899 PyObject
*parentname
, *parent
;
1900 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
1901 if (parentname
== NULL
)
1903 parent
= PyDict_GetItem(modules
, parentname
);
1904 Py_DECREF(parentname
);
1905 if (parent
== NULL
) {
1906 PyErr_Format(PyExc_ImportError
,
1907 "reload(): parent %.200s not in sys.modules",
1912 path
= PyObject_GetAttrString(parent
, "__path__");
1917 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1921 m
= load_module(name
, fp
, buf
, fdp
->type
);
1928 /* Higher-level import emulator which emulates the "import" statement
1929 more accurately -- it invokes the __import__() function from the
1930 builtins of the current globals. This means that the import is
1931 done using whatever import hooks are installed in the current
1932 environment, e.g. by "rexec".
1933 A dummy list ["__doc__"] is passed as the 4th argument so that
1934 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1935 will return <module "gencache"> instead of <module "win32com">. */
1938 PyImport_Import(PyObject
*module_name
)
1940 static PyObject
*silly_list
= NULL
;
1941 static PyObject
*builtins_str
= NULL
;
1942 static PyObject
*import_str
= NULL
;
1943 PyObject
*globals
= NULL
;
1944 PyObject
*import
= NULL
;
1945 PyObject
*builtins
= NULL
;
1948 /* Initialize constant string objects */
1949 if (silly_list
== NULL
) {
1950 import_str
= PyString_InternFromString("__import__");
1951 if (import_str
== NULL
)
1953 builtins_str
= PyString_InternFromString("__builtins__");
1954 if (builtins_str
== NULL
)
1956 silly_list
= Py_BuildValue("[s]", "__doc__");
1957 if (silly_list
== NULL
)
1961 /* Get the builtins from current globals */
1962 globals
= PyEval_GetGlobals();
1963 if (globals
!= NULL
) {
1965 builtins
= PyObject_GetItem(globals
, builtins_str
);
1966 if (builtins
== NULL
)
1970 /* No globals -- use standard builtins, and fake globals */
1973 builtins
= PyImport_ImportModuleEx("__builtin__",
1975 if (builtins
== NULL
)
1977 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
1978 if (globals
== NULL
)
1982 /* Get the __import__ function from the builtins */
1983 if (PyDict_Check(builtins
)) {
1984 import
= PyObject_GetItem(builtins
, import_str
);
1986 PyErr_SetObject(PyExc_KeyError
, import_str
);
1989 import
= PyObject_GetAttr(builtins
, import_str
);
1993 /* Call the _import__ function with the proper argument list */
1994 r
= PyObject_CallFunction(import
, "OOOO",
1995 module_name
, globals
, globals
, silly_list
);
1998 Py_XDECREF(globals
);
1999 Py_XDECREF(builtins
);
2006 /* Module 'imp' provides Python access to the primitives used for
2011 imp_get_magic(PyObject
*self
, PyObject
*args
)
2015 if (!PyArg_ParseTuple(args
, ":get_magic"))
2017 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2018 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2019 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2020 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2022 return PyString_FromStringAndSize(buf
, 4);
2026 imp_get_suffixes(PyObject
*self
, PyObject
*args
)
2029 struct filedescr
*fdp
;
2031 if (!PyArg_ParseTuple(args
, ":get_suffixes"))
2033 list
= PyList_New(0);
2036 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2037 PyObject
*item
= Py_BuildValue("ssi",
2038 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2043 if (PyList_Append(list
, item
) < 0) {
2054 call_find_module(char *name
, PyObject
*path
)
2056 extern int fclose(FILE *);
2057 PyObject
*fob
, *ret
;
2058 struct filedescr
*fdp
;
2059 char pathname
[MAXPATHLEN
+1];
2063 if (path
== Py_None
)
2065 fdp
= find_module(name
, path
, pathname
, MAXPATHLEN
+1, &fp
);
2069 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2079 ret
= Py_BuildValue("Os(ssi)",
2080 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2086 imp_find_module(PyObject
*self
, PyObject
*args
)
2089 PyObject
*path
= NULL
;
2090 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2092 return call_find_module(name
, path
);
2096 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2101 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2103 ret
= init_builtin(name
);
2110 m
= PyImport_AddModule(name
);
2116 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2121 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2123 ret
= PyImport_ImportFrozenModule(name
);
2130 m
= PyImport_AddModule(name
);
2136 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2140 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2142 return get_frozen_object(name
);
2146 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2149 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2151 return PyInt_FromLong(is_builtin(name
));
2155 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2159 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2161 p
= find_frozen(name
);
2162 return PyInt_FromLong((long) (p
== NULL
? 0 : p
->size
));
2166 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2170 fp
= fopen(pathname
, mode
);
2172 PyErr_SetFromErrno(PyExc_IOError
);
2175 fp
= PyFile_AsFile(fob
);
2177 PyErr_SetString(PyExc_ValueError
,
2178 "bad/closed file object");
2184 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2188 PyObject
*fob
= NULL
;
2191 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2192 &PyFile_Type
, &fob
))
2194 fp
= get_file(pathname
, fob
, "rb");
2197 m
= load_compiled_module(name
, pathname
, fp
);
2203 #ifdef HAVE_DYNAMIC_LOADING
2206 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2210 PyObject
*fob
= NULL
;
2213 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2214 &PyFile_Type
, &fob
))
2217 fp
= get_file(pathname
, fob
, "r");
2221 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2225 #endif /* HAVE_DYNAMIC_LOADING */
2228 imp_load_source(PyObject
*self
, PyObject
*args
)
2232 PyObject
*fob
= NULL
;
2235 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2236 &PyFile_Type
, &fob
))
2238 fp
= get_file(pathname
, fob
, "r");
2241 m
= load_source_module(name
, pathname
, fp
);
2249 imp_load_resource(PyObject
*self
, PyObject
*args
)
2255 if (!PyArg_ParseTuple(args
, "ss:load_resource", &name
, &pathname
))
2257 m
= PyMac_LoadResourceModule(name
, pathname
);
2260 #endif /* macintosh */
2263 imp_load_module(PyObject
*self
, PyObject
*args
)
2268 char *suffix
; /* Unused */
2273 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2274 &name
, &fob
, &pathname
,
2275 &suffix
, &mode
, &type
))
2277 if (*mode
&& (*mode
!= 'r' || strchr(mode
, '+') != NULL
)) {
2278 PyErr_Format(PyExc_ValueError
,
2279 "invalid file open mode %.200s", mode
);
2285 if (!PyFile_Check(fob
)) {
2286 PyErr_SetString(PyExc_ValueError
,
2287 "load_module arg#2 should be a file or None");
2290 fp
= get_file(pathname
, fob
, mode
);
2294 return load_module(name
, fp
, pathname
, type
);
2298 imp_load_package(PyObject
*self
, PyObject
*args
)
2302 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2304 return load_package(name
, pathname
);
2308 imp_new_module(PyObject
*self
, PyObject
*args
)
2311 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2313 return PyModule_New(name
);
2318 static char doc_imp
[] = "\
2319 This module provides the components needed to build your own\n\
2320 __import__ function. Undocumented functions are obsolete.\n\
2323 static char doc_find_module
[] = "\
2324 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2325 Search for a module. If path is omitted or None, search for a\n\
2326 built-in, frozen or special module and continue search in sys.path.\n\
2327 The module name cannot contain '.'; to search for a submodule of a\n\
2328 package, pass the submodule name and the package's __path__.\
2331 static char doc_load_module
[] = "\
2332 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2333 Load a module, given information returned by find_module().\n\
2334 The module name must include the full package name, if any.\
2337 static char doc_get_magic
[] = "\
2338 get_magic() -> string\n\
2339 Return the magic number for .pyc or .pyo files.\
2342 static char doc_get_suffixes
[] = "\
2343 get_suffixes() -> [(suffix, mode, type), ...]\n\
2344 Return a list of (suffix, mode, type) tuples describing the files\n\
2345 that find_module() looks for.\
2348 static char doc_new_module
[] = "\
2349 new_module(name) -> module\n\
2350 Create a new module. Do not enter it in sys.modules.\n\
2351 The module name must include the full package name, if any.\
2354 static char doc_lock_held
[] = "\
2355 lock_held() -> 0 or 1\n\
2356 Return 1 if the import lock is currently held.\n\
2357 On platforms without threads, return 0.\
2360 static PyMethodDef imp_methods
[] = {
2361 {"find_module", imp_find_module
, 1, doc_find_module
},
2362 {"get_magic", imp_get_magic
, 1, doc_get_magic
},
2363 {"get_suffixes", imp_get_suffixes
, 1, doc_get_suffixes
},
2364 {"load_module", imp_load_module
, 1, doc_load_module
},
2365 {"new_module", imp_new_module
, 1, doc_new_module
},
2366 {"lock_held", imp_lock_held
, 1, doc_lock_held
},
2367 /* The rest are obsolete */
2368 {"get_frozen_object", imp_get_frozen_object
, 1},
2369 {"init_builtin", imp_init_builtin
, 1},
2370 {"init_frozen", imp_init_frozen
, 1},
2371 {"is_builtin", imp_is_builtin
, 1},
2372 {"is_frozen", imp_is_frozen
, 1},
2373 {"load_compiled", imp_load_compiled
, 1},
2374 #ifdef HAVE_DYNAMIC_LOADING
2375 {"load_dynamic", imp_load_dynamic
, 1},
2377 {"load_package", imp_load_package
, 1},
2379 {"load_resource", imp_load_resource
, 1},
2381 {"load_source", imp_load_source
, 1},
2382 {NULL
, NULL
} /* sentinel */
2386 setint(PyObject
*d
, char *name
, int value
)
2391 v
= PyInt_FromLong((long)value
);
2392 err
= PyDict_SetItemString(d
, name
, v
);
2402 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2403 NULL
, PYTHON_API_VERSION
);
2404 d
= PyModule_GetDict(m
);
2406 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2407 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2408 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2409 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2410 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2411 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2412 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2413 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2414 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2421 /* API for embedding applications that want to add their own entries
2422 to the table of built-in modules. This should normally be called
2423 *before* Py_Initialize(). When the table resize fails, -1 is
2424 returned and the existing table is unchanged.
2426 After a similar function by Just van Rossum. */
2429 PyImport_ExtendInittab(struct _inittab
*newtab
)
2431 static struct _inittab
*our_copy
= NULL
;
2435 /* Count the number of entries in both tables */
2436 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2439 return 0; /* Nothing to do */
2440 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2443 /* Allocate new memory for the combined table */
2445 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
2449 /* Copy the tables into the new memory */
2450 if (our_copy
!= PyImport_Inittab
)
2451 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2452 PyImport_Inittab
= our_copy
= p
;
2453 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2458 /* Shorthand to add a single entry given a name and a function */
2461 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
2463 struct _inittab newtab
[2];
2465 memset(newtab
, '\0', sizeof newtab
);
2467 newtab
[0].name
= name
;
2468 newtab
[0].initfunc
= initfunc
;
2470 return PyImport_ExtendInittab(newtab
);