2 /* Module definition and import implementation */
22 /* We expect that stat exists on most systems.
23 It's confirmed on Unix, Mac and Windows.
24 If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
25 #ifndef DONT_HAVE_STAT
28 #ifndef DONT_HAVE_SYS_TYPES_H
29 #include <sys/types.h>
32 #ifndef DONT_HAVE_SYS_STAT_H
34 #elif defined(HAVE_STAT_H)
42 #if defined(PYCC_VACPP)
43 /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
44 #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
48 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
54 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
57 /* Magic word to reject .pyc files generated by other Python versions */
58 /* Change for each incompatible change */
59 /* The value of CR and LF is incorporated so if you ever read or write
60 a .pyc file in text mode the magic number will be wrong; also, the
61 Apple MPW compiler swaps their values, botching string constants */
62 /* XXX Perhaps the magic number should be frozen and a version field
63 added to the .pyc file header? */
64 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
65 #define MAGIC (50823 | ((long)'\r'<<16) | ((long)'\n'<<24))
67 /* Magic word as global; note that _PyImport_Init() can change the
68 value of this global to accommodate for alterations of how the
69 compiler works which are enabled by command line switches. */
70 static long pyc_magic
= MAGIC
;
72 /* See _PyImport_FixupExtension() below */
73 static PyObject
*extensions
= NULL
;
75 /* This table is defined in config.c: */
76 extern struct _inittab _PyImport_Inittab
[];
78 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
80 /* these tables define the module suffixes that Python recognizes */
81 struct filedescr
* _PyImport_Filetab
= NULL
;
82 static const struct filedescr _PyImport_StandardFiletab
[] = {
83 {".py", "r", PY_SOURCE
},
84 {".pyc", "rb", PY_COMPILED
},
88 /* Initialize things */
93 const struct filedescr
*scan
;
94 struct filedescr
*filetab
;
98 /* prepare _PyImport_Filetab: copy entries from
99 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
101 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
103 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
105 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
106 memcpy(filetab
, _PyImport_DynLoadFiletab
,
107 countD
* sizeof(struct filedescr
));
108 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
109 countS
* sizeof(struct filedescr
));
110 filetab
[countD
+ countS
].suffix
= NULL
;
112 _PyImport_Filetab
= filetab
;
114 if (Py_OptimizeFlag
) {
115 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
116 for (; filetab
->suffix
!= NULL
; filetab
++) {
117 if (strcmp(filetab
->suffix
, ".pyc") == 0)
118 filetab
->suffix
= ".pyo";
122 if (Py_UnicodeFlag
) {
123 /* Fix the pyc_magic so that byte compiled code created
124 using the all-Unicode method doesn't interfere with
125 code created in normal operation mode. */
126 pyc_magic
= MAGIC
+ 1;
133 Py_XDECREF(extensions
);
135 PyMem_DEL(_PyImport_Filetab
);
136 _PyImport_Filetab
= NULL
;
140 /* Locking primitives to prevent parallel imports of the same module
141 in different threads to return with a partially loaded module.
142 These calls are serialized by the global interpreter lock. */
146 #include "pythread.h"
148 static PyThread_type_lock import_lock
= 0;
149 static long import_lock_thread
= -1;
150 static int import_lock_level
= 0;
155 long me
= PyThread_get_thread_ident();
157 return; /* Too bad */
158 if (import_lock
== NULL
)
159 import_lock
= PyThread_allocate_lock();
160 if (import_lock_thread
== me
) {
164 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0)) {
165 PyThreadState
*tstate
= PyEval_SaveThread();
166 PyThread_acquire_lock(import_lock
, 1);
167 PyEval_RestoreThread(tstate
);
169 import_lock_thread
= me
;
170 import_lock_level
= 1;
176 long me
= PyThread_get_thread_ident();
178 return; /* Too bad */
179 if (import_lock_thread
!= me
)
180 Py_FatalError("unlock_import: not holding the import lock");
182 if (import_lock_level
== 0) {
183 import_lock_thread
= -1;
184 PyThread_release_lock(import_lock
);
190 #define lock_import()
191 #define unlock_import()
198 PyImport_GetModuleDict(void)
200 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
201 if (interp
->modules
== NULL
)
202 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
203 return interp
->modules
;
207 /* List of names to clear in sys */
208 static char* sys_deletes
[] = {
209 "path", "argv", "ps1", "ps2", "exitfunc",
210 "exc_type", "exc_value", "exc_traceback",
211 "last_type", "last_value", "last_traceback",
215 static char* sys_files
[] = {
216 "stdin", "__stdin__",
217 "stdout", "__stdout__",
218 "stderr", "__stderr__",
223 /* Un-initialize things, as good as we can */
226 PyImport_Cleanup(void)
230 PyObject
*key
, *value
, *dict
;
231 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
232 PyObject
*modules
= interp
->modules
;
235 return; /* Already done */
237 /* Delete some special variables first. These are common
238 places where user values hide and people complain when their
239 destructors fail. Since the modules containing them are
240 deleted *last* of all, they would come too late in the normal
241 destruction order. Sigh. */
243 value
= PyDict_GetItemString(modules
, "__builtin__");
244 if (value
!= NULL
&& PyModule_Check(value
)) {
245 dict
= PyModule_GetDict(value
);
247 PySys_WriteStderr("# clear __builtin__._\n");
248 PyDict_SetItemString(dict
, "_", Py_None
);
250 value
= PyDict_GetItemString(modules
, "sys");
251 if (value
!= NULL
&& PyModule_Check(value
)) {
254 dict
= PyModule_GetDict(value
);
255 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
257 PySys_WriteStderr("# clear sys.%s\n", *p
);
258 PyDict_SetItemString(dict
, *p
, Py_None
);
260 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
262 PySys_WriteStderr("# restore sys.%s\n", *p
);
263 v
= PyDict_GetItemString(dict
, *(p
+1));
266 PyDict_SetItemString(dict
, *p
, v
);
270 /* First, delete __main__ */
271 value
= PyDict_GetItemString(modules
, "__main__");
272 if (value
!= NULL
&& PyModule_Check(value
)) {
274 PySys_WriteStderr("# cleanup __main__\n");
275 _PyModule_Clear(value
);
276 PyDict_SetItemString(modules
, "__main__", Py_None
);
279 /* The special treatment of __builtin__ here is because even
280 when it's not referenced as a module, its dictionary is
281 referenced by almost every module's __builtins__. Since
282 deleting a module clears its dictionary (even if there are
283 references left to it), we need to delete the __builtin__
284 module last. Likewise, we don't delete sys until the very
285 end because it is implicitly referenced (e.g. by print).
287 Also note that we 'delete' modules by replacing their entry
288 in the modules dict with None, rather than really deleting
289 them; this avoids a rehash of the modules dictionary and
290 also marks them as "non existent" so they won't be
293 /* Next, repeatedly delete modules with a reference count of
294 one (skipping __builtin__ and sys) and delete them */
298 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
299 if (value
->ob_refcnt
!= 1)
301 if (PyString_Check(key
) && PyModule_Check(value
)) {
302 name
= PyString_AS_STRING(key
);
303 if (strcmp(name
, "__builtin__") == 0)
305 if (strcmp(name
, "sys") == 0)
309 "# cleanup[1] %s\n", name
);
310 _PyModule_Clear(value
);
311 PyDict_SetItem(modules
, key
, Py_None
);
317 /* Next, delete all modules (still skipping __builtin__ and sys) */
319 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
320 if (PyString_Check(key
) && PyModule_Check(value
)) {
321 name
= PyString_AS_STRING(key
);
322 if (strcmp(name
, "__builtin__") == 0)
324 if (strcmp(name
, "sys") == 0)
327 PySys_WriteStderr("# cleanup[2] %s\n", name
);
328 _PyModule_Clear(value
);
329 PyDict_SetItem(modules
, key
, Py_None
);
333 /* Next, delete sys and __builtin__ (in that order) */
334 value
= PyDict_GetItemString(modules
, "sys");
335 if (value
!= NULL
&& PyModule_Check(value
)) {
337 PySys_WriteStderr("# cleanup sys\n");
338 _PyModule_Clear(value
);
339 PyDict_SetItemString(modules
, "sys", Py_None
);
341 value
= PyDict_GetItemString(modules
, "__builtin__");
342 if (value
!= NULL
&& PyModule_Check(value
)) {
344 PySys_WriteStderr("# cleanup __builtin__\n");
345 _PyModule_Clear(value
);
346 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
349 /* Finally, clear and delete the modules directory */
350 PyDict_Clear(modules
);
351 interp
->modules
= NULL
;
356 /* Helper for pythonrun.c -- return magic number */
359 PyImport_GetMagicNumber(void)
365 /* Magic for extension modules (built-in as well as dynamically
366 loaded). To prevent initializing an extension module more than
367 once, we keep a static dictionary 'extensions' keyed by module name
368 (for built-in modules) or by filename (for dynamically loaded
369 modules), containing these modules. A copy od the module's
370 dictionary is stored by calling _PyImport_FixupExtension()
371 immediately after the module initialization function succeeds. A
372 copy can be retrieved from there by calling
373 _PyImport_FindExtension(). */
376 _PyImport_FixupExtension(char *name
, char *filename
)
378 PyObject
*modules
, *mod
, *dict
, *copy
;
379 if (extensions
== NULL
) {
380 extensions
= PyDict_New();
381 if (extensions
== NULL
)
384 modules
= PyImport_GetModuleDict();
385 mod
= PyDict_GetItemString(modules
, name
);
386 if (mod
== NULL
|| !PyModule_Check(mod
)) {
387 PyErr_Format(PyExc_SystemError
,
388 "_PyImport_FixupExtension: module %.200s not loaded", name
);
391 dict
= PyModule_GetDict(mod
);
394 copy
= PyObject_CallMethod(dict
, "copy", "");
397 PyDict_SetItemString(extensions
, filename
, copy
);
403 _PyImport_FindExtension(char *name
, char *filename
)
405 PyObject
*dict
, *mod
, *mdict
, *result
;
406 if (extensions
== NULL
)
408 dict
= PyDict_GetItemString(extensions
, filename
);
411 mod
= PyImport_AddModule(name
);
414 mdict
= PyModule_GetDict(mod
);
417 result
= PyObject_CallMethod(mdict
, "update", "O", dict
);
422 PySys_WriteStderr("import %s # previously loaded (%s)\n",
428 /* Get the module object corresponding to a module name.
429 First check the modules dictionary if there's one there,
430 if not, create a new one and insert in in the modules dictionary.
431 Because the former action is most common, THIS DOES NOT RETURN A
435 PyImport_AddModule(char *name
)
437 PyObject
*modules
= PyImport_GetModuleDict();
440 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
443 m
= PyModule_New(name
);
446 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
450 Py_DECREF(m
); /* Yes, it still exists, in modules! */
456 /* Execute a code object in a module and return the module object
457 WITH INCREMENTED REFERENCE COUNT */
460 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
462 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
466 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
468 PyObject
*modules
= PyImport_GetModuleDict();
471 m
= PyImport_AddModule(name
);
474 d
= PyModule_GetDict(m
);
475 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
476 if (PyDict_SetItemString(d
, "__builtins__",
477 PyEval_GetBuiltins()) != 0)
480 /* Remember the filename as the __file__ attribute */
482 if (pathname
!= NULL
) {
483 v
= PyString_FromString(pathname
);
488 v
= ((PyCodeObject
*)co
)->co_filename
;
491 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
492 PyErr_Clear(); /* Not important enough to report */
495 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
500 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
501 PyErr_Format(PyExc_ImportError
,
502 "Loaded module %.200s not found in sys.modules",
513 /* Given a pathname for a Python source file, fill a buffer with the
514 pathname for the corresponding compiled file. Return the pathname
515 for the compiled file, or NULL if there's no space in the buffer.
516 Doesn't set an exception. */
519 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
523 len
= strlen(pathname
);
526 strcpy(buf
, pathname
);
527 strcpy(buf
+len
, Py_OptimizeFlag
? "o" : "c");
533 /* Given a pathname for a Python source file, its time of last
534 modification, and a pathname for a compiled file, check whether the
535 compiled file represents the same version of the source. If so,
536 return a FILE pointer for the compiled file, positioned just after
537 the header; if not, return NULL.
538 Doesn't set an exception. */
541 check_compiled_module(char *pathname
, long mtime
, char *cpathname
)
547 fp
= fopen(cpathname
, "rb");
550 magic
= PyMarshal_ReadLongFromFile(fp
);
551 if (magic
!= pyc_magic
) {
553 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
557 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
558 if (pyc_mtime
!= mtime
) {
560 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
565 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
570 /* Read a code object from a file and check it for validity */
572 static PyCodeObject
*
573 read_compiled_module(char *cpathname
, FILE *fp
)
577 co
= PyMarshal_ReadObjectFromFile(fp
);
578 /* Ugly: rd_object() may return NULL with or without error */
579 if (co
== NULL
|| !PyCode_Check(co
)) {
580 if (!PyErr_Occurred())
581 PyErr_Format(PyExc_ImportError
,
582 "Non-code object in %.200s", cpathname
);
586 return (PyCodeObject
*)co
;
590 /* Load a module from a compiled file, execute it, and return its
591 module object WITH INCREMENTED REFERENCE COUNT */
594 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
600 magic
= PyMarshal_ReadLongFromFile(fp
);
601 if (magic
!= pyc_magic
) {
602 PyErr_Format(PyExc_ImportError
,
603 "Bad magic number in %.200s", cpathname
);
606 (void) PyMarshal_ReadLongFromFile(fp
);
607 co
= read_compiled_module(cpathname
, fp
);
611 PySys_WriteStderr("import %s # precompiled from %s\n",
613 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
619 /* Parse a source file and return the corresponding code object */
621 static PyCodeObject
*
622 parse_source_module(char *pathname
, FILE *fp
)
627 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
630 co
= PyNode_Compile(n
, pathname
);
637 /* Helper to open a bytecode file for writing in exclusive mode */
640 open_exclusive(char *filename
)
642 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
643 /* Use O_EXCL to avoid a race condition when another process tries to
644 write the same file. When that happens, our open() call fails,
645 which is just fine (since it's only a cache).
646 XXX If the file exists and is writable but the directory is not
647 writable, the file will never be written. Oh well.
650 (void) unlink(filename
);
651 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
653 |O_BINARY
/* necessary for Windows */
659 return fdopen(fd
, "wb");
661 /* Best we can do -- on Windows this can't happen anyway */
662 return fopen(filename
, "wb");
667 /* Write a compiled module to a file, placing the time of last
668 modification of its source into the header.
669 Errors are ignored, if a write error occurs an attempt is made to
673 write_compiled_module(PyCodeObject
*co
, char *cpathname
, long mtime
)
677 fp
= open_exclusive(cpathname
);
681 "# can't create %s\n", cpathname
);
684 PyMarshal_WriteLongToFile(pyc_magic
, fp
);
685 /* First write a 0 for mtime */
686 PyMarshal_WriteLongToFile(0L, fp
);
687 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
690 PySys_WriteStderr("# can't write %s\n", cpathname
);
691 /* Don't keep partial file */
693 (void) unlink(cpathname
);
696 /* Now write the true mtime */
698 PyMarshal_WriteLongToFile(mtime
, fp
);
702 PySys_WriteStderr("# wrote %s\n", cpathname
);
704 PyMac_setfiletype(cpathname
, 'Pyth', 'PYC ');
709 /* Load a source module from a given file and return its module
710 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
711 byte-compiled file, use that instead. */
714 load_source_module(char *name
, char *pathname
, FILE *fp
)
718 char buf
[MAXPATHLEN
+1];
723 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
726 #if SIZEOF_TIME_T > 4
727 /* Python's .pyc timestamp handling presumes that the timestamp fits
728 in 4 bytes. This will be fine until sometime in the year 2038,
729 when a 4-byte signed time_t will overflow.
732 PyErr_SetString(PyExc_OverflowError
,
733 "modification time overflows a 4 bytes");
737 cpathname
= make_compiled_pathname(pathname
, buf
, (size_t)MAXPATHLEN
+1);
738 if (cpathname
!= NULL
&&
739 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
740 co
= read_compiled_module(cpathname
, fpc
);
745 PySys_WriteStderr("import %s # precompiled from %s\n",
747 pathname
= cpathname
;
750 co
= parse_source_module(pathname
, fp
);
754 PySys_WriteStderr("import %s # from %s\n",
756 write_compiled_module(co
, cpathname
, mtime
);
758 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
766 static PyObject
*load_module(char *, FILE *, char *, int);
767 static struct filedescr
*find_module(char *, PyObject
*,
768 char *, size_t, FILE **);
769 static struct _frozen
*find_frozen(char *name
);
771 /* Load a package and return its module object WITH INCREMENTED
775 load_package(char *name
, char *pathname
)
777 PyObject
*m
, *d
, *file
, *path
;
779 char buf
[MAXPATHLEN
+1];
781 struct filedescr
*fdp
;
783 m
= PyImport_AddModule(name
);
787 PySys_WriteStderr("import %s # directory %s\n",
789 d
= PyModule_GetDict(m
);
790 file
= PyString_FromString(pathname
);
793 path
= Py_BuildValue("[O]", file
);
798 err
= PyDict_SetItemString(d
, "__file__", file
);
800 err
= PyDict_SetItemString(d
, "__path__", path
);
806 fdp
= find_module("__init__", path
, buf
, sizeof(buf
), &fp
);
808 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
815 m
= load_module(name
, fp
, buf
, fdp
->type
);
825 /* Helper to test for built-in module */
828 is_builtin(char *name
)
831 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
832 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
833 if (PyImport_Inittab
[i
].initfunc
== NULL
)
843 /* Search the path (default sys.path) for a module. Return the
844 corresponding filedescr struct, and (via return arguments) the
845 pathname and an open file. Return NULL if the module is not found. */
848 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
852 #ifdef CHECK_IMPORT_CASE
853 static int check_case(char *, int, int, char *);
856 static int find_init_module(char *); /* Forward */
858 static struct filedescr
*
859 find_module(char *realname
, PyObject
*path
, char *buf
, size_t buflen
,
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 if (strlen(realname
) > MAXPATHLEN
) {
874 PyErr_SetString(PyExc_OverflowError
, "module name is too long");
877 strcpy(name
, realname
);
879 if (path
!= NULL
&& PyString_Check(path
)) {
880 /* Submodule of "frozen" package:
881 Set name to the fullname, path to NULL
882 and continue as "usual" */
883 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
884 PyErr_SetString(PyExc_ImportError
,
885 "full frozen module name too long");
888 strcpy(buf
, PyString_AsString(path
));
895 if (is_builtin(name
)) {
899 if ((f
= find_frozen(name
)) != NULL
) {
905 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
911 path
= PySys_GetObject("path");
913 if (path
== NULL
|| !PyList_Check(path
)) {
914 PyErr_SetString(PyExc_ImportError
,
915 "sys.path must be a list of directory names");
918 npath
= PyList_Size(path
);
919 namelen
= strlen(name
);
920 for (i
= 0; i
< npath
; i
++) {
921 PyObject
*v
= PyList_GetItem(path
, i
);
922 if (!PyString_Check(v
))
924 len
= PyString_Size(v
);
925 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
)
926 continue; /* Too long */
927 strcpy(buf
, PyString_AsString(v
));
928 if (strlen(buf
) != len
)
929 continue; /* v contains '\0' */
931 #ifdef INTERN_STRINGS
933 ** Speedup: each sys.path item is interned, and
934 ** FindResourceModule remembers which items refer to
935 ** folders (so we don't have to bother trying to look
936 ** into them for resources).
938 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
939 v
= PyList_GET_ITEM(path
, i
);
941 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
942 static struct filedescr resfiledescr
=
943 {"", "", PY_RESOURCE
};
945 return &resfiledescr
;
947 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
948 static struct filedescr resfiledescr
=
949 {"", "", PY_CODERESOURCE
};
951 return &resfiledescr
;
954 if (len
> 0 && buf
[len
-1] != SEP
956 && buf
[len
-1] != ALTSEP
960 #ifdef IMPORT_8x3_NAMES
961 /* see if we are searching in directory dos-8x3 */
962 if (len
> 7 && !strncmp(buf
+ len
- 8, "dos-8x3", 7)){
964 char ch
; /* limit name to 8 lower-case characters */
965 for (j
= 0; (ch
= name
[j
]) && j
< 8; j
++)
967 buf
[len
++] = tolower(ch
);
971 else /* Not in dos-8x3, use the full name */
974 strcpy(buf
+len
, name
);
978 if (stat(buf
, &statbuf
) == 0) {
979 if (S_ISDIR(statbuf
.st_mode
)) {
980 if (find_init_module(buf
)) {
981 #ifdef CHECK_IMPORT_CASE
982 if (!check_case(buf
, len
, namelen
,
991 /* XXX How are you going to test for directories? */
994 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
996 fp
= fopen(buf
, fdp
->mode
);
998 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
999 strcpy(buf
+len
, fdp
->suffix
);
1000 if (Py_VerboseFlag
> 1)
1001 PySys_WriteStderr("# trying %s\n", buf
);
1002 fp
= fopen(buf
, fdp
->mode
);
1006 #endif /* !macintosh */
1011 PyErr_Format(PyExc_ImportError
,
1012 "No module named %.200s", name
);
1015 #ifdef CHECK_IMPORT_CASE
1016 if (!check_case(buf
, len
, namelen
, name
)) {
1026 #ifdef CHECK_IMPORT_CASE
1029 #include <windows.h>
1035 /* Return 1 if s is an 8.3 filename in ALLCAPS */
1037 char *dot
= strchr(s
, '.');
1038 char *end
= strchr(s
, '\0');
1041 return 0; /* More than 8 before '.' */
1043 return 0; /* More than 3 after '.' */
1044 end
= strchr(dot
+1, '.');
1046 return 0; /* More than one dot */
1049 return 0; /* More than 8 and no dot */
1050 while ((c
= *s
++)) {
1058 check_case(char *buf
, int len
, int namelen
, char *name
)
1060 WIN32_FIND_DATA data
;
1062 if (getenv("PYTHONCASEOK") != NULL
)
1064 h
= FindFirstFile(buf
, &data
);
1065 if (h
== INVALID_HANDLE_VALUE
) {
1066 PyErr_Format(PyExc_NameError
,
1067 "Can't find file for module %.100s\n(filename %.300s)",
1072 if (allcaps8x3(data
.cFileName
)) {
1073 /* Skip the test if the filename is ALL.CAPS. This can
1074 happen in certain circumstances beyond our control,
1075 e.g. when software is installed under NT on a FAT
1076 filesystem and then the same FAT filesystem is used
1077 under Windows 95. */
1080 if (strncmp(data
.cFileName
, name
, namelen
) != 0) {
1081 strcpy(buf
+len
-namelen
, data
.cFileName
);
1082 PyErr_Format(PyExc_NameError
,
1083 "Case mismatch for module name %.100s\n(filename %.300s)",
1089 #endif /* MS_WIN32 */
1092 #include <TextUtils.h>
1094 #include "TFileSpec.h" /* for Path2FSSpec() */
1097 check_case(char *buf
, int len
, int namelen
, char *name
)
1102 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1104 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1105 the way, which is fine for all directories, but here we need
1106 the original name of the alias file (say, Dlg.ppc.slb, not
1107 toolboxmodules.ppc.slb). */
1109 err
= Path2FSSpec(buf
, &fss
);
1111 colon
= strrchr(buf
, ':'); /* find filename */
1113 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1114 Pstring(colon
+1), &fss
);
1116 err
= FSMakeFSSpec(fss
.vRefNum
, fss
.parID
,
1121 PyErr_Format(PyExc_NameError
,
1122 "Can't find file for module %.100s\n(filename %.300s)",
1126 if ( namelen
> fss
.name
[0] || strncmp(name
, (char *)fss
.name
+1, namelen
) != 0 ) {
1127 PyErr_Format(PyExc_NameError
,
1128 "Case mismatch for module name %.100s\n(filename %.300s)",
1134 #endif /* macintosh */
1140 check_case(char *buf
, int len
, int namelen
, char *name
)
1145 if (getenv("PYTHONCASEOK") != NULL
)
1147 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1149 PyErr_Format(PyExc_NameError
,
1150 "Can't find file for module %.100s\n(filename %.300s)",
1155 if (strncmp(ffblk
.ff_name
, name
, namelen
) != 0) {
1156 strcpy(buf
+len
-namelen
, ffblk
.ff_name
);
1157 PyErr_Format(PyExc_NameError
,
1158 "Case mismatch for module name %.100s\n(filename %.300s)",
1166 #endif /* CHECK_IMPORT_CASE */
1169 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1171 find_init_module(char *buf
)
1173 size_t save_len
= strlen(buf
);
1174 size_t i
= save_len
;
1175 struct stat statbuf
;
1177 if (save_len
+ 13 >= MAXPATHLEN
)
1180 strcpy(buf
+i
, "__init__.py");
1181 if (stat(buf
, &statbuf
) == 0) {
1182 buf
[save_len
] = '\0';
1186 if (Py_OptimizeFlag
)
1190 if (stat(buf
, &statbuf
) == 0) {
1191 buf
[save_len
] = '\0';
1194 buf
[save_len
] = '\0';
1197 #endif /* HAVE_STAT */
1200 static int init_builtin(char *); /* Forward */
1202 /* Load an external module using the default search path and return
1203 its module object WITH INCREMENTED REFERENCE COUNT */
1206 load_module(char *name
, FILE *fp
, char *buf
, int type
)
1212 /* First check that there's an open file (if we need one) */
1217 PyErr_Format(PyExc_ValueError
,
1218 "file object required for import (type code %d)",
1227 m
= load_source_module(name
, buf
, fp
);
1231 m
= load_compiled_module(name
, buf
, fp
);
1234 #ifdef HAVE_DYNAMIC_LOADING
1236 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1242 m
= PyMac_LoadResourceModule(name
, buf
);
1244 case PY_CODERESOURCE
:
1245 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1250 m
= load_package(name
, buf
);
1255 if (buf
!= NULL
&& buf
[0] != '\0')
1257 if (type
== C_BUILTIN
)
1258 err
= init_builtin(name
);
1260 err
= PyImport_ImportFrozenModule(name
);
1264 PyErr_Format(PyExc_ImportError
,
1265 "Purported %s module %.200s not found",
1267 "builtin" : "frozen",
1271 modules
= PyImport_GetModuleDict();
1272 m
= PyDict_GetItemString(modules
, name
);
1276 "%s module %.200s not properly initialized",
1278 "builtin" : "frozen",
1286 PyErr_Format(PyExc_ImportError
,
1287 "Don't know how to import %.200s (type code %d)",
1297 /* Initialize a built-in module.
1298 Return 1 for succes, 0 if the module is not found, and -1 with
1299 an exception set if the initialization failed. */
1302 init_builtin(char *name
)
1307 if ((mod
= _PyImport_FindExtension(name
, name
)) != NULL
)
1310 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1311 if (strcmp(name
, p
->name
) == 0) {
1312 if (p
->initfunc
== NULL
) {
1313 PyErr_Format(PyExc_ImportError
,
1314 "Cannot re-init internal module %.200s",
1319 PySys_WriteStderr("import %s # builtin\n", name
);
1321 if (PyErr_Occurred())
1323 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1332 /* Frozen modules */
1334 static struct _frozen
*
1335 find_frozen(char *name
)
1339 for (p
= PyImport_FrozenModules
; ; p
++) {
1340 if (p
->name
== NULL
)
1342 if (strcmp(p
->name
, name
) == 0)
1349 get_frozen_object(char *name
)
1351 struct _frozen
*p
= find_frozen(name
);
1355 PyErr_Format(PyExc_ImportError
,
1356 "No such frozen object named %.200s",
1363 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1366 /* Initialize a frozen module.
1367 Return 1 for succes, 0 if the module is not found, and -1 with
1368 an exception set if the initialization failed.
1369 This function is also used from frozenmain.c */
1372 PyImport_ImportFrozenModule(char *name
)
1374 struct _frozen
*p
= find_frozen(name
);
1383 ispackage
= (size
< 0);
1387 PySys_WriteStderr("import %s # frozen%s\n",
1388 name
, ispackage
? " package" : "");
1389 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1392 if (!PyCode_Check(co
)) {
1394 PyErr_Format(PyExc_TypeError
,
1395 "frozen object %.200s is not a code object",
1400 /* Set __path__ to the package name */
1403 m
= PyImport_AddModule(name
);
1406 d
= PyModule_GetDict(m
);
1407 s
= PyString_InternFromString(name
);
1410 err
= PyDict_SetItemString(d
, "__path__", s
);
1415 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1424 /* Import a module, either built-in, frozen, or external, and return
1425 its module object WITH INCREMENTED REFERENCE COUNT */
1428 PyImport_ImportModule(char *name
)
1430 static PyObject
*fromlist
= NULL
;
1431 if (fromlist
== NULL
&& strchr(name
, '.') != NULL
) {
1432 fromlist
= Py_BuildValue("(s)", "*");
1433 if (fromlist
== NULL
)
1436 return PyImport_ImportModuleEx(name
, NULL
, NULL
, fromlist
);
1439 /* Forward declarations for helper routines */
1440 static PyObject
*get_parent(PyObject
*globals
, char *buf
, int *p_buflen
);
1441 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1442 char **p_name
, char *buf
, int *p_buflen
);
1443 static int mark_miss(char *name
);
1444 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1445 char *buf
, int buflen
, int recursive
);
1446 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1448 /* The Magnum Opus of dotted-name import :-) */
1451 import_module_ex(char *name
, PyObject
*globals
, PyObject
*locals
,
1454 char buf
[MAXPATHLEN
+1];
1456 PyObject
*parent
, *head
, *next
, *tail
;
1458 parent
= get_parent(globals
, buf
, &buflen
);
1462 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1469 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1478 if (fromlist
!= NULL
) {
1479 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1483 if (fromlist
== NULL
) {
1489 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1498 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
1503 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1509 get_parent(PyObject
*globals
, char *buf
, int *p_buflen
)
1511 static PyObject
*namestr
= NULL
;
1512 static PyObject
*pathstr
= NULL
;
1513 PyObject
*modname
, *modpath
, *modules
, *parent
;
1515 if (globals
== NULL
|| !PyDict_Check(globals
))
1518 if (namestr
== NULL
) {
1519 namestr
= PyString_InternFromString("__name__");
1520 if (namestr
== NULL
)
1523 if (pathstr
== NULL
) {
1524 pathstr
= PyString_InternFromString("__path__");
1525 if (pathstr
== NULL
)
1531 modname
= PyDict_GetItem(globals
, namestr
);
1532 if (modname
== NULL
|| !PyString_Check(modname
))
1535 modpath
= PyDict_GetItem(globals
, pathstr
);
1536 if (modpath
!= NULL
) {
1537 int len
= PyString_GET_SIZE(modname
);
1538 if (len
> MAXPATHLEN
) {
1539 PyErr_SetString(PyExc_ValueError
,
1540 "Module name too long");
1543 strcpy(buf
, PyString_AS_STRING(modname
));
1547 char *start
= PyString_AS_STRING(modname
);
1548 char *lastdot
= strrchr(start
, '.');
1550 if (lastdot
== NULL
)
1552 len
= lastdot
- start
;
1553 if (len
>= MAXPATHLEN
) {
1554 PyErr_SetString(PyExc_ValueError
,
1555 "Module name too long");
1558 strncpy(buf
, start
, len
);
1563 modules
= PyImport_GetModuleDict();
1564 parent
= PyDict_GetItemString(modules
, buf
);
1568 /* We expect, but can't guarantee, if parent != None, that:
1569 - parent.__name__ == buf
1570 - parent.__dict__ is globals
1571 If this is violated... Who cares? */
1574 /* altmod is either None or same as mod */
1576 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
1579 char *name
= *p_name
;
1580 char *dot
= strchr(name
, '.');
1594 PyErr_SetString(PyExc_ValueError
,
1595 "Empty module name");
1599 p
= buf
+ *p_buflen
;
1602 if (p
+len
-buf
>= MAXPATHLEN
) {
1603 PyErr_SetString(PyExc_ValueError
,
1604 "Module name too long");
1607 strncpy(p
, name
, len
);
1609 *p_buflen
= p
+len
-buf
;
1611 result
= import_submodule(mod
, p
, buf
);
1612 if (result
== Py_None
&& altmod
!= mod
) {
1614 /* Here, altmod must be None and mod must not be None */
1615 result
= import_submodule(altmod
, p
, p
);
1616 if (result
!= NULL
&& result
!= Py_None
) {
1617 if (mark_miss(buf
) != 0) {
1621 strncpy(buf
, name
, len
);
1629 if (result
== Py_None
) {
1631 PyErr_Format(PyExc_ImportError
,
1632 "No module named %.200s", name
);
1640 mark_miss(char *name
)
1642 PyObject
*modules
= PyImport_GetModuleDict();
1643 return PyDict_SetItemString(modules
, name
, Py_None
);
1647 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, int buflen
,
1652 if (!PyObject_HasAttrString(mod
, "__path__"))
1655 for (i
= 0; ; i
++) {
1656 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
1659 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1665 if (!PyString_Check(item
)) {
1666 PyErr_SetString(PyExc_TypeError
,
1667 "Item in ``from list'' not a string");
1671 if (PyString_AS_STRING(item
)[0] == '*') {
1674 /* See if the package defines __all__ */
1676 continue; /* Avoid endless recursion */
1677 all
= PyObject_GetAttrString(mod
, "__all__");
1681 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
1687 hasit
= PyObject_HasAttr(mod
, item
);
1689 char *subname
= PyString_AS_STRING(item
);
1692 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
1693 PyErr_SetString(PyExc_ValueError
,
1694 "Module name too long");
1701 submod
= import_submodule(mod
, subname
, buf
);
1703 if (submod
== NULL
) {
1715 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
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(PyObject
*m
)
1776 PyObject
*modules
= PyImport_GetModuleDict();
1777 PyObject
*path
= NULL
;
1778 char *name
, *subname
;
1779 char buf
[MAXPATHLEN
+1];
1780 struct filedescr
*fdp
;
1783 if (m
== NULL
|| !PyModule_Check(m
)) {
1784 PyErr_SetString(PyExc_TypeError
,
1785 "reload() argument must be module");
1788 name
= PyModule_GetName(m
);
1791 if (m
!= PyDict_GetItemString(modules
, name
)) {
1792 PyErr_Format(PyExc_ImportError
,
1793 "reload(): module %.200s not in sys.modules",
1797 subname
= strrchr(name
, '.');
1798 if (subname
== NULL
)
1801 PyObject
*parentname
, *parent
;
1802 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
1803 if (parentname
== NULL
)
1805 parent
= PyDict_GetItem(modules
, parentname
);
1806 Py_DECREF(parentname
);
1807 if (parent
== NULL
) {
1808 PyErr_Format(PyExc_ImportError
,
1809 "reload(): parent %.200s not in sys.modules",
1814 path
= PyObject_GetAttrString(parent
, "__path__");
1819 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1823 m
= load_module(name
, fp
, buf
, fdp
->type
);
1830 /* Higher-level import emulator which emulates the "import" statement
1831 more accurately -- it invokes the __import__() function from the
1832 builtins of the current globals. This means that the import is
1833 done using whatever import hooks are installed in the current
1834 environment, e.g. by "rexec".
1835 A dummy list ["__doc__"] is passed as the 4th argument so that
1836 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1837 will return <module "gencache"> instead of <module "win32com">. */
1840 PyImport_Import(PyObject
*module_name
)
1842 static PyObject
*silly_list
= NULL
;
1843 static PyObject
*builtins_str
= NULL
;
1844 static PyObject
*import_str
= NULL
;
1845 PyObject
*globals
= NULL
;
1846 PyObject
*import
= NULL
;
1847 PyObject
*builtins
= NULL
;
1850 /* Initialize constant string objects */
1851 if (silly_list
== NULL
) {
1852 import_str
= PyString_InternFromString("__import__");
1853 if (import_str
== NULL
)
1855 builtins_str
= PyString_InternFromString("__builtins__");
1856 if (builtins_str
== NULL
)
1858 silly_list
= Py_BuildValue("[s]", "__doc__");
1859 if (silly_list
== NULL
)
1863 /* Get the builtins from current globals */
1864 globals
= PyEval_GetGlobals();
1865 if(globals
!= NULL
) {
1867 builtins
= PyObject_GetItem(globals
, builtins_str
);
1868 if (builtins
== NULL
)
1872 /* No globals -- use standard builtins, and fake globals */
1875 builtins
= PyImport_ImportModuleEx("__builtin__",
1877 if (builtins
== NULL
)
1879 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
1880 if (globals
== NULL
)
1884 /* Get the __import__ function from the builtins */
1885 if (PyDict_Check(builtins
))
1886 import
=PyObject_GetItem(builtins
, import_str
);
1888 import
=PyObject_GetAttr(builtins
, import_str
);
1892 /* Call the _import__ function with the proper argument list */
1893 r
= PyObject_CallFunction(import
, "OOOO",
1894 module_name
, globals
, globals
, silly_list
);
1897 Py_XDECREF(globals
);
1898 Py_XDECREF(builtins
);
1905 /* Module 'imp' provides Python access to the primitives used for
1910 imp_get_magic(PyObject
*self
, PyObject
*args
)
1914 if (!PyArg_ParseTuple(args
, ":get_magic"))
1916 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
1917 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
1918 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
1919 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
1921 return PyString_FromStringAndSize(buf
, 4);
1925 imp_get_suffixes(PyObject
*self
, PyObject
*args
)
1928 struct filedescr
*fdp
;
1930 if (!PyArg_ParseTuple(args
, ":get_suffixes"))
1932 list
= PyList_New(0);
1935 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1936 PyObject
*item
= Py_BuildValue("ssi",
1937 fdp
->suffix
, fdp
->mode
, fdp
->type
);
1942 if (PyList_Append(list
, item
) < 0) {
1953 call_find_module(char *name
, PyObject
*path
)
1955 extern int fclose(FILE *);
1956 PyObject
*fob
, *ret
;
1957 struct filedescr
*fdp
;
1958 char pathname
[MAXPATHLEN
+1];
1962 if (path
== Py_None
)
1964 fdp
= find_module(name
, path
, pathname
, MAXPATHLEN
+1, &fp
);
1968 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
1978 ret
= Py_BuildValue("Os(ssi)",
1979 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
1985 imp_find_module(PyObject
*self
, PyObject
*args
)
1988 PyObject
*path
= NULL
;
1989 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
1991 return call_find_module(name
, path
);
1995 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2000 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2002 ret
= init_builtin(name
);
2009 m
= PyImport_AddModule(name
);
2015 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2020 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2022 ret
= PyImport_ImportFrozenModule(name
);
2029 m
= PyImport_AddModule(name
);
2035 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2039 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2041 return get_frozen_object(name
);
2045 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2048 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2050 return PyInt_FromLong(is_builtin(name
));
2054 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2058 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2060 p
= find_frozen(name
);
2061 return PyInt_FromLong((long) (p
== NULL
? 0 : p
->size
));
2065 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2069 fp
= fopen(pathname
, mode
);
2071 PyErr_SetFromErrno(PyExc_IOError
);
2074 fp
= PyFile_AsFile(fob
);
2076 PyErr_SetString(PyExc_ValueError
,
2077 "bad/closed file object");
2083 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2087 PyObject
*fob
= NULL
;
2090 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2091 &PyFile_Type
, &fob
))
2093 fp
= get_file(pathname
, fob
, "rb");
2096 m
= load_compiled_module(name
, pathname
, fp
);
2102 #ifdef HAVE_DYNAMIC_LOADING
2105 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2109 PyObject
*fob
= NULL
;
2112 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2113 &PyFile_Type
, &fob
))
2116 fp
= get_file(pathname
, fob
, "r");
2120 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2124 #endif /* HAVE_DYNAMIC_LOADING */
2127 imp_load_source(PyObject
*self
, PyObject
*args
)
2131 PyObject
*fob
= NULL
;
2134 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2135 &PyFile_Type
, &fob
))
2137 fp
= get_file(pathname
, fob
, "r");
2140 m
= load_source_module(name
, pathname
, fp
);
2148 imp_load_resource(PyObject
*self
, PyObject
*args
)
2154 if (!PyArg_ParseTuple(args
, "ss:load_resource", &name
, &pathname
))
2156 m
= PyMac_LoadResourceModule(name
, pathname
);
2159 #endif /* macintosh */
2162 imp_load_module(PyObject
*self
, PyObject
*args
)
2167 char *suffix
; /* Unused */
2172 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2173 &name
, &fob
, &pathname
,
2174 &suffix
, &mode
, &type
))
2176 if (*mode
&& (*mode
!= 'r' || strchr(mode
, '+') != NULL
)) {
2177 PyErr_Format(PyExc_ValueError
,
2178 "invalid file open mode %.200s", mode
);
2184 if (!PyFile_Check(fob
)) {
2185 PyErr_SetString(PyExc_ValueError
,
2186 "load_module arg#2 should be a file or None");
2189 fp
= get_file(pathname
, fob
, mode
);
2193 return load_module(name
, fp
, pathname
, type
);
2197 imp_load_package(PyObject
*self
, PyObject
*args
)
2201 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2203 return load_package(name
, pathname
);
2207 imp_new_module(PyObject
*self
, PyObject
*args
)
2210 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2212 return PyModule_New(name
);
2217 static char doc_imp
[] = "\
2218 This module provides the components needed to build your own\n\
2219 __import__ function. Undocumented functions are obsolete.\n\
2222 static char doc_find_module
[] = "\
2223 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2224 Search for a module. If path is omitted or None, search for a\n\
2225 built-in, frozen or special module and continue search in sys.path.\n\
2226 The module name cannot contain '.'; to search for a submodule of a\n\
2227 package, pass the submodule name and the package's __path__.\
2230 static char doc_load_module
[] = "\
2231 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2232 Load a module, given information returned by find_module().\n\
2233 The module name must include the full package name, if any.\
2236 static char doc_get_magic
[] = "\
2237 get_magic() -> string\n\
2238 Return the magic number for .pyc or .pyo files.\
2241 static char doc_get_suffixes
[] = "\
2242 get_suffixes() -> [(suffix, mode, type), ...]\n\
2243 Return a list of (suffix, mode, type) tuples describing the files\n\
2244 that find_module() looks for.\
2247 static char doc_new_module
[] = "\
2248 new_module(name) -> module\n\
2249 Create a new module. Do not enter it in sys.modules.\n\
2250 The module name must include the full package name, if any.\
2253 static PyMethodDef imp_methods
[] = {
2254 {"find_module", imp_find_module
, 1, doc_find_module
},
2255 {"get_magic", imp_get_magic
, 1, doc_get_magic
},
2256 {"get_suffixes", imp_get_suffixes
, 1, doc_get_suffixes
},
2257 {"load_module", imp_load_module
, 1, doc_load_module
},
2258 {"new_module", imp_new_module
, 1, doc_new_module
},
2259 /* The rest are obsolete */
2260 {"get_frozen_object", imp_get_frozen_object
, 1},
2261 {"init_builtin", imp_init_builtin
, 1},
2262 {"init_frozen", imp_init_frozen
, 1},
2263 {"is_builtin", imp_is_builtin
, 1},
2264 {"is_frozen", imp_is_frozen
, 1},
2265 {"load_compiled", imp_load_compiled
, 1},
2266 #ifdef HAVE_DYNAMIC_LOADING
2267 {"load_dynamic", imp_load_dynamic
, 1},
2269 {"load_package", imp_load_package
, 1},
2271 {"load_resource", imp_load_resource
, 1},
2273 {"load_source", imp_load_source
, 1},
2274 {NULL
, NULL
} /* sentinel */
2278 setint(PyObject
*d
, char *name
, int value
)
2283 v
= PyInt_FromLong((long)value
);
2284 err
= PyDict_SetItemString(d
, name
, v
);
2294 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2295 NULL
, PYTHON_API_VERSION
);
2296 d
= PyModule_GetDict(m
);
2298 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2299 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2300 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2301 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2302 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2303 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2304 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2305 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2306 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2313 /* API for embedding applications that want to add their own entries
2314 to the table of built-in modules. This should normally be called
2315 *before* Py_Initialize(). When the table resize fails, -1 is
2316 returned and the existing table is unchanged.
2318 After a similar function by Just van Rossum. */
2321 PyImport_ExtendInittab(struct _inittab
*newtab
)
2323 static struct _inittab
*our_copy
= NULL
;
2327 /* Count the number of entries in both tables */
2328 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2331 return 0; /* Nothing to do */
2332 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2335 /* Allocate new memory for the combined table */
2337 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
2341 /* Copy the tables into the new memory */
2342 if (our_copy
!= PyImport_Inittab
)
2343 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2344 PyImport_Inittab
= our_copy
= p
;
2345 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2350 /* Shorthand to add a single entry given a name and a function */
2353 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
2355 struct _inittab newtab
[2];
2357 memset(newtab
, '\0', sizeof newtab
);
2359 newtab
[0].name
= name
;
2360 newtab
[0].initfunc
= initfunc
;
2362 return PyImport_ExtendInittab(newtab
);