1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Module definition and import implementation */
52 /* We expect that stat exists on most systems.
53 It's confirmed on Unix, Mac and Windows.
54 If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
55 #ifndef DONT_HAVE_STAT
58 #ifndef DONT_HAVE_SYS_TYPES_H
59 #include <sys/types.h>
61 #ifndef DONT_HAVE_SYS_STAT_H
65 #if defined(PYCC_VACPP)
66 /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
67 #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
71 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
77 extern long PyOS_GetLastModificationTime(); /* In getmtime.c */
79 /* Magic word to reject .pyc files generated by other Python versions */
80 /* Change for each incompatible change */
81 /* The value of CR and LF is incorporated so if you ever read or write
82 a .pyc file in text mode the magic number will be wrong; also, the
83 Apple MPW compiler swaps their values, botching string constants */
84 /* XXX Perhaps the magic number should be frozen and a version field
85 added to the .pyc file header? */
86 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
87 #define MAGIC (20121 | ((long)'\r'<<16) | ((long)'\n'<<24))
89 /* See _PyImport_FixupExtension() below */
90 static PyObject
*extensions
= NULL
;
92 /* This table is defined in config.c: */
93 extern struct _inittab _PyImport_Inittab
[];
95 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
97 /* these tables define the module suffixes that Python recognizes */
98 struct filedescr
* _PyImport_Filetab
= NULL
;
99 static const struct filedescr _PyImport_StandardFiletab
[] = {
100 {".py", "r", PY_SOURCE
},
101 {".pyc", "rb", PY_COMPILED
},
105 /* Initialize things */
110 const struct filedescr
*scan
;
111 struct filedescr
*filetab
;
115 /* prepare _PyImport_Filetab: copy entries from
116 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
118 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
120 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
122 filetab
= malloc((countD
+ countS
+ 1) * sizeof(struct filedescr
));
123 memcpy(filetab
, _PyImport_DynLoadFiletab
,
124 countD
* sizeof(struct filedescr
));
125 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
126 countS
* sizeof(struct filedescr
));
127 filetab
[countD
+ countS
].suffix
= NULL
;
129 _PyImport_Filetab
= filetab
;
131 if (Py_OptimizeFlag
) {
132 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
133 for (; filetab
->suffix
!= NULL
; filetab
++) {
134 if (strcmp(filetab
->suffix
, ".pyc") == 0)
135 filetab
->suffix
= ".pyo";
143 Py_XDECREF(extensions
);
148 /* Locking primitives to prevent parallel imports of the same module
149 in different threads to return with a partially loaded module.
150 These calls are serialized by the global interpreter lock. */
154 #include "pythread.h"
156 static PyThread_type_lock import_lock
= 0;
157 static long import_lock_thread
= -1;
158 static int import_lock_level
= 0;
163 long me
= PyThread_get_thread_ident();
165 return; /* Too bad */
166 if (import_lock
== NULL
)
167 import_lock
= PyThread_allocate_lock();
168 if (import_lock_thread
== me
) {
172 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0)) {
173 PyThreadState
*tstate
= PyEval_SaveThread();
174 PyThread_acquire_lock(import_lock
, 1);
175 PyEval_RestoreThread(tstate
);
177 import_lock_thread
= me
;
178 import_lock_level
= 1;
184 long me
= PyThread_get_thread_ident();
186 return; /* Too bad */
187 if (import_lock_thread
!= me
)
188 Py_FatalError("unlock_import: not holding the import lock");
190 if (import_lock_level
== 0) {
191 import_lock_thread
= -1;
192 PyThread_release_lock(import_lock
);
198 #define lock_import()
199 #define unlock_import()
206 PyImport_GetModuleDict()
208 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
209 if (interp
->modules
== NULL
)
210 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
211 return interp
->modules
;
215 /* List of names to clear in sys */
216 static char* sys_deletes
[] = {
217 "path", "argv", "ps1", "ps2", "exitfunc",
218 "exc_type", "exc_value", "exc_traceback",
219 "last_type", "last_value", "last_traceback",
223 static char* sys_files
[] = {
224 "stdin", "__stdin__",
225 "stdout", "__stdout__",
226 "stderr", "__stderr__",
231 /* Un-initialize things, as good as we can */
238 PyObject
*key
, *value
, *dict
;
239 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
240 PyObject
*modules
= interp
->modules
;
243 return; /* Already done */
245 /* Delete some special variables first. These are common
246 places where user values hide and people complain when their
247 destructors fail. Since the modules containing them are
248 deleted *last* of all, they would come too late in the normal
249 destruction order. Sigh. */
251 value
= PyDict_GetItemString(modules
, "__builtin__");
252 if (value
!= NULL
&& PyModule_Check(value
)) {
253 dict
= PyModule_GetDict(value
);
255 PySys_WriteStderr("# clear __builtin__._\n");
256 PyDict_SetItemString(dict
, "_", Py_None
);
258 value
= PyDict_GetItemString(modules
, "sys");
259 if (value
!= NULL
&& PyModule_Check(value
)) {
262 dict
= PyModule_GetDict(value
);
263 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
265 PySys_WriteStderr("# clear sys.%s\n", *p
);
266 PyDict_SetItemString(dict
, *p
, Py_None
);
268 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
270 PySys_WriteStderr("# restore sys.%s\n", *p
);
271 v
= PyDict_GetItemString(dict
, *(p
+1));
274 PyDict_SetItemString(dict
, *p
, v
);
278 /* First, delete __main__ */
279 value
= PyDict_GetItemString(modules
, "__main__");
280 if (value
!= NULL
&& PyModule_Check(value
)) {
282 PySys_WriteStderr("# cleanup __main__\n");
283 _PyModule_Clear(value
);
284 PyDict_SetItemString(modules
, "__main__", Py_None
);
287 /* The special treatment of __builtin__ here is because even
288 when it's not referenced as a module, its dictionary is
289 referenced by almost every module's __builtins__. Since
290 deleting a module clears its dictionary (even if there are
291 references left to it), we need to delete the __builtin__
292 module last. Likewise, we don't delete sys until the very
293 end because it is implicitly referenced (e.g. by print).
295 Also note that we 'delete' modules by replacing their entry
296 in the modules dict with None, rather than really deleting
297 them; this avoids a rehash of the modules dictionary and
298 also marks them as "non existent" so they won't be
301 /* Next, repeatedly delete modules with a reference count of
302 one (skipping __builtin__ and sys) and delete them */
306 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
307 if (value
->ob_refcnt
!= 1)
309 if (PyString_Check(key
) && PyModule_Check(value
)) {
310 name
= PyString_AS_STRING(key
);
311 if (strcmp(name
, "__builtin__") == 0)
313 if (strcmp(name
, "sys") == 0)
317 "# cleanup[1] %s\n", name
);
318 _PyModule_Clear(value
);
319 PyDict_SetItem(modules
, key
, Py_None
);
325 /* Next, delete all modules (still skipping __builtin__ and sys) */
327 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
328 if (PyString_Check(key
) && PyModule_Check(value
)) {
329 name
= PyString_AS_STRING(key
);
330 if (strcmp(name
, "__builtin__") == 0)
332 if (strcmp(name
, "sys") == 0)
335 PySys_WriteStderr("# cleanup[2] %s\n", name
);
336 _PyModule_Clear(value
);
337 PyDict_SetItem(modules
, key
, Py_None
);
341 /* Next, delete sys and __builtin__ (in that order) */
342 value
= PyDict_GetItemString(modules
, "sys");
343 if (value
!= NULL
&& PyModule_Check(value
)) {
345 PySys_WriteStderr("# cleanup sys\n");
346 _PyModule_Clear(value
);
347 PyDict_SetItemString(modules
, "sys", Py_None
);
349 value
= PyDict_GetItemString(modules
, "__builtin__");
350 if (value
!= NULL
&& PyModule_Check(value
)) {
352 PySys_WriteStderr("# cleanup __builtin__\n");
353 _PyModule_Clear(value
);
354 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
357 /* Finally, clear and delete the modules directory */
358 PyDict_Clear(modules
);
359 interp
->modules
= NULL
;
364 /* Helper for pythonrun.c -- return magic number */
367 PyImport_GetMagicNumber()
373 /* Magic for extension modules (built-in as well as dynamically
374 loaded). To prevent initializing an extension module more than
375 once, we keep a static dictionary 'extensions' keyed by module name
376 (for built-in modules) or by filename (for dynamically loaded
377 modules), containing these modules. A copy od the module's
378 dictionary is stored by calling _PyImport_FixupExtension()
379 immediately after the module initialization function succeeds. A
380 copy can be retrieved from there by calling
381 _PyImport_FindExtension(). */
384 _PyImport_FixupExtension(name
, filename
)
388 PyObject
*modules
, *mod
, *dict
, *copy
;
389 if (extensions
== NULL
) {
390 extensions
= PyDict_New();
391 if (extensions
== NULL
)
394 modules
= PyImport_GetModuleDict();
395 mod
= PyDict_GetItemString(modules
, name
);
396 if (mod
== NULL
|| !PyModule_Check(mod
)) {
397 PyErr_Format(PyExc_SystemError
,
398 "_PyImport_FixupExtension: module %.200s not loaded", name
);
401 dict
= PyModule_GetDict(mod
);
404 copy
= PyObject_CallMethod(dict
, "copy", "");
407 PyDict_SetItemString(extensions
, filename
, copy
);
413 _PyImport_FindExtension(name
, filename
)
417 PyObject
*dict
, *mod
, *mdict
, *result
;
418 if (extensions
== NULL
)
420 dict
= PyDict_GetItemString(extensions
, filename
);
423 mod
= PyImport_AddModule(name
);
426 mdict
= PyModule_GetDict(mod
);
429 result
= PyObject_CallMethod(mdict
, "update", "O", dict
);
434 PySys_WriteStderr("import %s # previously loaded (%s)\n",
440 /* Get the module object corresponding to a module name.
441 First check the modules dictionary if there's one there,
442 if not, create a new one and insert in in the modules dictionary.
443 Because the former action is most common, THIS DOES NOT RETURN A
447 PyImport_AddModule(name
)
450 PyObject
*modules
= PyImport_GetModuleDict();
453 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
456 m
= PyModule_New(name
);
459 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
463 Py_DECREF(m
); /* Yes, it still exists, in modules! */
469 /* Execute a code object in a module and return the module object
470 WITH INCREMENTED REFERENCE COUNT */
473 PyImport_ExecCodeModule(name
, co
)
477 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
481 PyImport_ExecCodeModuleEx(name
, co
, pathname
)
486 PyObject
*modules
= PyImport_GetModuleDict();
489 m
= PyImport_AddModule(name
);
492 d
= PyModule_GetDict(m
);
493 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
494 if (PyDict_SetItemString(d
, "__builtins__",
495 PyEval_GetBuiltins()) != 0)
498 /* Remember the filename as the __file__ attribute */
500 if (pathname
!= NULL
) {
501 v
= PyString_FromString(pathname
);
506 v
= ((PyCodeObject
*)co
)->co_filename
;
509 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
510 PyErr_Clear(); /* Not important enough to report */
513 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
518 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
519 PyErr_Format(PyExc_ImportError
,
520 "Loaded module %.200s not found in sys.modules",
531 /* Given a pathname for a Python source file, fill a buffer with the
532 pathname for the corresponding compiled file. Return the pathname
533 for the compiled file, or NULL if there's no space in the buffer.
534 Doesn't set an exception. */
537 make_compiled_pathname(pathname
, buf
, buflen
)
544 len
= strlen(pathname
);
547 strcpy(buf
, pathname
);
548 strcpy(buf
+len
, Py_OptimizeFlag
? "o" : "c");
554 /* Given a pathname for a Python source file, its time of last
555 modification, and a pathname for a compiled file, check whether the
556 compiled file represents the same version of the source. If so,
557 return a FILE pointer for the compiled file, positioned just after
558 the header; if not, return NULL.
559 Doesn't set an exception. */
562 check_compiled_module(pathname
, mtime
, cpathname
)
571 fp
= fopen(cpathname
, "rb");
574 magic
= PyMarshal_ReadLongFromFile(fp
);
575 if (magic
!= MAGIC
) {
577 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
581 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
582 if (pyc_mtime
!= mtime
) {
584 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
589 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
594 /* Read a code object from a file and check it for validity */
596 static PyCodeObject
*
597 read_compiled_module(cpathname
, fp
)
603 co
= PyMarshal_ReadObjectFromFile(fp
);
604 /* Ugly: rd_object() may return NULL with or without error */
605 if (co
== NULL
|| !PyCode_Check(co
)) {
606 if (!PyErr_Occurred())
607 PyErr_Format(PyExc_ImportError
,
608 "Non-code object in %.200s", cpathname
);
612 return (PyCodeObject
*)co
;
616 /* Load a module from a compiled file, execute it, and return its
617 module object WITH INCREMENTED REFERENCE COUNT */
620 load_compiled_module(name
, cpathname
, fp
)
629 magic
= PyMarshal_ReadLongFromFile(fp
);
630 if (magic
!= MAGIC
) {
631 PyErr_Format(PyExc_ImportError
,
632 "Bad magic number in %.200s", cpathname
);
635 (void) PyMarshal_ReadLongFromFile(fp
);
636 co
= read_compiled_module(cpathname
, fp
);
640 PySys_WriteStderr("import %s # precompiled from %s\n",
642 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
648 /* Parse a source file and return the corresponding code object */
650 static PyCodeObject
*
651 parse_source_module(pathname
, fp
)
658 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
661 co
= PyNode_Compile(n
, pathname
);
668 /* Write a compiled module to a file, placing the time of last
669 modification of its source into the header.
670 Errors are ignored, if a write error occurs an attempt is made to
674 write_compiled_module(co
, cpathname
, mtime
)
681 fp
= fopen(cpathname
, "wb");
685 "# can't create %s\n", cpathname
);
688 PyMarshal_WriteLongToFile(MAGIC
, fp
);
689 /* First write a 0 for mtime */
690 PyMarshal_WriteLongToFile(0L, fp
);
691 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
694 PySys_WriteStderr("# can't write %s\n", cpathname
);
695 /* Don't keep partial file */
697 (void) unlink(cpathname
);
700 /* Now write the true mtime */
702 PyMarshal_WriteLongToFile(mtime
, fp
);
706 PySys_WriteStderr("# wrote %s\n", cpathname
);
708 setfiletype(cpathname
, 'Pyth', 'PYC ');
713 /* Load a source module from a given file and return its module
714 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
715 byte-compiled file, use that instead. */
718 load_source_module(name
, pathname
, fp
)
725 char buf
[MAXPATHLEN
+1];
730 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
731 cpathname
= make_compiled_pathname(pathname
, buf
, MAXPATHLEN
+1);
732 if (cpathname
!= NULL
&&
733 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
734 co
= read_compiled_module(cpathname
, fpc
);
739 PySys_WriteStderr("import %s # precompiled from %s\n",
741 pathname
= cpathname
;
744 co
= parse_source_module(pathname
, fp
);
748 PySys_WriteStderr("import %s # from %s\n",
750 write_compiled_module(co
, cpathname
, mtime
);
752 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
760 static PyObject
*load_module
Py_PROTO((char *, FILE *, char *, int));
761 static struct filedescr
*find_module
Py_PROTO((char *, PyObject
*,
762 char *, int, FILE **));
763 static struct _frozen
*find_frozen
Py_PROTO((char *name
));
765 /* Load a package and return its module object WITH INCREMENTED
769 load_package(name
, pathname
)
773 PyObject
*m
, *d
, *file
, *path
;
775 char buf
[MAXPATHLEN
+1];
777 struct filedescr
*fdp
;
779 m
= PyImport_AddModule(name
);
783 PySys_WriteStderr("import %s # directory %s\n",
785 d
= PyModule_GetDict(m
);
786 file
= PyString_FromString(pathname
);
789 path
= Py_BuildValue("[O]", file
);
794 err
= PyDict_SetItemString(d
, "__file__", file
);
796 err
= PyDict_SetItemString(d
, "__path__", path
);
802 fdp
= find_module("__init__", path
, buf
, sizeof(buf
), &fp
);
804 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
811 m
= load_module(name
, fp
, buf
, fdp
->type
);
821 /* Helper to test for built-in module */
828 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
829 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
830 if (PyImport_Inittab
[i
].initfunc
== NULL
)
840 /* Search the path (default sys.path) for a module. Return the
841 corresponding filedescr struct, and (via return arguments) the
842 pathname and an open file. Return NULL if the module is not found. */
845 extern FILE *PyWin_FindRegisteredModule();
848 #ifdef CHECK_IMPORT_CASE
849 static int check_case(char *, int, int, char *);
852 static int find_init_module
Py_PROTO((char *)); /* Forward */
854 static struct filedescr
*
855 find_module(realname
, path
, buf
, buflen
, p_fp
)
858 /* Output parameters: */
863 int i
, npath
, len
, namelen
;
865 struct filedescr
*fdp
= NULL
;
868 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
869 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
870 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
871 char name
[MAXPATHLEN
+1];
873 strcpy(name
, realname
);
875 if (path
!= NULL
&& PyString_Check(path
)) {
876 /* Submodule of "frozen" package:
877 Set name to the fullname, path to NULL
878 and continue as "usual" */
879 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
880 PyErr_SetString(PyExc_ImportError
,
881 "full frozen module name too long");
884 strcpy(buf
, PyString_AsString(path
));
891 if (is_builtin(name
)) {
895 if ((f
= find_frozen(name
)) != NULL
) {
901 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
907 path
= PySys_GetObject("path");
909 if (path
== NULL
|| !PyList_Check(path
)) {
910 PyErr_SetString(PyExc_ImportError
,
911 "sys.path must be a list of directory names");
914 npath
= PyList_Size(path
);
915 namelen
= strlen(name
);
916 for (i
= 0; i
< npath
; i
++) {
917 PyObject
*v
= PyList_GetItem(path
, i
);
918 if (!PyString_Check(v
))
920 len
= PyString_Size(v
);
921 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
)
922 continue; /* Too long */
923 strcpy(buf
, PyString_AsString(v
));
924 if ((int)strlen(buf
) != len
)
925 continue; /* v contains '\0' */
927 #ifdef INTERN_STRINGS
929 ** Speedup: each sys.path item is interned, and
930 ** FindResourceModule remembers which items refer to
931 ** folders (so we don't have to bother trying to look
932 ** into them for resources).
934 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
935 v
= PyList_GET_ITEM(path
, i
);
937 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
938 static struct filedescr resfiledescr
=
939 {"", "", PY_RESOURCE
};
941 return &resfiledescr
;
943 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
944 static struct filedescr resfiledescr
=
945 {"", "", PY_CODERESOURCE
};
947 return &resfiledescr
;
950 if (len
> 0 && buf
[len
-1] != SEP
952 && buf
[len
-1] != ALTSEP
956 #ifdef IMPORT_8x3_NAMES
957 /* see if we are searching in directory dos-8x3 */
958 if (len
> 7 && !strncmp(buf
+ len
- 8, "dos-8x3", 7)){
960 char ch
; /* limit name to 8 lower-case characters */
961 for (j
= 0; (ch
= name
[j
]) && j
< 8; j
++)
963 buf
[len
++] = tolower(ch
);
967 else /* Not in dos-8x3, use the full name */
970 strcpy(buf
+len
, name
);
974 if (stat(buf
, &statbuf
) == 0) {
975 if (S_ISDIR(statbuf
.st_mode
)) {
976 if (find_init_module(buf
)) {
977 #ifdef CHECK_IMPORT_CASE
978 if (!check_case(buf
, len
, namelen
,
987 /* XXX How are you going to test for directories? */
990 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
992 fp
= fopen(buf
, fdp
->mode
);
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 fp
= fopen(buf
, fdp
->mode
);
1002 #endif /* !macintosh */
1007 PyErr_Format(PyExc_ImportError
,
1008 "No module named %.200s", name
);
1011 #ifdef CHECK_IMPORT_CASE
1012 if (!check_case(buf
, len
, namelen
, name
)) {
1022 #ifdef CHECK_IMPORT_CASE
1025 #include <windows.h>
1032 /* Return 1 if s is an 8.3 filename in ALLCAPS */
1034 char *dot
= strchr(s
, '.');
1035 char *end
= strchr(s
, '\0');
1038 return 1; /* More than 8 before '.' */
1040 return 1; /* More than 3 after '.' */
1041 end
= strchr(dot
+1, '.');
1043 return 1; /* More than one dot */
1046 return 1; /* More than 8 and no dot */
1047 while ((c
= *s
++)) {
1055 check_case(char *buf
, int len
, int namelen
, char *name
)
1057 WIN32_FIND_DATA data
;
1059 if (getenv("PYTHONCASEOK") != NULL
)
1061 h
= FindFirstFile(buf
, &data
);
1062 if (h
== INVALID_HANDLE_VALUE
) {
1063 PyErr_Format(PyExc_NameError
,
1064 "Can't find file for module %.100s\n(filename %.300s)",
1069 if (allcaps8x3(data
.cFileName
)) {
1070 /* Skip the test if the filename is ALL.CAPS. This can
1071 happen in certain circumstances beyond our control,
1072 e.g. when software is installed under NT on a FAT
1073 filesystem and then the same FAT filesystem is used
1074 under Windows 95. */
1077 if (strncmp(data
.cFileName
, name
, namelen
) != 0) {
1078 strcpy(buf
+len
-namelen
, data
.cFileName
);
1079 PyErr_Format(PyExc_NameError
,
1080 "Case mismatch for module name %.100s\n(filename %.300s)",
1086 #endif /* MS_WIN32 */
1089 #include <TextUtils.h>
1091 #include "TFileSpec.h" /* for Path2FSSpec() */
1094 check_case(char *buf
, int len
, int namelen
, char *name
)
1099 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1101 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1102 the way, which is fine for all directories, but here we need
1103 the original name of the alias file (say, Dlg.ppc.slb, not
1104 toolboxmodules.ppc.slb). */
1106 err
= Path2FSSpec(buf
, &fss
);
1108 colon
= strrchr(buf
, ':'); /* find filename */
1110 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1111 Pstring(colon
+1), &fss
);
1113 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1118 PyErr_Format(PyExc_NameError
,
1119 "Can't find file for module %.100s\n(filename %.300s)",
1124 if ( strncmp(name
, (char *)fss
.name
, namelen
) != 0 ) {
1125 PyErr_Format(PyExc_NameError
,
1126 "Case mismatch for module name %.100s\n(filename %.300s)",
1132 #endif /* macintosh */
1138 check_case(char *buf
, int len
, int namelen
, char *name
)
1143 if (getenv("PYTHONCASEOK") != NULL
)
1145 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1147 PyErr_Format(PyExc_NameError
,
1148 "Can't find file for module %.100s\n(filename %.300s)",
1153 if (strncmp(ffblk
.ff_name
, name
, namelen
) != 0) {
1154 strcpy(buf
+len
-namelen
, ffblk
.ff_name
);
1155 PyErr_Format(PyExc_NameError
,
1156 "Case mismatch for module name %.100s\n(filename %.300s)",
1164 #endif /* CHECK_IMPORT_CASE */
1167 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1169 find_init_module(buf
)
1172 int save_len
= strlen(buf
);
1174 struct stat statbuf
;
1176 if (save_len
+ 13 >= MAXPATHLEN
)
1179 strcpy(buf
+i
, "__init__.py");
1180 if (stat(buf
, &statbuf
) == 0) {
1181 buf
[save_len
] = '\0';
1185 if (Py_OptimizeFlag
)
1189 if (stat(buf
, &statbuf
) == 0) {
1190 buf
[save_len
] = '\0';
1193 buf
[save_len
] = '\0';
1196 #endif /* HAVE_STAT */
1199 static int init_builtin
Py_PROTO((char *)); /* Forward */
1201 /* Load an external module using the default search path and return
1202 its module object WITH INCREMENTED REFERENCE COUNT */
1205 load_module(name
, fp
, buf
, type
)
1215 /* First check that there's an open file (if we need one) */
1220 PyErr_Format(PyExc_ValueError
,
1221 "file object required for import (type code %d)",
1230 m
= load_source_module(name
, buf
, fp
);
1234 m
= load_compiled_module(name
, buf
, fp
);
1237 #ifdef HAVE_DYNAMIC_LOADING
1239 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1245 m
= PyMac_LoadResourceModule(name
, buf
);
1247 case PY_CODERESOURCE
:
1248 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1253 m
= load_package(name
, buf
);
1258 if (buf
!= NULL
&& buf
[0] != '\0')
1260 if (type
== C_BUILTIN
)
1261 err
= init_builtin(name
);
1263 err
= PyImport_ImportFrozenModule(name
);
1267 PyErr_Format(PyExc_ImportError
,
1268 "Purported %s module %.200s not found",
1270 "builtin" : "frozen",
1274 modules
= PyImport_GetModuleDict();
1275 m
= PyDict_GetItemString(modules
, name
);
1279 "%s module %.200s not properly initialized",
1281 "builtin" : "frozen",
1289 PyErr_Format(PyExc_ImportError
,
1290 "Don't know how to import %.200s (type code %d)",
1300 /* Initialize a built-in module.
1301 Return 1 for succes, 0 if the module is not found, and -1 with
1302 an exception set if the initialization failed. */
1311 if ((mod
= _PyImport_FindExtension(name
, name
)) != NULL
)
1314 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1315 if (strcmp(name
, p
->name
) == 0) {
1316 if (p
->initfunc
== NULL
) {
1317 PyErr_Format(PyExc_ImportError
,
1318 "Cannot re-init internal module %.200s",
1323 PySys_WriteStderr("import %s # builtin\n", name
);
1325 if (PyErr_Occurred())
1327 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1336 /* Frozen modules */
1338 static struct _frozen
*
1344 for (p
= PyImport_FrozenModules
; ; p
++) {
1345 if (p
->name
== NULL
)
1347 if (strcmp(p
->name
, name
) == 0)
1354 get_frozen_object(name
)
1357 struct _frozen
*p
= find_frozen(name
);
1361 PyErr_Format(PyExc_ImportError
,
1362 "No such frozen object named %.200s",
1369 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1372 /* Initialize a frozen module.
1373 Return 1 for succes, 0 if the module is not found, and -1 with
1374 an exception set if the initialization failed.
1375 This function is also used from frozenmain.c */
1378 PyImport_ImportFrozenModule(name
)
1381 struct _frozen
*p
= find_frozen(name
);
1390 ispackage
= (size
< 0);
1394 PySys_WriteStderr("import %s # frozen%s\n",
1395 name
, ispackage
? " package" : "");
1396 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1399 if (!PyCode_Check(co
)) {
1401 PyErr_Format(PyExc_TypeError
,
1402 "frozen object %.200s is not a code object",
1407 /* Set __path__ to the package name */
1410 m
= PyImport_AddModule(name
);
1413 d
= PyModule_GetDict(m
);
1414 s
= PyString_InternFromString(name
);
1417 err
= PyDict_SetItemString(d
, "__path__", s
);
1422 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1431 /* Import a module, either built-in, frozen, or external, and return
1432 its module object WITH INCREMENTED REFERENCE COUNT */
1435 PyImport_ImportModule(name
)
1438 static PyObject
*fromlist
= NULL
;
1439 if (fromlist
== NULL
&& strchr(name
, '.') != NULL
) {
1440 fromlist
= Py_BuildValue("[s]", "*");
1441 if (fromlist
== NULL
)
1444 return PyImport_ImportModuleEx(name
, NULL
, NULL
, fromlist
);
1447 /* Forward declarations for helper routines */
1448 static PyObject
*get_parent
Py_PROTO((PyObject
*globals
,
1449 char *buf
, int *p_buflen
));
1450 static PyObject
*load_next
Py_PROTO((PyObject
*mod
, PyObject
*altmod
,
1451 char **p_name
, char *buf
, int *p_buflen
));
1452 static int mark_miss
Py_PROTO((char *name
));
1453 static int ensure_fromlist
Py_PROTO((PyObject
*mod
, PyObject
*fromlist
,
1454 char *buf
, int buflen
, int recursive
));
1455 static PyObject
* import_submodule
Py_PROTO((PyObject
*mod
,
1456 char *name
, char *fullname
));
1458 /* The Magnum Opus of dotted-name import :-) */
1461 import_module_ex(name
, globals
, locals
, fromlist
)
1467 char buf
[MAXPATHLEN
+1];
1469 PyObject
*parent
, *head
, *next
, *tail
;
1471 parent
= get_parent(globals
, buf
, &buflen
);
1475 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1482 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1491 if (fromlist
!= NULL
) {
1492 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1496 if (fromlist
== NULL
) {
1502 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1511 PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
)
1519 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1525 get_parent(globals
, buf
, p_buflen
)
1530 static PyObject
*namestr
= NULL
;
1531 static PyObject
*pathstr
= NULL
;
1532 PyObject
*modname
, *modpath
, *modules
, *parent
;
1534 if (globals
== NULL
|| !PyDict_Check(globals
))
1537 if (namestr
== NULL
) {
1538 namestr
= PyString_InternFromString("__name__");
1539 if (namestr
== NULL
)
1542 if (pathstr
== NULL
) {
1543 pathstr
= PyString_InternFromString("__path__");
1544 if (pathstr
== NULL
)
1550 modname
= PyDict_GetItem(globals
, namestr
);
1551 if (modname
== NULL
|| !PyString_Check(modname
))
1554 modpath
= PyDict_GetItem(globals
, pathstr
);
1555 if (modpath
!= NULL
) {
1556 int len
= PyString_GET_SIZE(modname
);
1557 if (len
> MAXPATHLEN
) {
1558 PyErr_SetString(PyExc_ValueError
,
1559 "Module name too long");
1562 strcpy(buf
, PyString_AS_STRING(modname
));
1566 char *start
= PyString_AS_STRING(modname
);
1567 char *lastdot
= strrchr(start
, '.');
1569 if (lastdot
== NULL
)
1571 len
= lastdot
- start
;
1572 if (len
>= MAXPATHLEN
) {
1573 PyErr_SetString(PyExc_ValueError
,
1574 "Module name too long");
1577 strncpy(buf
, start
, len
);
1582 modules
= PyImport_GetModuleDict();
1583 parent
= PyDict_GetItemString(modules
, buf
);
1587 /* We expect, but can't guarantee, if parent != None, that:
1588 - parent.__name__ == buf
1589 - parent.__dict__ is globals
1590 If this is violated... Who cares? */
1594 load_next(mod
, altmod
, p_name
, buf
, p_buflen
)
1596 PyObject
*altmod
; /* Either None or same as mod */
1601 char *name
= *p_name
;
1602 char *dot
= strchr(name
, '.');
1616 PyErr_SetString(PyExc_ValueError
,
1617 "Empty module name");
1621 p
= buf
+ *p_buflen
;
1624 if (p
+len
-buf
>= MAXPATHLEN
) {
1625 PyErr_SetString(PyExc_ValueError
,
1626 "Module name too long");
1629 strncpy(p
, name
, len
);
1631 *p_buflen
= p
+len
-buf
;
1633 result
= import_submodule(mod
, p
, buf
);
1634 if (result
== Py_None
&& altmod
!= mod
) {
1636 /* Here, altmod must be None and mod must not be None */
1637 result
= import_submodule(altmod
, p
, p
);
1638 if (result
!= NULL
&& result
!= Py_None
) {
1639 if (mark_miss(buf
) != 0) {
1643 strncpy(buf
, name
, len
);
1651 if (result
== Py_None
) {
1653 PyErr_Format(PyExc_ImportError
,
1654 "No module named %.200s", name
);
1665 PyObject
*modules
= PyImport_GetModuleDict();
1666 return PyDict_SetItemString(modules
, name
, Py_None
);
1670 ensure_fromlist(mod
, fromlist
, buf
, buflen
, recursive
)
1679 if (!PyObject_HasAttrString(mod
, "__path__"))
1682 for (i
= 0; ; i
++) {
1683 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
1686 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1692 if (!PyString_Check(item
)) {
1693 PyErr_SetString(PyExc_TypeError
,
1694 "Item in ``from list'' not a string");
1698 if (PyString_AS_STRING(item
)[0] == '*') {
1701 /* See if the package defines __all__ */
1703 continue; /* Avoid endless recursion */
1704 all
= PyObject_GetAttrString(mod
, "__all__");
1708 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
1714 hasit
= PyObject_HasAttr(mod
, item
);
1716 char *subname
= PyString_AS_STRING(item
);
1719 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
1720 PyErr_SetString(PyExc_ValueError
,
1721 "Module name too long");
1728 submod
= import_submodule(mod
, subname
, buf
);
1730 if (submod
== NULL
) {
1742 import_submodule(mod
, subname
, fullname
)
1743 PyObject
*mod
; /* May be None */
1747 PyObject
*modules
= PyImport_GetModuleDict();
1751 if mod == None: subname == fullname
1752 else: mod.__name__ + "." + subname == fullname
1755 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
1760 char buf
[MAXPATHLEN
+1];
1761 struct filedescr
*fdp
;
1767 path
= PyObject_GetAttrString(mod
, "__path__");
1776 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1779 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
1785 m
= load_module(fullname
, fp
, buf
, fdp
->type
);
1788 if (m
!= NULL
&& mod
!= Py_None
) {
1789 if (PyObject_SetAttrString(mod
, subname
, m
) < 0) {
1800 /* Re-import a module of any kind and return its module object, WITH
1801 INCREMENTED REFERENCE COUNT */
1804 PyImport_ReloadModule(m
)
1807 PyObject
*modules
= PyImport_GetModuleDict();
1808 PyObject
*path
= NULL
;
1809 char *name
, *subname
;
1810 char buf
[MAXPATHLEN
+1];
1811 struct filedescr
*fdp
;
1814 if (m
== NULL
|| !PyModule_Check(m
)) {
1815 PyErr_SetString(PyExc_TypeError
,
1816 "reload() argument must be module");
1819 name
= PyModule_GetName(m
);
1822 if (m
!= PyDict_GetItemString(modules
, name
)) {
1823 PyErr_Format(PyExc_ImportError
,
1824 "reload(): module %.200s not in sys.modules",
1828 subname
= strrchr(name
, '.');
1829 if (subname
== NULL
)
1832 PyObject
*parentname
, *parent
;
1833 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
1834 if (parentname
== NULL
)
1836 parent
= PyDict_GetItem(modules
, parentname
);
1837 Py_DECREF(parentname
);
1838 if (parent
== NULL
) {
1839 PyErr_Format(PyExc_ImportError
,
1840 "reload(): parent %.200s not in sys.modules",
1845 path
= PyObject_GetAttrString(parent
, "__path__");
1850 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1854 m
= load_module(name
, fp
, buf
, fdp
->type
);
1861 /* Higher-level import emulator which emulates the "import" statement
1862 more accurately -- it invokes the __import__() function from the
1863 builtins of the current globals. This means that the import is
1864 done using whatever import hooks are installed in the current
1865 environment, e.g. by "rexec".
1866 A dummy list ["__doc__"] is passed as the 4th argument so that
1867 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1868 will return <module "gencache"> instead of <module "win32com">. */
1871 PyImport_Import(module_name
)
1872 PyObject
*module_name
;
1874 static PyObject
*silly_list
= NULL
;
1875 static PyObject
*builtins_str
= NULL
;
1876 static PyObject
*import_str
= NULL
;
1877 static PyObject
*standard_builtins
= NULL
;
1878 PyObject
*globals
= NULL
;
1879 PyObject
*import
= NULL
;
1880 PyObject
*builtins
= NULL
;
1883 /* Initialize constant string objects */
1884 if (silly_list
== NULL
) {
1885 import_str
= PyString_InternFromString("__import__");
1886 if (import_str
== NULL
)
1888 builtins_str
= PyString_InternFromString("__builtins__");
1889 if (builtins_str
== NULL
)
1891 silly_list
= Py_BuildValue("[s]", "__doc__");
1892 if (silly_list
== NULL
)
1896 /* Get the builtins from current globals */
1897 globals
= PyEval_GetGlobals();
1898 if(globals
!= NULL
) {
1900 builtins
= PyObject_GetItem(globals
, builtins_str
);
1901 if (builtins
== NULL
)
1905 /* No globals -- use standard builtins, and fake globals */
1908 if (standard_builtins
== NULL
) {
1910 PyImport_ImportModule("__builtin__");
1911 if (standard_builtins
== NULL
)
1915 builtins
= standard_builtins
;
1916 Py_INCREF(builtins
);
1917 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
1918 if (globals
== NULL
)
1922 /* Get the __import__ function from the builtins */
1923 if (PyDict_Check(builtins
))
1924 import
=PyObject_GetItem(builtins
, import_str
);
1926 import
=PyObject_GetAttr(builtins
, import_str
);
1930 /* Call the _import__ function with the proper argument list */
1931 r
= PyObject_CallFunction(import
, "OOOO",
1932 module_name
, globals
, globals
, silly_list
);
1935 Py_XDECREF(globals
);
1936 Py_XDECREF(builtins
);
1943 /* Module 'imp' provides Python access to the primitives used for
1948 imp_get_magic(self
, args
)
1954 if (!PyArg_ParseTuple(args
, ""))
1956 buf
[0] = (char) ((MAGIC
>> 0) & 0xff);
1957 buf
[1] = (char) ((MAGIC
>> 8) & 0xff);
1958 buf
[2] = (char) ((MAGIC
>> 16) & 0xff);
1959 buf
[3] = (char) ((MAGIC
>> 24) & 0xff);
1961 return PyString_FromStringAndSize(buf
, 4);
1965 imp_get_suffixes(self
, args
)
1970 struct filedescr
*fdp
;
1972 if (!PyArg_ParseTuple(args
, ""))
1974 list
= PyList_New(0);
1977 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1978 PyObject
*item
= Py_BuildValue("ssi",
1979 fdp
->suffix
, fdp
->mode
, fdp
->type
);
1984 if (PyList_Append(list
, item
) < 0) {
1995 call_find_module(name
, path
)
1997 PyObject
*path
; /* list or None or NULL */
1999 extern int fclose
Py_PROTO((FILE *));
2000 PyObject
*fob
, *ret
;
2001 struct filedescr
*fdp
;
2002 char pathname
[MAXPATHLEN
+1];
2006 if (path
== Py_None
)
2008 fdp
= find_module(name
, path
, pathname
, MAXPATHLEN
+1, &fp
);
2012 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2022 ret
= Py_BuildValue("Os(ssi)",
2023 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2029 imp_find_module(self
, args
)
2034 PyObject
*path
= NULL
;
2035 if (!PyArg_ParseTuple(args
, "s|O", &name
, &path
))
2037 return call_find_module(name
, path
);
2041 imp_init_builtin(self
, args
)
2048 if (!PyArg_ParseTuple(args
, "s", &name
))
2050 ret
= init_builtin(name
);
2057 m
= PyImport_AddModule(name
);
2063 imp_init_frozen(self
, args
)
2070 if (!PyArg_ParseTuple(args
, "s", &name
))
2072 ret
= PyImport_ImportFrozenModule(name
);
2079 m
= PyImport_AddModule(name
);
2085 imp_get_frozen_object(self
, args
)
2091 if (!PyArg_ParseTuple(args
, "s", &name
))
2093 return get_frozen_object(name
);
2097 imp_is_builtin(self
, args
)
2102 if (!PyArg_ParseTuple(args
, "s", &name
))
2104 return PyInt_FromLong(is_builtin(name
));
2108 imp_is_frozen(self
, args
)
2114 if (!PyArg_ParseTuple(args
, "s", &name
))
2116 p
= find_frozen(name
);
2117 return PyInt_FromLong((long) (p
== NULL
? 0 : p
->size
));
2121 get_file(pathname
, fob
, mode
)
2128 fp
= fopen(pathname
, mode
);
2130 PyErr_SetFromErrno(PyExc_IOError
);
2133 fp
= PyFile_AsFile(fob
);
2135 PyErr_SetString(PyExc_ValueError
,
2136 "bad/closed file object");
2142 imp_load_compiled(self
, args
)
2148 PyObject
*fob
= NULL
;
2151 if (!PyArg_ParseTuple(args
, "ss|O!", &name
, &pathname
,
2152 &PyFile_Type
, &fob
))
2154 fp
= get_file(pathname
, fob
, "rb");
2157 m
= load_compiled_module(name
, pathname
, fp
);
2163 #ifdef HAVE_DYNAMIC_LOADING
2166 imp_load_dynamic(self
, args
)
2172 PyObject
*fob
= NULL
;
2175 if (!PyArg_ParseTuple(args
, "ss|O!", &name
, &pathname
,
2176 &PyFile_Type
, &fob
))
2179 fp
= get_file(pathname
, fob
, "r");
2183 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2187 #endif /* HAVE_DYNAMIC_LOADING */
2190 imp_load_source(self
, args
)
2196 PyObject
*fob
= NULL
;
2199 if (!PyArg_ParseTuple(args
, "ss|O!", &name
, &pathname
,
2200 &PyFile_Type
, &fob
))
2202 fp
= get_file(pathname
, fob
, "r");
2205 m
= load_source_module(name
, pathname
, fp
);
2213 imp_load_resource(self
, args
)
2221 if (!PyArg_ParseTuple(args
, "ss", &name
, &pathname
))
2223 m
= PyMac_LoadResourceModule(name
, pathname
);
2226 #endif /* macintosh */
2229 imp_load_module(self
, args
)
2236 char *suffix
; /* Unused */
2241 if (!PyArg_ParseTuple(args
, "sOs(ssi)",
2242 &name
, &fob
, &pathname
,
2243 &suffix
, &mode
, &type
))
2245 if (*mode
&& (*mode
!= 'r' || strchr(mode
, '+') != NULL
)) {
2246 PyErr_Format(PyExc_ValueError
,
2247 "invalid file open mode %.200s", mode
);
2253 if (!PyFile_Check(fob
)) {
2254 PyErr_SetString(PyExc_ValueError
,
2255 "load_module arg#2 should be a file or None");
2258 fp
= get_file(pathname
, fob
, mode
);
2262 return load_module(name
, fp
, pathname
, type
);
2266 imp_load_package(self
, args
)
2272 if (!PyArg_ParseTuple(args
, "ss", &name
, &pathname
))
2274 return load_package(name
, pathname
);
2278 imp_new_module(self
, args
)
2283 if (!PyArg_ParseTuple(args
, "s", &name
))
2285 return PyModule_New(name
);
2290 static char doc_imp
[] = "\
2291 This module provides the components needed to build your own\n\
2292 __import__ function. Undocumented functions are obsolete.\n\
2295 static char doc_find_module
[] = "\
2296 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2297 Search for a module. If path is omitted or None, search for a\n\
2298 built-in, frozen or special module and continue search in sys.path.\n\
2299 The module name cannot contain '.'; to search for a submodule of a\n\
2300 package, pass the submodule name and the package's __path__.\
2303 static char doc_load_module
[] = "\
2304 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2305 Load a module, given information returned by find_module().\n\
2306 The module name must include the full package name, if any.\
2309 static char doc_get_magic
[] = "\
2310 get_magic() -> string\n\
2311 Return the magic number for .pyc or .pyo files.\
2314 static char doc_get_suffixes
[] = "\
2315 get_suffixes() -> [(suffix, mode, type), ...]\n\
2316 Return a list of (suffix, mode, type) tuples describing the files\n\
2317 that find_module() looks for.\
2320 static char doc_new_module
[] = "\
2321 new_module(name) -> module\n\
2322 Create a new module. Do not enter it in sys.modules.\n\
2323 The module name must include the full package name, if any.\
2326 static PyMethodDef imp_methods
[] = {
2327 {"find_module", imp_find_module
, 1, doc_find_module
},
2328 {"get_magic", imp_get_magic
, 1, doc_get_magic
},
2329 {"get_suffixes", imp_get_suffixes
, 1, doc_get_suffixes
},
2330 {"load_module", imp_load_module
, 1, doc_load_module
},
2331 {"new_module", imp_new_module
, 1, doc_new_module
},
2332 /* The rest are obsolete */
2333 {"get_frozen_object", imp_get_frozen_object
, 1},
2334 {"init_builtin", imp_init_builtin
, 1},
2335 {"init_frozen", imp_init_frozen
, 1},
2336 {"is_builtin", imp_is_builtin
, 1},
2337 {"is_frozen", imp_is_frozen
, 1},
2338 {"load_compiled", imp_load_compiled
, 1},
2339 #ifdef HAVE_DYNAMIC_LOADING
2340 {"load_dynamic", imp_load_dynamic
, 1},
2342 {"load_package", imp_load_package
, 1},
2344 {"load_resource", imp_load_resource
, 1},
2346 {"load_source", imp_load_source
, 1},
2347 {NULL
, NULL
} /* sentinel */
2351 setint(d
, name
, value
)
2359 v
= PyInt_FromLong((long)value
);
2360 err
= PyDict_SetItemString(d
, name
, v
);
2370 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2371 NULL
, PYTHON_API_VERSION
);
2372 d
= PyModule_GetDict(m
);
2374 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2375 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2376 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2377 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2378 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2379 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2380 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2381 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2382 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2389 /* API for embedding applications that want to add their own entries to the
2390 table of built-in modules. This should normally be called *before*
2391 Py_Initialize(). When the malloc() or realloc() call fails, -1 is returned
2392 and the existing table is unchanged.
2394 After a similar function by Just van Rossum. */
2397 PyImport_ExtendInittab(newtab
)
2398 struct _inittab
*newtab
;
2400 static struct _inittab
*our_copy
= NULL
;
2404 /* Count the number of entries in both tables */
2405 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2408 return 0; /* Nothing to do */
2409 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2412 /* Allocate new memory for the combined table */
2413 if (our_copy
== NULL
)
2414 p
= malloc((i
+n
+1) * sizeof(struct _inittab
));
2416 p
= realloc(our_copy
, (i
+n
+1) * sizeof(struct _inittab
));
2420 /* Copy the tables into the new memory */
2421 if (our_copy
!= PyImport_Inittab
)
2422 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2423 PyImport_Inittab
= our_copy
= p
;
2424 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2429 /* Shorthand to add a single entry given a name and a function */
2432 PyImport_AppendInittab(name
, initfunc
)
2436 struct _inittab newtab
[2];
2438 memset(newtab
, '\0', sizeof newtab
);
2440 newtab
[0].name
= name
;
2441 newtab
[0].initfunc
= initfunc
;
2443 return PyImport_ExtendInittab(newtab
);