1 /***********************************************************
2 Copyright (c) 2000, BeOpen.com.
3 Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4 Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
7 See the file "Misc/COPYRIGHT" for information on usage and
8 redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9 ******************************************************************/
11 /* Module definition and import implementation */
31 /* We expect that stat exists on most systems.
32 It's confirmed on Unix, Mac and Windows.
33 If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
34 #ifndef DONT_HAVE_STAT
37 #ifndef DONT_HAVE_SYS_TYPES_H
38 #include <sys/types.h>
40 #ifndef DONT_HAVE_SYS_STAT_H
42 #elif defined(HAVE_STAT_H)
46 #if defined(PYCC_VACPP)
47 /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
48 #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
52 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
58 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
61 /* Magic word to reject .pyc files generated by other Python versions */
62 /* Change for each incompatible change */
63 /* The value of CR and LF is incorporated so if you ever read or write
64 a .pyc file in text mode the magic number will be wrong; also, the
65 Apple MPW compiler swaps their values, botching string constants */
66 /* XXX Perhaps the magic number should be frozen and a version field
67 added to the .pyc file header? */
68 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
69 #define MAGIC (50822 | ((long)'\r'<<16) | ((long)'\n'<<24))
71 /* Magic word as global; note that _PyImport_Init() can change the
72 value of this global to accommodate for alterations of how the
73 compiler works which are enabled by command line switches. */
74 static long pyc_magic
= MAGIC
;
76 /* See _PyImport_FixupExtension() below */
77 static PyObject
*extensions
= NULL
;
79 /* This table is defined in config.c: */
80 extern struct _inittab _PyImport_Inittab
[];
82 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
84 /* these tables define the module suffixes that Python recognizes */
85 struct filedescr
* _PyImport_Filetab
= NULL
;
86 static const struct filedescr _PyImport_StandardFiletab
[] = {
87 {".py", "r", PY_SOURCE
},
88 {".pyc", "rb", PY_COMPILED
},
92 /* Initialize things */
97 const struct filedescr
*scan
;
98 struct filedescr
*filetab
;
102 /* prepare _PyImport_Filetab: copy entries from
103 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
105 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
107 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
109 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
110 memcpy(filetab
, _PyImport_DynLoadFiletab
,
111 countD
* sizeof(struct filedescr
));
112 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
113 countS
* sizeof(struct filedescr
));
114 filetab
[countD
+ countS
].suffix
= NULL
;
116 _PyImport_Filetab
= filetab
;
118 if (Py_OptimizeFlag
) {
119 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
120 for (; filetab
->suffix
!= NULL
; filetab
++) {
121 if (strcmp(filetab
->suffix
, ".pyc") == 0)
122 filetab
->suffix
= ".pyo";
126 if (Py_UnicodeFlag
) {
127 /* Fix the pyc_magic so that byte compiled code created
128 using the all-Unicode method doesn't interfere with
129 code created in normal operation mode. */
130 pyc_magic
= MAGIC
+ 1;
137 Py_XDECREF(extensions
);
142 /* Locking primitives to prevent parallel imports of the same module
143 in different threads to return with a partially loaded module.
144 These calls are serialized by the global interpreter lock. */
148 #include "pythread.h"
150 static PyThread_type_lock import_lock
= 0;
151 static long import_lock_thread
= -1;
152 static int import_lock_level
= 0;
157 long me
= PyThread_get_thread_ident();
159 return; /* Too bad */
160 if (import_lock
== NULL
)
161 import_lock
= PyThread_allocate_lock();
162 if (import_lock_thread
== me
) {
166 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0)) {
167 PyThreadState
*tstate
= PyEval_SaveThread();
168 PyThread_acquire_lock(import_lock
, 1);
169 PyEval_RestoreThread(tstate
);
171 import_lock_thread
= me
;
172 import_lock_level
= 1;
178 long me
= PyThread_get_thread_ident();
180 return; /* Too bad */
181 if (import_lock_thread
!= me
)
182 Py_FatalError("unlock_import: not holding the import lock");
184 if (import_lock_level
== 0) {
185 import_lock_thread
= -1;
186 PyThread_release_lock(import_lock
);
192 #define lock_import()
193 #define unlock_import()
200 PyImport_GetModuleDict(void)
202 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
203 if (interp
->modules
== NULL
)
204 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
205 return interp
->modules
;
209 /* List of names to clear in sys */
210 static char* sys_deletes
[] = {
211 "path", "argv", "ps1", "ps2", "exitfunc",
212 "exc_type", "exc_value", "exc_traceback",
213 "last_type", "last_value", "last_traceback",
217 static char* sys_files
[] = {
218 "stdin", "__stdin__",
219 "stdout", "__stdout__",
220 "stderr", "__stderr__",
225 /* Un-initialize things, as good as we can */
228 PyImport_Cleanup(void)
232 PyObject
*key
, *value
, *dict
;
233 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
234 PyObject
*modules
= interp
->modules
;
237 return; /* Already done */
239 /* Delete some special variables first. These are common
240 places where user values hide and people complain when their
241 destructors fail. Since the modules containing them are
242 deleted *last* of all, they would come too late in the normal
243 destruction order. Sigh. */
245 value
= PyDict_GetItemString(modules
, "__builtin__");
246 if (value
!= NULL
&& PyModule_Check(value
)) {
247 dict
= PyModule_GetDict(value
);
249 PySys_WriteStderr("# clear __builtin__._\n");
250 PyDict_SetItemString(dict
, "_", Py_None
);
252 value
= PyDict_GetItemString(modules
, "sys");
253 if (value
!= NULL
&& PyModule_Check(value
)) {
256 dict
= PyModule_GetDict(value
);
257 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
259 PySys_WriteStderr("# clear sys.%s\n", *p
);
260 PyDict_SetItemString(dict
, *p
, Py_None
);
262 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
264 PySys_WriteStderr("# restore sys.%s\n", *p
);
265 v
= PyDict_GetItemString(dict
, *(p
+1));
268 PyDict_SetItemString(dict
, *p
, v
);
272 /* First, delete __main__ */
273 value
= PyDict_GetItemString(modules
, "__main__");
274 if (value
!= NULL
&& PyModule_Check(value
)) {
276 PySys_WriteStderr("# cleanup __main__\n");
277 _PyModule_Clear(value
);
278 PyDict_SetItemString(modules
, "__main__", Py_None
);
281 /* The special treatment of __builtin__ here is because even
282 when it's not referenced as a module, its dictionary is
283 referenced by almost every module's __builtins__. Since
284 deleting a module clears its dictionary (even if there are
285 references left to it), we need to delete the __builtin__
286 module last. Likewise, we don't delete sys until the very
287 end because it is implicitly referenced (e.g. by print).
289 Also note that we 'delete' modules by replacing their entry
290 in the modules dict with None, rather than really deleting
291 them; this avoids a rehash of the modules dictionary and
292 also marks them as "non existent" so they won't be
295 /* Next, repeatedly delete modules with a reference count of
296 one (skipping __builtin__ and sys) and delete them */
300 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
301 if (value
->ob_refcnt
!= 1)
303 if (PyString_Check(key
) && PyModule_Check(value
)) {
304 name
= PyString_AS_STRING(key
);
305 if (strcmp(name
, "__builtin__") == 0)
307 if (strcmp(name
, "sys") == 0)
311 "# cleanup[1] %s\n", name
);
312 _PyModule_Clear(value
);
313 PyDict_SetItem(modules
, key
, Py_None
);
319 /* Next, delete all modules (still skipping __builtin__ and sys) */
321 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
322 if (PyString_Check(key
) && PyModule_Check(value
)) {
323 name
= PyString_AS_STRING(key
);
324 if (strcmp(name
, "__builtin__") == 0)
326 if (strcmp(name
, "sys") == 0)
329 PySys_WriteStderr("# cleanup[2] %s\n", name
);
330 _PyModule_Clear(value
);
331 PyDict_SetItem(modules
, key
, Py_None
);
335 /* Next, delete sys and __builtin__ (in that order) */
336 value
= PyDict_GetItemString(modules
, "sys");
337 if (value
!= NULL
&& PyModule_Check(value
)) {
339 PySys_WriteStderr("# cleanup sys\n");
340 _PyModule_Clear(value
);
341 PyDict_SetItemString(modules
, "sys", Py_None
);
343 value
= PyDict_GetItemString(modules
, "__builtin__");
344 if (value
!= NULL
&& PyModule_Check(value
)) {
346 PySys_WriteStderr("# cleanup __builtin__\n");
347 _PyModule_Clear(value
);
348 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
351 /* Finally, clear and delete the modules directory */
352 PyDict_Clear(modules
);
353 interp
->modules
= NULL
;
358 /* Helper for pythonrun.c -- return magic number */
361 PyImport_GetMagicNumber(void)
367 /* Magic for extension modules (built-in as well as dynamically
368 loaded). To prevent initializing an extension module more than
369 once, we keep a static dictionary 'extensions' keyed by module name
370 (for built-in modules) or by filename (for dynamically loaded
371 modules), containing these modules. A copy od the module's
372 dictionary is stored by calling _PyImport_FixupExtension()
373 immediately after the module initialization function succeeds. A
374 copy can be retrieved from there by calling
375 _PyImport_FindExtension(). */
378 _PyImport_FixupExtension(char *name
, char *filename
)
380 PyObject
*modules
, *mod
, *dict
, *copy
;
381 if (extensions
== NULL
) {
382 extensions
= PyDict_New();
383 if (extensions
== NULL
)
386 modules
= PyImport_GetModuleDict();
387 mod
= PyDict_GetItemString(modules
, name
);
388 if (mod
== NULL
|| !PyModule_Check(mod
)) {
389 PyErr_Format(PyExc_SystemError
,
390 "_PyImport_FixupExtension: module %.200s not loaded", name
);
393 dict
= PyModule_GetDict(mod
);
396 copy
= PyObject_CallMethod(dict
, "copy", "");
399 PyDict_SetItemString(extensions
, filename
, copy
);
405 _PyImport_FindExtension(char *name
, char *filename
)
407 PyObject
*dict
, *mod
, *mdict
, *result
;
408 if (extensions
== NULL
)
410 dict
= PyDict_GetItemString(extensions
, filename
);
413 mod
= PyImport_AddModule(name
);
416 mdict
= PyModule_GetDict(mod
);
419 result
= PyObject_CallMethod(mdict
, "update", "O", dict
);
424 PySys_WriteStderr("import %s # previously loaded (%s)\n",
430 /* Get the module object corresponding to a module name.
431 First check the modules dictionary if there's one there,
432 if not, create a new one and insert in in the modules dictionary.
433 Because the former action is most common, THIS DOES NOT RETURN A
437 PyImport_AddModule(char *name
)
439 PyObject
*modules
= PyImport_GetModuleDict();
442 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
445 m
= PyModule_New(name
);
448 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
452 Py_DECREF(m
); /* Yes, it still exists, in modules! */
458 /* Execute a code object in a module and return the module object
459 WITH INCREMENTED REFERENCE COUNT */
462 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
464 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
468 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
470 PyObject
*modules
= PyImport_GetModuleDict();
473 m
= PyImport_AddModule(name
);
476 d
= PyModule_GetDict(m
);
477 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
478 if (PyDict_SetItemString(d
, "__builtins__",
479 PyEval_GetBuiltins()) != 0)
482 /* Remember the filename as the __file__ attribute */
484 if (pathname
!= NULL
) {
485 v
= PyString_FromString(pathname
);
490 v
= ((PyCodeObject
*)co
)->co_filename
;
493 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
494 PyErr_Clear(); /* Not important enough to report */
497 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
502 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
503 PyErr_Format(PyExc_ImportError
,
504 "Loaded module %.200s not found in sys.modules",
515 /* Given a pathname for a Python source file, fill a buffer with the
516 pathname for the corresponding compiled file. Return the pathname
517 for the compiled file, or NULL if there's no space in the buffer.
518 Doesn't set an exception. */
521 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
525 len
= strlen(pathname
);
528 strcpy(buf
, pathname
);
529 strcpy(buf
+len
, Py_OptimizeFlag
? "o" : "c");
535 /* Given a pathname for a Python source file, its time of last
536 modification, and a pathname for a compiled file, check whether the
537 compiled file represents the same version of the source. If so,
538 return a FILE pointer for the compiled file, positioned just after
539 the header; if not, return NULL.
540 Doesn't set an exception. */
543 check_compiled_module(char *pathname
, long mtime
, char *cpathname
)
549 fp
= fopen(cpathname
, "rb");
552 magic
= PyMarshal_ReadLongFromFile(fp
);
553 if (magic
!= pyc_magic
) {
555 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
559 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
560 if (pyc_mtime
!= mtime
) {
562 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
567 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
572 /* Read a code object from a file and check it for validity */
574 static PyCodeObject
*
575 read_compiled_module(char *cpathname
, FILE *fp
)
579 co
= PyMarshal_ReadObjectFromFile(fp
);
580 /* Ugly: rd_object() may return NULL with or without error */
581 if (co
== NULL
|| !PyCode_Check(co
)) {
582 if (!PyErr_Occurred())
583 PyErr_Format(PyExc_ImportError
,
584 "Non-code object in %.200s", cpathname
);
588 return (PyCodeObject
*)co
;
592 /* Load a module from a compiled file, execute it, and return its
593 module object WITH INCREMENTED REFERENCE COUNT */
596 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
602 magic
= PyMarshal_ReadLongFromFile(fp
);
603 if (magic
!= pyc_magic
) {
604 PyErr_Format(PyExc_ImportError
,
605 "Bad magic number in %.200s", cpathname
);
608 (void) PyMarshal_ReadLongFromFile(fp
);
609 co
= read_compiled_module(cpathname
, fp
);
613 PySys_WriteStderr("import %s # precompiled from %s\n",
615 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
621 /* Parse a source file and return the corresponding code object */
623 static PyCodeObject
*
624 parse_source_module(char *pathname
, FILE *fp
)
629 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
632 co
= PyNode_Compile(n
, pathname
);
639 /* Write a compiled module to a file, placing the time of last
640 modification of its source into the header.
641 Errors are ignored, if a write error occurs an attempt is made to
645 write_compiled_module(PyCodeObject
*co
, char *cpathname
, long mtime
)
649 fp
= fopen(cpathname
, "wb");
653 "# can't create %s\n", cpathname
);
656 PyMarshal_WriteLongToFile(pyc_magic
, fp
);
657 /* First write a 0 for mtime */
658 PyMarshal_WriteLongToFile(0L, fp
);
659 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
662 PySys_WriteStderr("# can't write %s\n", cpathname
);
663 /* Don't keep partial file */
665 (void) unlink(cpathname
);
668 /* Now write the true mtime */
670 PyMarshal_WriteLongToFile(mtime
, fp
);
674 PySys_WriteStderr("# wrote %s\n", cpathname
);
676 PyMac_setfiletype(cpathname
, 'Pyth', 'PYC ');
681 /* Load a source module from a given file and return its module
682 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
683 byte-compiled file, use that instead. */
686 load_source_module(char *name
, char *pathname
, FILE *fp
)
690 char buf
[MAXPATHLEN
+1];
695 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
698 #if SIZEOF_TIME_T > 4
699 /* Python's .pyc timestamp handling presumes that the timestamp fits
700 in 4 bytes. This will be fine until sometime in the year 2038,
701 when a 4-byte signed time_t will overflow.
704 PyErr_SetString(PyExc_OverflowError
,
705 "modification time overflows a 4 bytes");
709 cpathname
= make_compiled_pathname(pathname
, buf
, (size_t)MAXPATHLEN
+1);
710 if (cpathname
!= NULL
&&
711 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
712 co
= read_compiled_module(cpathname
, fpc
);
717 PySys_WriteStderr("import %s # precompiled from %s\n",
719 pathname
= cpathname
;
722 co
= parse_source_module(pathname
, fp
);
726 PySys_WriteStderr("import %s # from %s\n",
728 write_compiled_module(co
, cpathname
, mtime
);
730 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
738 static PyObject
*load_module(char *, FILE *, char *, int);
739 static struct filedescr
*find_module(char *, PyObject
*,
740 char *, size_t, FILE **);
741 static struct _frozen
*find_frozen(char *name
);
743 /* Load a package and return its module object WITH INCREMENTED
747 load_package(char *name
, char *pathname
)
749 PyObject
*m
, *d
, *file
, *path
;
751 char buf
[MAXPATHLEN
+1];
753 struct filedescr
*fdp
;
755 m
= PyImport_AddModule(name
);
759 PySys_WriteStderr("import %s # directory %s\n",
761 d
= PyModule_GetDict(m
);
762 file
= PyString_FromString(pathname
);
765 path
= Py_BuildValue("[O]", file
);
770 err
= PyDict_SetItemString(d
, "__file__", file
);
772 err
= PyDict_SetItemString(d
, "__path__", path
);
778 fdp
= find_module("__init__", path
, buf
, sizeof(buf
), &fp
);
780 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
787 m
= load_module(name
, fp
, buf
, fdp
->type
);
797 /* Helper to test for built-in module */
800 is_builtin(char *name
)
803 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
804 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
805 if (PyImport_Inittab
[i
].initfunc
== NULL
)
815 /* Search the path (default sys.path) for a module. Return the
816 corresponding filedescr struct, and (via return arguments) the
817 pathname and an open file. Return NULL if the module is not found. */
820 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
824 #ifdef CHECK_IMPORT_CASE
825 static int check_case(char *, int, int, char *);
828 static int find_init_module(char *); /* Forward */
830 static struct filedescr
*
831 find_module(char *realname
, PyObject
*path
, char *buf
, size_t buflen
,
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 if (strlen(realname
) > MAXPATHLEN
) {
846 PyErr_SetString(PyExc_OverflowError
, "module name is too long");
849 strcpy(name
, realname
);
851 if (path
!= NULL
&& PyString_Check(path
)) {
852 /* Submodule of "frozen" package:
853 Set name to the fullname, path to NULL
854 and continue as "usual" */
855 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
856 PyErr_SetString(PyExc_ImportError
,
857 "full frozen module name too long");
860 strcpy(buf
, PyString_AsString(path
));
867 if (is_builtin(name
)) {
871 if ((f
= find_frozen(name
)) != NULL
) {
877 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
883 path
= PySys_GetObject("path");
885 if (path
== NULL
|| !PyList_Check(path
)) {
886 PyErr_SetString(PyExc_ImportError
,
887 "sys.path must be a list of directory names");
890 npath
= PyList_Size(path
);
891 namelen
= strlen(name
);
892 for (i
= 0; i
< npath
; i
++) {
893 PyObject
*v
= PyList_GetItem(path
, i
);
894 if (!PyString_Check(v
))
896 len
= PyString_Size(v
);
897 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
)
898 continue; /* Too long */
899 strcpy(buf
, PyString_AsString(v
));
900 if (strlen(buf
) != len
)
901 continue; /* v contains '\0' */
903 #ifdef INTERN_STRINGS
905 ** Speedup: each sys.path item is interned, and
906 ** FindResourceModule remembers which items refer to
907 ** folders (so we don't have to bother trying to look
908 ** into them for resources).
910 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
911 v
= PyList_GET_ITEM(path
, i
);
913 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
914 static struct filedescr resfiledescr
=
915 {"", "", PY_RESOURCE
};
917 return &resfiledescr
;
919 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
920 static struct filedescr resfiledescr
=
921 {"", "", PY_CODERESOURCE
};
923 return &resfiledescr
;
926 if (len
> 0 && buf
[len
-1] != SEP
928 && buf
[len
-1] != ALTSEP
932 #ifdef IMPORT_8x3_NAMES
933 /* see if we are searching in directory dos-8x3 */
934 if (len
> 7 && !strncmp(buf
+ len
- 8, "dos-8x3", 7)){
936 char ch
; /* limit name to 8 lower-case characters */
937 for (j
= 0; (ch
= name
[j
]) && j
< 8; j
++)
939 buf
[len
++] = tolower(ch
);
943 else /* Not in dos-8x3, use the full name */
946 strcpy(buf
+len
, name
);
950 if (stat(buf
, &statbuf
) == 0) {
951 if (S_ISDIR(statbuf
.st_mode
)) {
952 if (find_init_module(buf
)) {
953 #ifdef CHECK_IMPORT_CASE
954 if (!check_case(buf
, len
, namelen
,
963 /* XXX How are you going to test for directories? */
966 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
968 fp
= fopen(buf
, fdp
->mode
);
970 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
971 strcpy(buf
+len
, fdp
->suffix
);
972 if (Py_VerboseFlag
> 1)
973 PySys_WriteStderr("# trying %s\n", buf
);
974 fp
= fopen(buf
, fdp
->mode
);
978 #endif /* !macintosh */
983 PyErr_Format(PyExc_ImportError
,
984 "No module named %.200s", name
);
987 #ifdef CHECK_IMPORT_CASE
988 if (!check_case(buf
, len
, namelen
, name
)) {
998 #ifdef CHECK_IMPORT_CASE
1001 #include <windows.h>
1007 /* Return 1 if s is an 8.3 filename in ALLCAPS */
1009 char *dot
= strchr(s
, '.');
1010 char *end
= strchr(s
, '\0');
1013 return 0; /* More than 8 before '.' */
1015 return 0; /* More than 3 after '.' */
1016 end
= strchr(dot
+1, '.');
1018 return 0; /* More than one dot */
1021 return 0; /* More than 8 and no dot */
1022 while ((c
= *s
++)) {
1030 check_case(char *buf
, int len
, int namelen
, char *name
)
1032 WIN32_FIND_DATA data
;
1034 if (getenv("PYTHONCASEOK") != NULL
)
1036 h
= FindFirstFile(buf
, &data
);
1037 if (h
== INVALID_HANDLE_VALUE
) {
1038 PyErr_Format(PyExc_NameError
,
1039 "Can't find file for module %.100s\n(filename %.300s)",
1044 if (allcaps8x3(data
.cFileName
)) {
1045 /* Skip the test if the filename is ALL.CAPS. This can
1046 happen in certain circumstances beyond our control,
1047 e.g. when software is installed under NT on a FAT
1048 filesystem and then the same FAT filesystem is used
1049 under Windows 95. */
1052 if (strncmp(data
.cFileName
, name
, namelen
) != 0) {
1053 strcpy(buf
+len
-namelen
, data
.cFileName
);
1054 PyErr_Format(PyExc_NameError
,
1055 "Case mismatch for module name %.100s\n(filename %.300s)",
1061 #endif /* MS_WIN32 */
1064 #include <TextUtils.h>
1066 #include "TFileSpec.h" /* for Path2FSSpec() */
1069 check_case(char *buf
, int len
, int namelen
, char *name
)
1074 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1076 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1077 the way, which is fine for all directories, but here we need
1078 the original name of the alias file (say, Dlg.ppc.slb, not
1079 toolboxmodules.ppc.slb). */
1081 err
= Path2FSSpec(buf
, &fss
);
1083 colon
= strrchr(buf
, ':'); /* find filename */
1085 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1086 Pstring(colon
+1), &fss
);
1088 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1093 PyErr_Format(PyExc_NameError
,
1094 "Can't find file for module %.100s\n(filename %.300s)",
1098 if ( namelen
> fss
.name
[0] || strncmp(name
, (char *)fss
.name
+1, namelen
) != 0 ) {
1099 PyErr_Format(PyExc_NameError
,
1100 "Case mismatch for module name %.100s\n(filename %.300s)",
1106 #endif /* macintosh */
1112 check_case(char *buf
, int len
, int namelen
, char *name
)
1117 if (getenv("PYTHONCASEOK") != NULL
)
1119 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1121 PyErr_Format(PyExc_NameError
,
1122 "Can't find file for module %.100s\n(filename %.300s)",
1127 if (strncmp(ffblk
.ff_name
, name
, namelen
) != 0) {
1128 strcpy(buf
+len
-namelen
, ffblk
.ff_name
);
1129 PyErr_Format(PyExc_NameError
,
1130 "Case mismatch for module name %.100s\n(filename %.300s)",
1138 #endif /* CHECK_IMPORT_CASE */
1141 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1143 find_init_module(char *buf
)
1145 size_t save_len
= strlen(buf
);
1146 size_t i
= save_len
;
1147 struct stat statbuf
;
1149 if (save_len
+ 13 >= MAXPATHLEN
)
1152 strcpy(buf
+i
, "__init__.py");
1153 if (stat(buf
, &statbuf
) == 0) {
1154 buf
[save_len
] = '\0';
1158 if (Py_OptimizeFlag
)
1162 if (stat(buf
, &statbuf
) == 0) {
1163 buf
[save_len
] = '\0';
1166 buf
[save_len
] = '\0';
1169 #endif /* HAVE_STAT */
1172 static int init_builtin(char *); /* Forward */
1174 /* Load an external module using the default search path and return
1175 its module object WITH INCREMENTED REFERENCE COUNT */
1178 load_module(char *name
, FILE *fp
, char *buf
, int type
)
1184 /* First check that there's an open file (if we need one) */
1189 PyErr_Format(PyExc_ValueError
,
1190 "file object required for import (type code %d)",
1199 m
= load_source_module(name
, buf
, fp
);
1203 m
= load_compiled_module(name
, buf
, fp
);
1206 #ifdef HAVE_DYNAMIC_LOADING
1208 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1214 m
= PyMac_LoadResourceModule(name
, buf
);
1216 case PY_CODERESOURCE
:
1217 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1222 m
= load_package(name
, buf
);
1227 if (buf
!= NULL
&& buf
[0] != '\0')
1229 if (type
== C_BUILTIN
)
1230 err
= init_builtin(name
);
1232 err
= PyImport_ImportFrozenModule(name
);
1236 PyErr_Format(PyExc_ImportError
,
1237 "Purported %s module %.200s not found",
1239 "builtin" : "frozen",
1243 modules
= PyImport_GetModuleDict();
1244 m
= PyDict_GetItemString(modules
, name
);
1248 "%s module %.200s not properly initialized",
1250 "builtin" : "frozen",
1258 PyErr_Format(PyExc_ImportError
,
1259 "Don't know how to import %.200s (type code %d)",
1269 /* Initialize a built-in module.
1270 Return 1 for succes, 0 if the module is not found, and -1 with
1271 an exception set if the initialization failed. */
1274 init_builtin(char *name
)
1279 if ((mod
= _PyImport_FindExtension(name
, name
)) != NULL
)
1282 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1283 if (strcmp(name
, p
->name
) == 0) {
1284 if (p
->initfunc
== NULL
) {
1285 PyErr_Format(PyExc_ImportError
,
1286 "Cannot re-init internal module %.200s",
1291 PySys_WriteStderr("import %s # builtin\n", name
);
1293 if (PyErr_Occurred())
1295 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1304 /* Frozen modules */
1306 static struct _frozen
*
1307 find_frozen(char *name
)
1311 for (p
= PyImport_FrozenModules
; ; p
++) {
1312 if (p
->name
== NULL
)
1314 if (strcmp(p
->name
, name
) == 0)
1321 get_frozen_object(char *name
)
1323 struct _frozen
*p
= find_frozen(name
);
1327 PyErr_Format(PyExc_ImportError
,
1328 "No such frozen object named %.200s",
1335 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1338 /* Initialize a frozen module.
1339 Return 1 for succes, 0 if the module is not found, and -1 with
1340 an exception set if the initialization failed.
1341 This function is also used from frozenmain.c */
1344 PyImport_ImportFrozenModule(char *name
)
1346 struct _frozen
*p
= find_frozen(name
);
1355 ispackage
= (size
< 0);
1359 PySys_WriteStderr("import %s # frozen%s\n",
1360 name
, ispackage
? " package" : "");
1361 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1364 if (!PyCode_Check(co
)) {
1366 PyErr_Format(PyExc_TypeError
,
1367 "frozen object %.200s is not a code object",
1372 /* Set __path__ to the package name */
1375 m
= PyImport_AddModule(name
);
1378 d
= PyModule_GetDict(m
);
1379 s
= PyString_InternFromString(name
);
1382 err
= PyDict_SetItemString(d
, "__path__", s
);
1387 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1396 /* Import a module, either built-in, frozen, or external, and return
1397 its module object WITH INCREMENTED REFERENCE COUNT */
1400 PyImport_ImportModule(char *name
)
1402 static PyObject
*fromlist
= NULL
;
1403 if (fromlist
== NULL
&& strchr(name
, '.') != NULL
) {
1404 fromlist
= Py_BuildValue("[s]", "*");
1405 if (fromlist
== NULL
)
1408 return PyImport_ImportModuleEx(name
, NULL
, NULL
, fromlist
);
1411 /* Forward declarations for helper routines */
1412 static PyObject
*get_parent(PyObject
*globals
, char *buf
, int *p_buflen
);
1413 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1414 char **p_name
, char *buf
, int *p_buflen
);
1415 static int mark_miss(char *name
);
1416 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1417 char *buf
, int buflen
, int recursive
);
1418 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1420 /* The Magnum Opus of dotted-name import :-) */
1423 import_module_ex(char *name
, PyObject
*globals
, PyObject
*locals
,
1426 char buf
[MAXPATHLEN
+1];
1428 PyObject
*parent
, *head
, *next
, *tail
;
1430 parent
= get_parent(globals
, buf
, &buflen
);
1434 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1441 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1450 if (fromlist
!= NULL
) {
1451 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1455 if (fromlist
== NULL
) {
1461 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1470 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
1475 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1481 get_parent(PyObject
*globals
, char *buf
, int *p_buflen
)
1483 static PyObject
*namestr
= NULL
;
1484 static PyObject
*pathstr
= NULL
;
1485 PyObject
*modname
, *modpath
, *modules
, *parent
;
1487 if (globals
== NULL
|| !PyDict_Check(globals
))
1490 if (namestr
== NULL
) {
1491 namestr
= PyString_InternFromString("__name__");
1492 if (namestr
== NULL
)
1495 if (pathstr
== NULL
) {
1496 pathstr
= PyString_InternFromString("__path__");
1497 if (pathstr
== NULL
)
1503 modname
= PyDict_GetItem(globals
, namestr
);
1504 if (modname
== NULL
|| !PyString_Check(modname
))
1507 modpath
= PyDict_GetItem(globals
, pathstr
);
1508 if (modpath
!= NULL
) {
1509 int len
= PyString_GET_SIZE(modname
);
1510 if (len
> MAXPATHLEN
) {
1511 PyErr_SetString(PyExc_ValueError
,
1512 "Module name too long");
1515 strcpy(buf
, PyString_AS_STRING(modname
));
1519 char *start
= PyString_AS_STRING(modname
);
1520 char *lastdot
= strrchr(start
, '.');
1522 if (lastdot
== NULL
)
1524 len
= lastdot
- start
;
1525 if (len
>= MAXPATHLEN
) {
1526 PyErr_SetString(PyExc_ValueError
,
1527 "Module name too long");
1530 strncpy(buf
, start
, len
);
1535 modules
= PyImport_GetModuleDict();
1536 parent
= PyDict_GetItemString(modules
, buf
);
1540 /* We expect, but can't guarantee, if parent != None, that:
1541 - parent.__name__ == buf
1542 - parent.__dict__ is globals
1543 If this is violated... Who cares? */
1546 /* altmod is either None or same as mod */
1548 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
1551 char *name
= *p_name
;
1552 char *dot
= strchr(name
, '.');
1566 PyErr_SetString(PyExc_ValueError
,
1567 "Empty module name");
1571 p
= buf
+ *p_buflen
;
1574 if (p
+len
-buf
>= MAXPATHLEN
) {
1575 PyErr_SetString(PyExc_ValueError
,
1576 "Module name too long");
1579 strncpy(p
, name
, len
);
1581 *p_buflen
= p
+len
-buf
;
1583 result
= import_submodule(mod
, p
, buf
);
1584 if (result
== Py_None
&& altmod
!= mod
) {
1586 /* Here, altmod must be None and mod must not be None */
1587 result
= import_submodule(altmod
, p
, p
);
1588 if (result
!= NULL
&& result
!= Py_None
) {
1589 if (mark_miss(buf
) != 0) {
1593 strncpy(buf
, name
, len
);
1601 if (result
== Py_None
) {
1603 PyErr_Format(PyExc_ImportError
,
1604 "No module named %.200s", name
);
1612 mark_miss(char *name
)
1614 PyObject
*modules
= PyImport_GetModuleDict();
1615 return PyDict_SetItemString(modules
, name
, Py_None
);
1619 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, int buflen
,
1624 if (!PyObject_HasAttrString(mod
, "__path__"))
1627 for (i
= 0; ; i
++) {
1628 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
1631 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1637 if (!PyString_Check(item
)) {
1638 PyErr_SetString(PyExc_TypeError
,
1639 "Item in ``from list'' not a string");
1643 if (PyString_AS_STRING(item
)[0] == '*') {
1646 /* See if the package defines __all__ */
1648 continue; /* Avoid endless recursion */
1649 all
= PyObject_GetAttrString(mod
, "__all__");
1653 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
1659 hasit
= PyObject_HasAttr(mod
, item
);
1661 char *subname
= PyString_AS_STRING(item
);
1664 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
1665 PyErr_SetString(PyExc_ValueError
,
1666 "Module name too long");
1673 submod
= import_submodule(mod
, subname
, buf
);
1675 if (submod
== NULL
) {
1687 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
1689 PyObject
*modules
= PyImport_GetModuleDict();
1693 if mod == None: subname == fullname
1694 else: mod.__name__ + "." + subname == fullname
1697 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
1702 char buf
[MAXPATHLEN
+1];
1703 struct filedescr
*fdp
;
1709 path
= PyObject_GetAttrString(mod
, "__path__");
1718 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1721 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
1727 m
= load_module(fullname
, fp
, buf
, fdp
->type
);
1730 if (m
!= NULL
&& mod
!= Py_None
) {
1731 if (PyObject_SetAttrString(mod
, subname
, m
) < 0) {
1742 /* Re-import a module of any kind and return its module object, WITH
1743 INCREMENTED REFERENCE COUNT */
1746 PyImport_ReloadModule(PyObject
*m
)
1748 PyObject
*modules
= PyImport_GetModuleDict();
1749 PyObject
*path
= NULL
;
1750 char *name
, *subname
;
1751 char buf
[MAXPATHLEN
+1];
1752 struct filedescr
*fdp
;
1755 if (m
== NULL
|| !PyModule_Check(m
)) {
1756 PyErr_SetString(PyExc_TypeError
,
1757 "reload() argument must be module");
1760 name
= PyModule_GetName(m
);
1763 if (m
!= PyDict_GetItemString(modules
, name
)) {
1764 PyErr_Format(PyExc_ImportError
,
1765 "reload(): module %.200s not in sys.modules",
1769 subname
= strrchr(name
, '.');
1770 if (subname
== NULL
)
1773 PyObject
*parentname
, *parent
;
1774 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
1775 if (parentname
== NULL
)
1777 parent
= PyDict_GetItem(modules
, parentname
);
1778 Py_DECREF(parentname
);
1779 if (parent
== NULL
) {
1780 PyErr_Format(PyExc_ImportError
,
1781 "reload(): parent %.200s not in sys.modules",
1786 path
= PyObject_GetAttrString(parent
, "__path__");
1791 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1795 m
= load_module(name
, fp
, buf
, fdp
->type
);
1802 /* Higher-level import emulator which emulates the "import" statement
1803 more accurately -- it invokes the __import__() function from the
1804 builtins of the current globals. This means that the import is
1805 done using whatever import hooks are installed in the current
1806 environment, e.g. by "rexec".
1807 A dummy list ["__doc__"] is passed as the 4th argument so that
1808 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1809 will return <module "gencache"> instead of <module "win32com">. */
1812 PyImport_Import(PyObject
*module_name
)
1814 static PyObject
*silly_list
= NULL
;
1815 static PyObject
*builtins_str
= NULL
;
1816 static PyObject
*import_str
= NULL
;
1817 static PyObject
*standard_builtins
= NULL
;
1818 PyObject
*globals
= NULL
;
1819 PyObject
*import
= NULL
;
1820 PyObject
*builtins
= NULL
;
1823 /* Initialize constant string objects */
1824 if (silly_list
== NULL
) {
1825 import_str
= PyString_InternFromString("__import__");
1826 if (import_str
== NULL
)
1828 builtins_str
= PyString_InternFromString("__builtins__");
1829 if (builtins_str
== NULL
)
1831 silly_list
= Py_BuildValue("[s]", "__doc__");
1832 if (silly_list
== NULL
)
1836 /* Get the builtins from current globals */
1837 globals
= PyEval_GetGlobals();
1838 if(globals
!= NULL
) {
1840 builtins
= PyObject_GetItem(globals
, builtins_str
);
1841 if (builtins
== NULL
)
1845 /* No globals -- use standard builtins, and fake globals */
1848 if (standard_builtins
== NULL
) {
1850 PyImport_ImportModule("__builtin__");
1851 if (standard_builtins
== NULL
)
1855 builtins
= standard_builtins
;
1856 Py_INCREF(builtins
);
1857 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
1858 if (globals
== NULL
)
1862 /* Get the __import__ function from the builtins */
1863 if (PyDict_Check(builtins
))
1864 import
=PyObject_GetItem(builtins
, import_str
);
1866 import
=PyObject_GetAttr(builtins
, import_str
);
1870 /* Call the _import__ function with the proper argument list */
1871 r
= PyObject_CallFunction(import
, "OOOO",
1872 module_name
, globals
, globals
, silly_list
);
1875 Py_XDECREF(globals
);
1876 Py_XDECREF(builtins
);
1883 /* Module 'imp' provides Python access to the primitives used for
1888 imp_get_magic(PyObject
*self
, PyObject
*args
)
1892 if (!PyArg_ParseTuple(args
, ":get_magic"))
1894 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
1895 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
1896 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
1897 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
1899 return PyString_FromStringAndSize(buf
, 4);
1903 imp_get_suffixes(PyObject
*self
, PyObject
*args
)
1906 struct filedescr
*fdp
;
1908 if (!PyArg_ParseTuple(args
, ":get_suffixes"))
1910 list
= PyList_New(0);
1913 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1914 PyObject
*item
= Py_BuildValue("ssi",
1915 fdp
->suffix
, fdp
->mode
, fdp
->type
);
1920 if (PyList_Append(list
, item
) < 0) {
1931 call_find_module(char *name
, PyObject
*path
)
1933 extern int fclose(FILE *);
1934 PyObject
*fob
, *ret
;
1935 struct filedescr
*fdp
;
1936 char pathname
[MAXPATHLEN
+1];
1940 if (path
== Py_None
)
1942 fdp
= find_module(name
, path
, pathname
, MAXPATHLEN
+1, &fp
);
1946 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
1956 ret
= Py_BuildValue("Os(ssi)",
1957 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
1963 imp_find_module(PyObject
*self
, PyObject
*args
)
1966 PyObject
*path
= NULL
;
1967 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
1969 return call_find_module(name
, path
);
1973 imp_init_builtin(PyObject
*self
, PyObject
*args
)
1978 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
1980 ret
= init_builtin(name
);
1987 m
= PyImport_AddModule(name
);
1993 imp_init_frozen(PyObject
*self
, PyObject
*args
)
1998 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2000 ret
= PyImport_ImportFrozenModule(name
);
2007 m
= PyImport_AddModule(name
);
2013 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2017 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2019 return get_frozen_object(name
);
2023 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2026 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2028 return PyInt_FromLong(is_builtin(name
));
2032 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2036 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2038 p
= find_frozen(name
);
2039 return PyInt_FromLong((long) (p
== NULL
? 0 : p
->size
));
2043 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2047 fp
= fopen(pathname
, mode
);
2049 PyErr_SetFromErrno(PyExc_IOError
);
2052 fp
= PyFile_AsFile(fob
);
2054 PyErr_SetString(PyExc_ValueError
,
2055 "bad/closed file object");
2061 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2065 PyObject
*fob
= NULL
;
2068 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2069 &PyFile_Type
, &fob
))
2071 fp
= get_file(pathname
, fob
, "rb");
2074 m
= load_compiled_module(name
, pathname
, fp
);
2080 #ifdef HAVE_DYNAMIC_LOADING
2083 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2087 PyObject
*fob
= NULL
;
2090 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2091 &PyFile_Type
, &fob
))
2094 fp
= get_file(pathname
, fob
, "r");
2098 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2102 #endif /* HAVE_DYNAMIC_LOADING */
2105 imp_load_source(PyObject
*self
, PyObject
*args
)
2109 PyObject
*fob
= NULL
;
2112 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2113 &PyFile_Type
, &fob
))
2115 fp
= get_file(pathname
, fob
, "r");
2118 m
= load_source_module(name
, pathname
, fp
);
2126 imp_load_resource(PyObject
*self
, PyObject
*args
)
2132 if (!PyArg_ParseTuple(args
, "ss:load_resource", &name
, &pathname
))
2134 m
= PyMac_LoadResourceModule(name
, pathname
);
2137 #endif /* macintosh */
2140 imp_load_module(PyObject
*self
, PyObject
*args
)
2145 char *suffix
; /* Unused */
2150 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2151 &name
, &fob
, &pathname
,
2152 &suffix
, &mode
, &type
))
2154 if (*mode
&& (*mode
!= 'r' || strchr(mode
, '+') != NULL
)) {
2155 PyErr_Format(PyExc_ValueError
,
2156 "invalid file open mode %.200s", mode
);
2162 if (!PyFile_Check(fob
)) {
2163 PyErr_SetString(PyExc_ValueError
,
2164 "load_module arg#2 should be a file or None");
2167 fp
= get_file(pathname
, fob
, mode
);
2171 return load_module(name
, fp
, pathname
, type
);
2175 imp_load_package(PyObject
*self
, PyObject
*args
)
2179 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2181 return load_package(name
, pathname
);
2185 imp_new_module(PyObject
*self
, PyObject
*args
)
2188 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2190 return PyModule_New(name
);
2195 static char doc_imp
[] = "\
2196 This module provides the components needed to build your own\n\
2197 __import__ function. Undocumented functions are obsolete.\n\
2200 static char doc_find_module
[] = "\
2201 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2202 Search for a module. If path is omitted or None, search for a\n\
2203 built-in, frozen or special module and continue search in sys.path.\n\
2204 The module name cannot contain '.'; to search for a submodule of a\n\
2205 package, pass the submodule name and the package's __path__.\
2208 static char doc_load_module
[] = "\
2209 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2210 Load a module, given information returned by find_module().\n\
2211 The module name must include the full package name, if any.\
2214 static char doc_get_magic
[] = "\
2215 get_magic() -> string\n\
2216 Return the magic number for .pyc or .pyo files.\
2219 static char doc_get_suffixes
[] = "\
2220 get_suffixes() -> [(suffix, mode, type), ...]\n\
2221 Return a list of (suffix, mode, type) tuples describing the files\n\
2222 that find_module() looks for.\
2225 static char doc_new_module
[] = "\
2226 new_module(name) -> module\n\
2227 Create a new module. Do not enter it in sys.modules.\n\
2228 The module name must include the full package name, if any.\
2231 static PyMethodDef imp_methods
[] = {
2232 {"find_module", imp_find_module
, 1, doc_find_module
},
2233 {"get_magic", imp_get_magic
, 1, doc_get_magic
},
2234 {"get_suffixes", imp_get_suffixes
, 1, doc_get_suffixes
},
2235 {"load_module", imp_load_module
, 1, doc_load_module
},
2236 {"new_module", imp_new_module
, 1, doc_new_module
},
2237 /* The rest are obsolete */
2238 {"get_frozen_object", imp_get_frozen_object
, 1},
2239 {"init_builtin", imp_init_builtin
, 1},
2240 {"init_frozen", imp_init_frozen
, 1},
2241 {"is_builtin", imp_is_builtin
, 1},
2242 {"is_frozen", imp_is_frozen
, 1},
2243 {"load_compiled", imp_load_compiled
, 1},
2244 #ifdef HAVE_DYNAMIC_LOADING
2245 {"load_dynamic", imp_load_dynamic
, 1},
2247 {"load_package", imp_load_package
, 1},
2249 {"load_resource", imp_load_resource
, 1},
2251 {"load_source", imp_load_source
, 1},
2252 {NULL
, NULL
} /* sentinel */
2256 setint(PyObject
*d
, char *name
, int value
)
2261 v
= PyInt_FromLong((long)value
);
2262 err
= PyDict_SetItemString(d
, name
, v
);
2272 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2273 NULL
, PYTHON_API_VERSION
);
2274 d
= PyModule_GetDict(m
);
2276 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2277 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2278 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2279 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2280 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2281 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2282 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2283 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2284 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2291 /* API for embedding applications that want to add their own entries
2292 to the table of built-in modules. This should normally be called
2293 *before* Py_Initialize(). When the table resize fails, -1 is
2294 returned and the existing table is unchanged.
2296 After a similar function by Just van Rossum. */
2299 PyImport_ExtendInittab(struct _inittab
*newtab
)
2301 static struct _inittab
*our_copy
= NULL
;
2305 /* Count the number of entries in both tables */
2306 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2309 return 0; /* Nothing to do */
2310 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2313 /* Allocate new memory for the combined table */
2315 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
2319 /* Copy the tables into the new memory */
2320 if (our_copy
!= PyImport_Inittab
)
2321 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2322 PyImport_Inittab
= our_copy
= p
;
2323 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2328 /* Shorthand to add a single entry given a name and a function */
2331 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
2333 struct _inittab newtab
[2];
2335 memset(newtab
, '\0', sizeof newtab
);
2337 newtab
[0].name
= name
;
2338 newtab
[0].initfunc
= initfunc
;
2340 return PyImport_ExtendInittab(newtab
);