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 /* Initialize things */
102 if (Py_OptimizeFlag
) {
103 /* Replace ".pyc" with ".pyo" in import_filetab */
105 for (p
= _PyImport_Filetab
; p
->suffix
!= NULL
; p
++) {
106 if (strcmp(p
->suffix
, ".pyc") == 0)
115 Py_XDECREF(extensions
);
120 /* Locking primitives to prevent parallel imports of the same module
121 in different threads to return with a partially loaded module.
122 These calls are serialized by the global interpreter lock. */
126 #include "pythread.h"
128 static PyThread_type_lock import_lock
= 0;
129 static long import_lock_thread
= -1;
130 static int import_lock_level
= 0;
135 long me
= PyThread_get_thread_ident();
137 return; /* Too bad */
138 if (import_lock
== NULL
)
139 import_lock
= PyThread_allocate_lock();
140 if (import_lock_thread
== me
) {
144 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0)) {
145 PyThreadState
*tstate
= PyEval_SaveThread();
146 PyThread_acquire_lock(import_lock
, 1);
147 PyEval_RestoreThread(tstate
);
149 import_lock_thread
= me
;
150 import_lock_level
= 1;
156 long me
= PyThread_get_thread_ident();
158 return; /* Too bad */
159 if (import_lock_thread
!= me
)
160 Py_FatalError("unlock_import: not holding the import lock");
162 if (import_lock_level
== 0) {
163 import_lock_thread
= -1;
164 PyThread_release_lock(import_lock
);
170 #define lock_import()
171 #define unlock_import()
178 PyImport_GetModuleDict()
180 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
181 if (interp
->modules
== NULL
)
182 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
183 return interp
->modules
;
187 /* List of names to clear in sys */
188 static char* sys_deletes
[] = {
189 "path", "argv", "ps1", "ps2", "exitfunc",
190 "exc_type", "exc_value", "exc_traceback",
191 "last_type", "last_value", "last_traceback",
195 static char* sys_files
[] = {
196 "stdin", "__stdin__",
197 "stdout", "__stdout__",
198 "stderr", "__stderr__",
203 /* Un-initialize things, as good as we can */
210 PyObject
*key
, *value
, *dict
;
211 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
212 PyObject
*modules
= interp
->modules
;
215 return; /* Already done */
217 /* Delete some special variables first. These are common
218 places where user values hide and people complain when their
219 destructors fail. Since the modules containing them are
220 deleted *last* of all, they would come too late in the normal
221 destruction order. Sigh. */
223 value
= PyDict_GetItemString(modules
, "__builtin__");
224 if (value
!= NULL
&& PyModule_Check(value
)) {
225 dict
= PyModule_GetDict(value
);
227 PySys_WriteStderr("# clear __builtin__._\n");
228 PyDict_SetItemString(dict
, "_", Py_None
);
230 value
= PyDict_GetItemString(modules
, "sys");
231 if (value
!= NULL
&& PyModule_Check(value
)) {
234 dict
= PyModule_GetDict(value
);
235 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
237 PySys_WriteStderr("# clear sys.%s\n", *p
);
238 PyDict_SetItemString(dict
, *p
, Py_None
);
240 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
242 PySys_WriteStderr("# restore sys.%s\n", *p
);
243 v
= PyDict_GetItemString(dict
, *(p
+1));
246 PyDict_SetItemString(dict
, *p
, v
);
250 /* First, delete __main__ */
251 value
= PyDict_GetItemString(modules
, "__main__");
252 if (value
!= NULL
&& PyModule_Check(value
)) {
254 PySys_WriteStderr("# cleanup __main__\n");
255 _PyModule_Clear(value
);
256 PyDict_SetItemString(modules
, "__main__", Py_None
);
259 /* The special treatment of __builtin__ here is because even
260 when it's not referenced as a module, its dictionary is
261 referenced by almost every module's __builtins__. Since
262 deleting a module clears its dictionary (even if there are
263 references left to it), we need to delete the __builtin__
264 module last. Likewise, we don't delete sys until the very
265 end because it is implicitly referenced (e.g. by print).
267 Also note that we 'delete' modules by replacing their entry
268 in the modules dict with None, rather than really deleting
269 them; this avoids a rehash of the modules dictionary and
270 also marks them as "non existent" so they won't be
273 /* Next, repeatedly delete modules with a reference count of
274 one (skipping __builtin__ and sys) and delete them */
278 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
279 if (value
->ob_refcnt
!= 1)
281 if (PyString_Check(key
) && PyModule_Check(value
)) {
282 name
= PyString_AS_STRING(key
);
283 if (strcmp(name
, "__builtin__") == 0)
285 if (strcmp(name
, "sys") == 0)
289 "# cleanup[1] %s\n", name
);
290 _PyModule_Clear(value
);
291 PyDict_SetItem(modules
, key
, Py_None
);
297 /* Next, delete all modules (still skipping __builtin__ and sys) */
299 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
300 if (PyString_Check(key
) && PyModule_Check(value
)) {
301 name
= PyString_AS_STRING(key
);
302 if (strcmp(name
, "__builtin__") == 0)
304 if (strcmp(name
, "sys") == 0)
307 PySys_WriteStderr("# cleanup[2] %s\n", name
);
308 _PyModule_Clear(value
);
309 PyDict_SetItem(modules
, key
, Py_None
);
313 /* Next, delete sys and __builtin__ (in that order) */
314 value
= PyDict_GetItemString(modules
, "sys");
315 if (value
!= NULL
&& PyModule_Check(value
)) {
317 PySys_WriteStderr("# cleanup sys\n");
318 _PyModule_Clear(value
);
319 PyDict_SetItemString(modules
, "sys", Py_None
);
321 value
= PyDict_GetItemString(modules
, "__builtin__");
322 if (value
!= NULL
&& PyModule_Check(value
)) {
324 PySys_WriteStderr("# cleanup __builtin__\n");
325 _PyModule_Clear(value
);
326 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
329 /* Finally, clear and delete the modules directory */
330 PyDict_Clear(modules
);
331 interp
->modules
= NULL
;
336 /* Helper for pythonrun.c -- return magic number */
339 PyImport_GetMagicNumber()
345 /* Magic for extension modules (built-in as well as dynamically
346 loaded). To prevent initializing an extension module more than
347 once, we keep a static dictionary 'extensions' keyed by module name
348 (for built-in modules) or by filename (for dynamically loaded
349 modules), containing these modules. A copy od the module's
350 dictionary is stored by calling _PyImport_FixupExtension()
351 immediately after the module initialization function succeeds. A
352 copy can be retrieved from there by calling
353 _PyImport_FindExtension(). */
356 _PyImport_FixupExtension(name
, filename
)
360 PyObject
*modules
, *mod
, *dict
, *copy
;
361 if (extensions
== NULL
) {
362 extensions
= PyDict_New();
363 if (extensions
== NULL
)
366 modules
= PyImport_GetModuleDict();
367 mod
= PyDict_GetItemString(modules
, name
);
368 if (mod
== NULL
|| !PyModule_Check(mod
)) {
369 PyErr_Format(PyExc_SystemError
,
370 "_PyImport_FixupExtension: module %.200s not loaded", name
);
373 dict
= PyModule_GetDict(mod
);
376 copy
= PyObject_CallMethod(dict
, "copy", "");
379 PyDict_SetItemString(extensions
, filename
, copy
);
385 _PyImport_FindExtension(name
, filename
)
389 PyObject
*dict
, *mod
, *mdict
, *result
;
390 if (extensions
== NULL
)
392 dict
= PyDict_GetItemString(extensions
, filename
);
395 mod
= PyImport_AddModule(name
);
398 mdict
= PyModule_GetDict(mod
);
401 result
= PyObject_CallMethod(mdict
, "update", "O", dict
);
406 PySys_WriteStderr("import %s # previously loaded (%s)\n",
412 /* Get the module object corresponding to a module name.
413 First check the modules dictionary if there's one there,
414 if not, create a new one and insert in in the modules dictionary.
415 Because the former action is most common, THIS DOES NOT RETURN A
419 PyImport_AddModule(name
)
422 PyObject
*modules
= PyImport_GetModuleDict();
425 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
428 m
= PyModule_New(name
);
431 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
435 Py_DECREF(m
); /* Yes, it still exists, in modules! */
441 /* Execute a code object in a module and return the module object
442 WITH INCREMENTED REFERENCE COUNT */
445 PyImport_ExecCodeModule(name
, co
)
449 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
453 PyImport_ExecCodeModuleEx(name
, co
, pathname
)
458 PyObject
*modules
= PyImport_GetModuleDict();
461 m
= PyImport_AddModule(name
);
464 d
= PyModule_GetDict(m
);
465 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
466 if (PyDict_SetItemString(d
, "__builtins__",
467 PyEval_GetBuiltins()) != 0)
470 /* Remember the filename as the __file__ attribute */
472 if (pathname
!= NULL
) {
473 v
= PyString_FromString(pathname
);
478 v
= ((PyCodeObject
*)co
)->co_filename
;
481 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
482 PyErr_Clear(); /* Not important enough to report */
485 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
490 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
491 PyErr_Format(PyExc_ImportError
,
492 "Loaded module %.200s not found in sys.modules",
503 /* Given a pathname for a Python source file, fill a buffer with the
504 pathname for the corresponding compiled file. Return the pathname
505 for the compiled file, or NULL if there's no space in the buffer.
506 Doesn't set an exception. */
509 make_compiled_pathname(pathname
, buf
, buflen
)
516 len
= strlen(pathname
);
519 strcpy(buf
, pathname
);
520 strcpy(buf
+len
, Py_OptimizeFlag
? "o" : "c");
526 /* Given a pathname for a Python source file, its time of last
527 modification, and a pathname for a compiled file, check whether the
528 compiled file represents the same version of the source. If so,
529 return a FILE pointer for the compiled file, positioned just after
530 the header; if not, return NULL.
531 Doesn't set an exception. */
534 check_compiled_module(pathname
, mtime
, cpathname
)
543 fp
= fopen(cpathname
, "rb");
546 magic
= PyMarshal_ReadLongFromFile(fp
);
547 if (magic
!= MAGIC
) {
549 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
553 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
554 if (pyc_mtime
!= mtime
) {
556 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
561 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
566 /* Read a code object from a file and check it for validity */
568 static PyCodeObject
*
569 read_compiled_module(cpathname
, fp
)
575 co
= PyMarshal_ReadObjectFromFile(fp
);
576 /* Ugly: rd_object() may return NULL with or without error */
577 if (co
== NULL
|| !PyCode_Check(co
)) {
578 if (!PyErr_Occurred())
579 PyErr_Format(PyExc_ImportError
,
580 "Non-code object in %.200s", cpathname
);
584 return (PyCodeObject
*)co
;
588 /* Load a module from a compiled file, execute it, and return its
589 module object WITH INCREMENTED REFERENCE COUNT */
592 load_compiled_module(name
, cpathname
, fp
)
601 magic
= PyMarshal_ReadLongFromFile(fp
);
602 if (magic
!= MAGIC
) {
603 PyErr_Format(PyExc_ImportError
,
604 "Bad magic number in %.200s", cpathname
);
607 (void) PyMarshal_ReadLongFromFile(fp
);
608 co
= read_compiled_module(cpathname
, fp
);
612 PySys_WriteStderr("import %s # precompiled from %s\n",
614 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
620 /* Parse a source file and return the corresponding code object */
622 static PyCodeObject
*
623 parse_source_module(pathname
, fp
)
630 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
633 co
= PyNode_Compile(n
, pathname
);
640 /* Write a compiled module to a file, placing the time of last
641 modification of its source into the header.
642 Errors are ignored, if a write error occurs an attempt is made to
646 write_compiled_module(co
, cpathname
, mtime
)
653 fp
= fopen(cpathname
, "wb");
657 "# can't create %s\n", cpathname
);
660 PyMarshal_WriteLongToFile(MAGIC
, fp
);
661 /* First write a 0 for mtime */
662 PyMarshal_WriteLongToFile(0L, fp
);
663 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
666 PySys_WriteStderr("# can't write %s\n", cpathname
);
667 /* Don't keep partial file */
669 (void) unlink(cpathname
);
672 /* Now write the true mtime */
674 PyMarshal_WriteLongToFile(mtime
, fp
);
678 PySys_WriteStderr("# wrote %s\n", cpathname
);
680 setfiletype(cpathname
, 'Pyth', 'PYC ');
685 /* Load a source module from a given file and return its module
686 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
687 byte-compiled file, use that instead. */
690 load_source_module(name
, pathname
, fp
)
697 char buf
[MAXPATHLEN
+1];
702 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
703 cpathname
= make_compiled_pathname(pathname
, buf
, MAXPATHLEN
+1);
704 if (cpathname
!= NULL
&&
705 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
706 co
= read_compiled_module(cpathname
, fpc
);
711 PySys_WriteStderr("import %s # precompiled from %s\n",
713 pathname
= cpathname
;
716 co
= parse_source_module(pathname
, fp
);
720 PySys_WriteStderr("import %s # from %s\n",
722 write_compiled_module(co
, cpathname
, mtime
);
724 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
732 static PyObject
*load_module
Py_PROTO((char *, FILE *, char *, int));
733 static struct filedescr
*find_module
Py_PROTO((char *, PyObject
*,
734 char *, int, FILE **));
735 static struct _frozen
*find_frozen
Py_PROTO((char *name
));
737 /* Load a package and return its module object WITH INCREMENTED
741 load_package(name
, pathname
)
745 PyObject
*m
, *d
, *file
, *path
;
747 char buf
[MAXPATHLEN
+1];
749 struct filedescr
*fdp
;
751 m
= PyImport_AddModule(name
);
755 PySys_WriteStderr("import %s # directory %s\n",
757 d
= PyModule_GetDict(m
);
758 file
= PyString_FromString(pathname
);
761 path
= Py_BuildValue("[O]", file
);
766 err
= PyDict_SetItemString(d
, "__file__", file
);
768 err
= PyDict_SetItemString(d
, "__path__", path
);
774 fdp
= find_module("__init__", path
, buf
, sizeof(buf
), &fp
);
776 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
783 m
= load_module(name
, fp
, buf
, fdp
->type
);
793 /* Helper to test for built-in module */
800 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
801 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
802 if (PyImport_Inittab
[i
].initfunc
== NULL
)
812 /* Search the path (default sys.path) for a module. Return the
813 corresponding filedescr struct, and (via return arguments) the
814 pathname and an open file. Return NULL if the module is not found. */
817 extern FILE *PyWin_FindRegisteredModule();
820 #ifdef CHECK_IMPORT_CASE
821 static int check_case(char *, int, int, char *);
824 static int find_init_module
Py_PROTO((char *)); /* Forward */
826 static struct filedescr
*
827 find_module(realname
, path
, buf
, buflen
, p_fp
)
830 /* Output parameters: */
835 int i
, npath
, len
, namelen
;
837 struct filedescr
*fdp
= NULL
;
840 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
841 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
842 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
843 char name
[MAXPATHLEN
+1];
845 strcpy(name
, realname
);
847 if (path
!= NULL
&& PyString_Check(path
)) {
848 /* Submodule of "frozen" package:
849 Set name to the fullname, path to NULL
850 and continue as "usual" */
851 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
852 PyErr_SetString(PyExc_ImportError
,
853 "full frozen module name too long");
856 strcpy(buf
, PyString_AsString(path
));
863 if (is_builtin(name
)) {
867 if ((f
= find_frozen(name
)) != NULL
) {
873 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
879 path
= PySys_GetObject("path");
881 if (path
== NULL
|| !PyList_Check(path
)) {
882 PyErr_SetString(PyExc_ImportError
,
883 "sys.path must be a list of directory names");
886 npath
= PyList_Size(path
);
887 namelen
= strlen(name
);
888 for (i
= 0; i
< npath
; i
++) {
889 PyObject
*v
= PyList_GetItem(path
, i
);
890 if (!PyString_Check(v
))
892 len
= PyString_Size(v
);
893 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
)
894 continue; /* Too long */
895 strcpy(buf
, PyString_AsString(v
));
896 if ((int)strlen(buf
) != len
)
897 continue; /* v contains '\0' */
899 #ifdef INTERN_STRINGS
901 ** Speedup: each sys.path item is interned, and
902 ** FindResourceModule remembers which items refer to
903 ** folders (so we don't have to bother trying to look
904 ** into them for resources).
906 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
907 v
= PyList_GET_ITEM(path
, i
);
909 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
910 static struct filedescr resfiledescr
=
911 {"", "", PY_RESOURCE
};
913 return &resfiledescr
;
915 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
916 static struct filedescr resfiledescr
=
917 {"", "", PY_CODERESOURCE
};
919 return &resfiledescr
;
922 if (len
> 0 && buf
[len
-1] != SEP
924 && buf
[len
-1] != ALTSEP
928 #ifdef IMPORT_8x3_NAMES
929 /* see if we are searching in directory dos-8x3 */
930 if (len
> 7 && !strncmp(buf
+ len
- 8, "dos-8x3", 7)){
932 char ch
; /* limit name to 8 lower-case characters */
933 for (j
= 0; (ch
= name
[j
]) && j
< 8; j
++)
935 buf
[len
++] = tolower(ch
);
939 else /* Not in dos-8x3, use the full name */
942 strcpy(buf
+len
, name
);
946 if (stat(buf
, &statbuf
) == 0) {
947 if (S_ISDIR(statbuf
.st_mode
)) {
948 if (find_init_module(buf
)) {
949 #ifdef CHECK_IMPORT_CASE
950 if (!check_case(buf
, len
, namelen
,
959 /* XXX How are you going to test for directories? */
962 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
964 fp
= fopen(buf
, fdp
->mode
);
966 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
967 strcpy(buf
+len
, fdp
->suffix
);
968 if (Py_VerboseFlag
> 1)
969 PySys_WriteStderr("# trying %s\n", buf
);
970 fp
= fopen(buf
, fdp
->mode
);
974 #endif /* !macintosh */
979 PyErr_Format(PyExc_ImportError
,
980 "No module named %.200s", name
);
983 #ifdef CHECK_IMPORT_CASE
984 if (!check_case(buf
, len
, namelen
, name
)) {
994 #ifdef CHECK_IMPORT_CASE
1004 /* Return 1 if s is an 8.3 filename in ALLCAPS */
1006 char *dot
= strchr(s
, '.');
1007 char *end
= strchr(s
, '\0');
1010 return 1; /* More than 8 before '.' */
1012 return 1; /* More than 3 after '.' */
1013 end
= strchr(dot
+1, '.');
1015 return 1; /* More than one dot */
1018 return 1; /* More than 8 and no dot */
1019 while ((c
= *s
++)) {
1027 check_case(char *buf
, int len
, int namelen
, char *name
)
1029 WIN32_FIND_DATA data
;
1031 if (getenv("PYTHONCASEOK") != NULL
)
1033 h
= FindFirstFile(buf
, &data
);
1034 if (h
== INVALID_HANDLE_VALUE
) {
1035 PyErr_Format(PyExc_NameError
,
1036 "Can't find file for module %.100s\n(filename %.300s)",
1041 if (allcaps8x3(data
.cFileName
)) {
1042 /* Skip the test if the filename is ALL.CAPS. This can
1043 happen in certain circumstances beyond our control,
1044 e.g. when software is installed under NT on a FAT
1045 filesystem and then the same FAT filesystem is used
1046 under Windows 95. */
1049 if (strncmp(data
.cFileName
, name
, namelen
) != 0) {
1050 strcpy(buf
+len
-namelen
, data
.cFileName
);
1051 PyErr_Format(PyExc_NameError
,
1052 "Case mismatch for module name %.100s\n(filename %.300s)",
1058 #endif /* MS_WIN32 */
1061 #include <TextUtils.h>
1063 #include "TFileSpec.h" /* for Path2FSSpec() */
1066 check_case(char *buf
, int len
, int namelen
, char *name
)
1071 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1073 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1074 the way, which is fine for all directories, but here we need
1075 the original name of the alias file (say, Dlg.ppc.slb, not
1076 toolboxmodules.ppc.slb). */
1078 err
= Path2FSSpec(buf
, &fss
);
1080 colon
= strrchr(buf
, ':'); /* find filename */
1082 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1083 Pstring(colon
+1), &fss
);
1085 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1090 PyErr_Format(PyExc_NameError
,
1091 "Can't find file for module %.100s\n(filename %.300s)",
1096 if ( strncmp(name
, (char *)fss
.name
, namelen
) != 0 ) {
1097 PyErr_Format(PyExc_NameError
,
1098 "Case mismatch for module name %.100s\n(filename %.300s)",
1104 #endif /* macintosh */
1110 check_case(char *buf
, int len
, int namelen
, char *name
)
1115 if (getenv("PYTHONCASEOK") != NULL
)
1117 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1119 PyErr_Format(PyExc_NameError
,
1120 "Can't find file for module %.100s\n(filename %.300s)",
1125 if (strncmp(ffblk
.ff_name
, name
, namelen
) != 0) {
1126 strcpy(buf
+len
-namelen
, ffblk
.ff_name
);
1127 PyErr_Format(PyExc_NameError
,
1128 "Case mismatch for module name %.100s\n(filename %.300s)",
1136 #endif /* CHECK_IMPORT_CASE */
1139 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1141 find_init_module(buf
)
1144 int save_len
= strlen(buf
);
1146 struct stat statbuf
;
1148 if (save_len
+ 13 >= MAXPATHLEN
)
1151 strcpy(buf
+i
, "__init__.py");
1152 if (stat(buf
, &statbuf
) == 0) {
1153 buf
[save_len
] = '\0';
1157 if (Py_OptimizeFlag
)
1161 if (stat(buf
, &statbuf
) == 0) {
1162 buf
[save_len
] = '\0';
1165 buf
[save_len
] = '\0';
1168 #endif /* HAVE_STAT */
1171 static int init_builtin
Py_PROTO((char *)); /* Forward */
1173 /* Load an external module using the default search path and return
1174 its module object WITH INCREMENTED REFERENCE COUNT */
1177 load_module(name
, fp
, buf
, type
)
1187 /* First check that there's an open file (if we need one) */
1192 PyErr_Format(PyExc_ValueError
,
1193 "file object required for import (type code %d)",
1202 m
= load_source_module(name
, buf
, fp
);
1206 m
= load_compiled_module(name
, buf
, fp
);
1210 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1215 m
= PyMac_LoadResourceModule(name
, buf
);
1217 case PY_CODERESOURCE
:
1218 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1223 m
= load_package(name
, buf
);
1228 if (buf
!= NULL
&& buf
[0] != '\0')
1230 if (type
== C_BUILTIN
)
1231 err
= init_builtin(name
);
1233 err
= PyImport_ImportFrozenModule(name
);
1237 PyErr_Format(PyExc_ImportError
,
1238 "Purported %s module %.200s not found",
1240 "builtin" : "frozen",
1244 modules
= PyImport_GetModuleDict();
1245 m
= PyDict_GetItemString(modules
, name
);
1249 "%s module %.200s not properly initialized",
1251 "builtin" : "frozen",
1259 PyErr_Format(PyExc_ImportError
,
1260 "Don't know how to import %.200s (type code %d)",
1270 /* Initialize a built-in module.
1271 Return 1 for succes, 0 if the module is not found, and -1 with
1272 an exception set if the initialization failed. */
1281 if ((mod
= _PyImport_FindExtension(name
, name
)) != NULL
)
1284 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1285 if (strcmp(name
, p
->name
) == 0) {
1286 if (p
->initfunc
== NULL
) {
1287 PyErr_Format(PyExc_ImportError
,
1288 "Cannot re-init internal module %.200s",
1293 PySys_WriteStderr("import %s # builtin\n", name
);
1295 if (PyErr_Occurred())
1297 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1306 /* Frozen modules */
1308 static struct _frozen
*
1314 for (p
= PyImport_FrozenModules
; ; p
++) {
1315 if (p
->name
== NULL
)
1317 if (strcmp(p
->name
, name
) == 0)
1324 get_frozen_object(name
)
1327 struct _frozen
*p
= find_frozen(name
);
1331 PyErr_Format(PyExc_ImportError
,
1332 "No such frozen object named %.200s",
1339 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1342 /* Initialize a frozen module.
1343 Return 1 for succes, 0 if the module is not found, and -1 with
1344 an exception set if the initialization failed.
1345 This function is also used from frozenmain.c */
1348 PyImport_ImportFrozenModule(name
)
1351 struct _frozen
*p
= find_frozen(name
);
1360 ispackage
= (size
< 0);
1364 PySys_WriteStderr("import %s # frozen%s\n",
1365 name
, ispackage
? " package" : "");
1366 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1369 if (!PyCode_Check(co
)) {
1371 PyErr_Format(PyExc_TypeError
,
1372 "frozen object %.200s is not a code object",
1377 /* Set __path__ to the package name */
1380 m
= PyImport_AddModule(name
);
1383 d
= PyModule_GetDict(m
);
1384 s
= PyString_InternFromString(name
);
1387 err
= PyDict_SetItemString(d
, "__path__", s
);
1392 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1401 /* Import a module, either built-in, frozen, or external, and return
1402 its module object WITH INCREMENTED REFERENCE COUNT */
1405 PyImport_ImportModule(name
)
1408 static PyObject
*fromlist
= NULL
;
1409 if (fromlist
== NULL
&& strchr(name
, '.') != NULL
) {
1410 fromlist
= Py_BuildValue("[s]", "*");
1411 if (fromlist
== NULL
)
1414 return PyImport_ImportModuleEx(name
, NULL
, NULL
, fromlist
);
1417 /* Forward declarations for helper routines */
1418 static PyObject
*get_parent
Py_PROTO((PyObject
*globals
,
1419 char *buf
, int *p_buflen
));
1420 static PyObject
*load_next
Py_PROTO((PyObject
*mod
, PyObject
*altmod
,
1421 char **p_name
, char *buf
, int *p_buflen
));
1422 static int mark_miss
Py_PROTO((char *name
));
1423 static int ensure_fromlist
Py_PROTO((PyObject
*mod
, PyObject
*fromlist
,
1424 char *buf
, int buflen
, int recursive
));
1425 static PyObject
* import_submodule
Py_PROTO((PyObject
*mod
,
1426 char *name
, char *fullname
));
1428 /* The Magnum Opus of dotted-name import :-) */
1431 import_module_ex(name
, globals
, locals
, fromlist
)
1437 char buf
[MAXPATHLEN
+1];
1439 PyObject
*parent
, *head
, *next
, *tail
;
1441 parent
= get_parent(globals
, buf
, &buflen
);
1445 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1452 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1461 if (fromlist
!= NULL
) {
1462 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1466 if (fromlist
== NULL
) {
1472 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1481 PyImport_ImportModuleEx(name
, globals
, locals
, fromlist
)
1489 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1495 get_parent(globals
, buf
, p_buflen
)
1500 static PyObject
*namestr
= NULL
;
1501 static PyObject
*pathstr
= NULL
;
1502 PyObject
*modname
, *modpath
, *modules
, *parent
;
1504 if (globals
== NULL
|| !PyDict_Check(globals
))
1507 if (namestr
== NULL
) {
1508 namestr
= PyString_InternFromString("__name__");
1509 if (namestr
== NULL
)
1512 if (pathstr
== NULL
) {
1513 pathstr
= PyString_InternFromString("__path__");
1514 if (pathstr
== NULL
)
1520 modname
= PyDict_GetItem(globals
, namestr
);
1521 if (modname
== NULL
|| !PyString_Check(modname
))
1524 modpath
= PyDict_GetItem(globals
, pathstr
);
1525 if (modpath
!= NULL
) {
1526 int len
= PyString_GET_SIZE(modname
);
1527 if (len
> MAXPATHLEN
) {
1528 PyErr_SetString(PyExc_ValueError
,
1529 "Module name too long");
1532 strcpy(buf
, PyString_AS_STRING(modname
));
1536 char *start
= PyString_AS_STRING(modname
);
1537 char *lastdot
= strrchr(start
, '.');
1539 if (lastdot
== NULL
)
1541 len
= lastdot
- start
;
1542 if (len
>= MAXPATHLEN
) {
1543 PyErr_SetString(PyExc_ValueError
,
1544 "Module name too long");
1547 strncpy(buf
, start
, len
);
1552 modules
= PyImport_GetModuleDict();
1553 parent
= PyDict_GetItemString(modules
, buf
);
1557 /* We expect, but can't guarantee, if parent != None, that:
1558 - parent.__name__ == buf
1559 - parent.__dict__ is globals
1560 If this is violated... Who cares? */
1564 load_next(mod
, altmod
, p_name
, buf
, p_buflen
)
1566 PyObject
*altmod
; /* Either None or same as mod */
1571 char *name
= *p_name
;
1572 char *dot
= strchr(name
, '.');
1586 PyErr_SetString(PyExc_ValueError
,
1587 "Empty module name");
1591 p
= buf
+ *p_buflen
;
1594 if (p
+len
-buf
>= MAXPATHLEN
) {
1595 PyErr_SetString(PyExc_ValueError
,
1596 "Module name too long");
1599 strncpy(p
, name
, len
);
1601 *p_buflen
= p
+len
-buf
;
1603 result
= import_submodule(mod
, p
, buf
);
1604 if (result
== Py_None
&& altmod
!= mod
) {
1606 /* Here, altmod must be None and mod must not be None */
1607 result
= import_submodule(altmod
, p
, p
);
1608 if (result
!= NULL
&& result
!= Py_None
) {
1609 if (mark_miss(buf
) != 0) {
1613 strncpy(buf
, name
, len
);
1621 if (result
== Py_None
) {
1623 PyErr_Format(PyExc_ImportError
,
1624 "No module named %.200s", name
);
1635 PyObject
*modules
= PyImport_GetModuleDict();
1636 return PyDict_SetItemString(modules
, name
, Py_None
);
1640 ensure_fromlist(mod
, fromlist
, buf
, buflen
, recursive
)
1649 if (!PyObject_HasAttrString(mod
, "__path__"))
1652 for (i
= 0; ; i
++) {
1653 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
1656 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1662 if (!PyString_Check(item
)) {
1663 PyErr_SetString(PyExc_TypeError
,
1664 "Item in ``from list'' not a string");
1668 if (PyString_AS_STRING(item
)[0] == '*') {
1671 /* See if the package defines __all__ */
1673 continue; /* Avoid endless recursion */
1674 all
= PyObject_GetAttrString(mod
, "__all__");
1678 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
1684 hasit
= PyObject_HasAttr(mod
, item
);
1686 char *subname
= PyString_AS_STRING(item
);
1689 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
1690 PyErr_SetString(PyExc_ValueError
,
1691 "Module name too long");
1698 submod
= import_submodule(mod
, subname
, buf
);
1700 if (submod
== NULL
) {
1712 import_submodule(mod
, subname
, fullname
)
1713 PyObject
*mod
; /* May be None */
1717 PyObject
*modules
= PyImport_GetModuleDict();
1721 if mod == None: subname == fullname
1722 else: mod.__name__ + "." + subname == fullname
1725 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
1730 char buf
[MAXPATHLEN
+1];
1731 struct filedescr
*fdp
;
1737 path
= PyObject_GetAttrString(mod
, "__path__");
1746 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1749 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
1755 m
= load_module(fullname
, fp
, buf
, fdp
->type
);
1758 if (m
!= NULL
&& mod
!= Py_None
) {
1759 if (PyObject_SetAttrString(mod
, subname
, m
) < 0) {
1770 /* Re-import a module of any kind and return its module object, WITH
1771 INCREMENTED REFERENCE COUNT */
1774 PyImport_ReloadModule(m
)
1777 PyObject
*modules
= PyImport_GetModuleDict();
1778 PyObject
*path
= NULL
;
1779 char *name
, *subname
;
1780 char buf
[MAXPATHLEN
+1];
1781 struct filedescr
*fdp
;
1784 if (m
== NULL
|| !PyModule_Check(m
)) {
1785 PyErr_SetString(PyExc_TypeError
,
1786 "reload() argument must be module");
1789 name
= PyModule_GetName(m
);
1792 if (m
!= PyDict_GetItemString(modules
, name
)) {
1793 PyErr_Format(PyExc_ImportError
,
1794 "reload(): module %.200s not in sys.modules",
1798 subname
= strrchr(name
, '.');
1799 if (subname
== NULL
)
1802 PyObject
*parentname
, *parent
;
1803 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
1804 if (parentname
== NULL
)
1806 parent
= PyDict_GetItem(modules
, parentname
);
1807 Py_DECREF(parentname
);
1808 if (parent
== NULL
) {
1809 PyErr_Format(PyExc_ImportError
,
1810 "reload(): parent %.200s not in sys.modules",
1815 path
= PyObject_GetAttrString(parent
, "__path__");
1820 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1824 m
= load_module(name
, fp
, buf
, fdp
->type
);
1831 /* Higher-level import emulator which emulates the "import" statement
1832 more accurately -- it invokes the __import__() function from the
1833 builtins of the current globals. This means that the import is
1834 done using whatever import hooks are installed in the current
1835 environment, e.g. by "rexec".
1836 A dummy list ["__doc__"] is passed as the 4th argument so that
1837 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1838 will return <module "gencache"> instead of <module "win32com">. */
1841 PyImport_Import(module_name
)
1842 PyObject
*module_name
;
1844 static PyObject
*silly_list
= NULL
;
1845 static PyObject
*builtins_str
= NULL
;
1846 static PyObject
*import_str
= NULL
;
1847 static PyObject
*standard_builtins
= NULL
;
1848 PyObject
*globals
= NULL
;
1849 PyObject
*import
= NULL
;
1850 PyObject
*builtins
= NULL
;
1853 /* Initialize constant string objects */
1854 if (silly_list
== NULL
) {
1855 import_str
= PyString_InternFromString("__import__");
1856 if (import_str
== NULL
)
1858 builtins_str
= PyString_InternFromString("__builtins__");
1859 if (builtins_str
== NULL
)
1861 silly_list
= Py_BuildValue("[s]", "__doc__");
1862 if (silly_list
== NULL
)
1866 /* Get the builtins from current globals */
1867 globals
= PyEval_GetGlobals();
1868 if(globals
!= NULL
) {
1870 builtins
= PyObject_GetItem(globals
, builtins_str
);
1871 if (builtins
== NULL
)
1875 /* No globals -- use standard builtins, and fake globals */
1878 if (standard_builtins
== NULL
) {
1880 PyImport_ImportModule("__builtin__");
1881 if (standard_builtins
== NULL
)
1885 builtins
= standard_builtins
;
1886 Py_INCREF(builtins
);
1887 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
1888 if (globals
== NULL
)
1892 /* Get the __import__ function from the builtins */
1893 if (PyDict_Check(builtins
))
1894 import
=PyObject_GetItem(builtins
, import_str
);
1896 import
=PyObject_GetAttr(builtins
, import_str
);
1900 /* Call the _import__ function with the proper argument list */
1901 r
= PyObject_CallFunction(import
, "OOOO",
1902 module_name
, globals
, globals
, silly_list
);
1905 Py_XDECREF(globals
);
1906 Py_XDECREF(builtins
);
1913 /* Module 'imp' provides Python access to the primitives used for
1918 imp_get_magic(self
, args
)
1924 if (!PyArg_ParseTuple(args
, ""))
1926 buf
[0] = (char) ((MAGIC
>> 0) & 0xff);
1927 buf
[1] = (char) ((MAGIC
>> 8) & 0xff);
1928 buf
[2] = (char) ((MAGIC
>> 16) & 0xff);
1929 buf
[3] = (char) ((MAGIC
>> 24) & 0xff);
1931 return PyString_FromStringAndSize(buf
, 4);
1935 imp_get_suffixes(self
, args
)
1940 struct filedescr
*fdp
;
1942 if (!PyArg_ParseTuple(args
, ""))
1944 list
= PyList_New(0);
1947 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1948 PyObject
*item
= Py_BuildValue("ssi",
1949 fdp
->suffix
, fdp
->mode
, fdp
->type
);
1954 if (PyList_Append(list
, item
) < 0) {
1965 call_find_module(name
, path
)
1967 PyObject
*path
; /* list or None or NULL */
1969 extern int fclose
Py_PROTO((FILE *));
1970 PyObject
*fob
, *ret
;
1971 struct filedescr
*fdp
;
1972 char pathname
[MAXPATHLEN
+1];
1976 if (path
== Py_None
)
1978 fdp
= find_module(name
, path
, pathname
, MAXPATHLEN
+1, &fp
);
1982 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
1992 ret
= Py_BuildValue("Os(ssi)",
1993 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
1999 imp_find_module(self
, args
)
2004 PyObject
*path
= NULL
;
2005 if (!PyArg_ParseTuple(args
, "s|O", &name
, &path
))
2007 return call_find_module(name
, path
);
2011 imp_init_builtin(self
, args
)
2018 if (!PyArg_ParseTuple(args
, "s", &name
))
2020 ret
= init_builtin(name
);
2027 m
= PyImport_AddModule(name
);
2033 imp_init_frozen(self
, args
)
2040 if (!PyArg_ParseTuple(args
, "s", &name
))
2042 ret
= PyImport_ImportFrozenModule(name
);
2049 m
= PyImport_AddModule(name
);
2055 imp_get_frozen_object(self
, args
)
2061 if (!PyArg_ParseTuple(args
, "s", &name
))
2063 return get_frozen_object(name
);
2067 imp_is_builtin(self
, args
)
2072 if (!PyArg_ParseTuple(args
, "s", &name
))
2074 return PyInt_FromLong(is_builtin(name
));
2078 imp_is_frozen(self
, args
)
2084 if (!PyArg_ParseTuple(args
, "s", &name
))
2086 p
= find_frozen(name
);
2087 return PyInt_FromLong((long) (p
== NULL
? 0 : p
->size
));
2091 get_file(pathname
, fob
, mode
)
2098 fp
= fopen(pathname
, mode
);
2100 PyErr_SetFromErrno(PyExc_IOError
);
2103 fp
= PyFile_AsFile(fob
);
2105 PyErr_SetString(PyExc_ValueError
,
2106 "bad/closed file object");
2112 imp_load_compiled(self
, args
)
2118 PyObject
*fob
= NULL
;
2121 if (!PyArg_ParseTuple(args
, "ss|O!", &name
, &pathname
,
2122 &PyFile_Type
, &fob
))
2124 fp
= get_file(pathname
, fob
, "rb");
2127 m
= load_compiled_module(name
, pathname
, fp
);
2134 imp_load_dynamic(self
, args
)
2140 PyObject
*fob
= NULL
;
2143 if (!PyArg_ParseTuple(args
, "ss|O!", &name
, &pathname
,
2144 &PyFile_Type
, &fob
))
2147 fp
= get_file(pathname
, fob
, "r");
2151 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2156 imp_load_source(self
, args
)
2162 PyObject
*fob
= NULL
;
2165 if (!PyArg_ParseTuple(args
, "ss|O!", &name
, &pathname
,
2166 &PyFile_Type
, &fob
))
2168 fp
= get_file(pathname
, fob
, "r");
2171 m
= load_source_module(name
, pathname
, fp
);
2179 imp_load_resource(self
, args
)
2187 if (!PyArg_ParseTuple(args
, "ss", &name
, &pathname
))
2189 m
= PyMac_LoadResourceModule(name
, pathname
);
2192 #endif /* macintosh */
2195 imp_load_module(self
, args
)
2202 char *suffix
; /* Unused */
2207 if (!PyArg_ParseTuple(args
, "sOs(ssi)",
2208 &name
, &fob
, &pathname
,
2209 &suffix
, &mode
, &type
))
2211 if (*mode
&& (*mode
!= 'r' || strchr(mode
, '+') != NULL
)) {
2212 PyErr_Format(PyExc_ValueError
,
2213 "invalid file open mode %.200s", mode
);
2219 if (!PyFile_Check(fob
)) {
2220 PyErr_SetString(PyExc_ValueError
,
2221 "load_module arg#2 should be a file or None");
2224 fp
= get_file(pathname
, fob
, mode
);
2228 return load_module(name
, fp
, pathname
, type
);
2232 imp_load_package(self
, args
)
2238 if (!PyArg_ParseTuple(args
, "ss", &name
, &pathname
))
2240 return load_package(name
, pathname
);
2244 imp_new_module(self
, args
)
2249 if (!PyArg_ParseTuple(args
, "s", &name
))
2251 return PyModule_New(name
);
2256 static char doc_imp
[] = "\
2257 This module provides the components needed to build your own\n\
2258 __import__ function. Undocumented functions are obsolete.\n\
2261 static char doc_find_module
[] = "\
2262 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2263 Search for a module. If path is omitted or None, search for a\n\
2264 built-in, frozen or special module and continue search in sys.path.\n\
2265 The module name cannot contain '.'; to search for a submodule of a\n\
2266 package, pass the submodule name and the package's __path__.\
2269 static char doc_load_module
[] = "\
2270 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2271 Load a module, given information returned by find_module().\n\
2272 The module name must include the full package name, if any.\
2275 static char doc_get_magic
[] = "\
2276 get_magic() -> string\n\
2277 Return the magic number for .pyc or .pyo files.\
2280 static char doc_get_suffixes
[] = "\
2281 get_suffixes() -> [(suffix, mode, type), ...]\n\
2282 Return a list of (suffix, mode, type) tuples describing the files\n\
2283 that find_module() looks for.\
2286 static char doc_new_module
[] = "\
2287 new_module(name) -> module\n\
2288 Create a new module. Do not enter it in sys.modules.\n\
2289 The module name must include the full package name, if any.\
2292 static PyMethodDef imp_methods
[] = {
2293 {"find_module", imp_find_module
, 1, doc_find_module
},
2294 {"get_magic", imp_get_magic
, 1, doc_get_magic
},
2295 {"get_suffixes", imp_get_suffixes
, 1, doc_get_suffixes
},
2296 {"load_module", imp_load_module
, 1, doc_load_module
},
2297 {"new_module", imp_new_module
, 1, doc_new_module
},
2298 /* The rest are obsolete */
2299 {"get_frozen_object", imp_get_frozen_object
, 1},
2300 {"init_builtin", imp_init_builtin
, 1},
2301 {"init_frozen", imp_init_frozen
, 1},
2302 {"is_builtin", imp_is_builtin
, 1},
2303 {"is_frozen", imp_is_frozen
, 1},
2304 {"load_compiled", imp_load_compiled
, 1},
2305 {"load_dynamic", imp_load_dynamic
, 1},
2306 {"load_package", imp_load_package
, 1},
2308 {"load_resource", imp_load_resource
, 1},
2310 {"load_source", imp_load_source
, 1},
2311 {NULL
, NULL
} /* sentinel */
2315 setint(d
, name
, value
)
2323 v
= PyInt_FromLong((long)value
);
2324 err
= PyDict_SetItemString(d
, name
, v
);
2334 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2335 NULL
, PYTHON_API_VERSION
);
2336 d
= PyModule_GetDict(m
);
2338 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2339 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2340 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2341 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2342 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2343 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2344 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2345 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2346 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2353 /* API for embedding applications that want to add their own entries to the
2354 table of built-in modules. This should normally be called *before*
2355 Py_Initialize(). When the malloc() or realloc() call fails, -1 is returned
2356 and the existing table is unchanged.
2358 After a similar function by Just van Rossum. */
2361 PyImport_ExtendInittab(newtab
)
2362 struct _inittab
*newtab
;
2364 static struct _inittab
*our_copy
= NULL
;
2368 /* Count the number of entries in both tables */
2369 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2372 return 0; /* Nothing to do */
2373 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2376 /* Allocate new memory for the combined table */
2377 if (our_copy
== NULL
)
2378 p
= malloc((i
+n
+1) * sizeof(struct _inittab
));
2380 p
= realloc(our_copy
, (i
+n
+1) * sizeof(struct _inittab
));
2384 /* Copy the tables into the new memory */
2385 if (our_copy
!= PyImport_Inittab
)
2386 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2387 PyImport_Inittab
= our_copy
= p
;
2388 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2393 /* Shorthand to add a single entry given a name and a function */
2396 PyImport_AppendInittab(name
, initfunc
)
2400 struct _inittab newtab
[2];
2402 memset(newtab
, '\0', sizeof newtab
);
2404 newtab
[0].name
= name
;
2405 newtab
[0].initfunc
= initfunc
;
2407 return PyImport_ExtendInittab(newtab
);