2 /* Module definition and import implementation */
22 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
25 /* Magic word to reject .pyc files generated by other Python versions */
26 /* Change for each incompatible change */
27 /* The value of CR and LF is incorporated so if you ever read or write
28 a .pyc file in text mode the magic number will be wrong; also, the
29 Apple MPW compiler swaps their values, botching string constants.
30 XXX That probably isn't important anymore.
32 /* XXX Perhaps the magic number should be frozen and a version field
33 added to the .pyc file header? */
34 /* New way to come up with the low 16 bits of the magic number:
35 (YEAR-1995) * 10000 + MONTH * 100 + DAY
36 where MONTH and DAY are 1-based.
37 XXX Whatever the "old way" may have been isn't documented.
38 XXX This scheme breaks in 2002, as (2002-1995)*10000 = 70000 doesn't
40 XXX Later, sometimes 1 gets added to MAGIC in order to record that
41 the Unicode -U option is in use. IMO (Tim's), that's a Bad Idea
42 (quite apart from that the -U option doesn't work so isn't used
45 XXX MAL, 2002-02-07: I had to modify the MAGIC due to a fix of the
46 UTF-8 encoder (it previously produced invalid UTF-8 for unpaired
47 high surrogates), so I simply bumped the month value to 20 (invalid
48 month) and set the day to 1. This should be recognizable by any
49 algorithm relying on the above scheme. Perhaps we should simply
50 start counting in increments of 10 from now on ?!
52 MWH, 2002-08-03: Removed SET_LINENO. Couldn't be bothered figuring
53 out the MAGIC schemes, so just incremented it by 10.
55 GvR, 2002-08-31: Because MWH changed the bytecode again, moved the
56 magic number *back* to 62011. This should get the snake-farm to
57 throw away its old .pyc files, amongst others.
71 Python 2.3a0: 62011 (!)
73 #define MAGIC (62011 | ((long)'\r'<<16) | ((long)'\n'<<24))
75 /* Magic word as global; note that _PyImport_Init() can change the
76 value of this global to accommodate for alterations of how the
77 compiler works which are enabled by command line switches. */
78 static long pyc_magic
= MAGIC
;
80 /* See _PyImport_FixupExtension() below */
81 static PyObject
*extensions
= NULL
;
83 /* This table is defined in config.c: */
84 extern struct _inittab _PyImport_Inittab
[];
86 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
88 /* these tables define the module suffixes that Python recognizes */
89 struct filedescr
* _PyImport_Filetab
= NULL
;
92 static const struct filedescr _PyImport_StandardFiletab
[] = {
93 {"/py", "U", PY_SOURCE
},
94 {"/pyc", "rb", PY_COMPILED
},
98 static const struct filedescr _PyImport_StandardFiletab
[] = {
99 {".py", "U", PY_SOURCE
},
101 {".pyw", "U", PY_SOURCE
},
103 {".pyc", "rb", PY_COMPILED
},
108 /* Initialize things */
113 const struct filedescr
*scan
;
114 struct filedescr
*filetab
;
118 /* prepare _PyImport_Filetab: copy entries from
119 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
121 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
123 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
125 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
126 memcpy(filetab
, _PyImport_DynLoadFiletab
,
127 countD
* sizeof(struct filedescr
));
128 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
129 countS
* sizeof(struct filedescr
));
130 filetab
[countD
+ countS
].suffix
= NULL
;
132 _PyImport_Filetab
= filetab
;
134 if (Py_OptimizeFlag
) {
135 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
136 for (; filetab
->suffix
!= NULL
; filetab
++) {
138 if (strcmp(filetab
->suffix
, ".pyc") == 0)
139 filetab
->suffix
= ".pyo";
141 if (strcmp(filetab
->suffix
, "/pyc") == 0)
142 filetab
->suffix
= "/pyo";
147 if (Py_UnicodeFlag
) {
148 /* Fix the pyc_magic so that byte compiled code created
149 using the all-Unicode method doesn't interfere with
150 code created in normal operation mode. */
151 pyc_magic
= MAGIC
+ 1;
158 Py_XDECREF(extensions
);
160 PyMem_DEL(_PyImport_Filetab
);
161 _PyImport_Filetab
= NULL
;
165 /* Locking primitives to prevent parallel imports of the same module
166 in different threads to return with a partially loaded module.
167 These calls are serialized by the global interpreter lock. */
171 #include "pythread.h"
173 static PyThread_type_lock import_lock
= 0;
174 static long import_lock_thread
= -1;
175 static int import_lock_level
= 0;
180 long me
= PyThread_get_thread_ident();
182 return; /* Too bad */
183 if (import_lock
== NULL
)
184 import_lock
= PyThread_allocate_lock();
185 if (import_lock_thread
== me
) {
189 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0)) {
190 PyThreadState
*tstate
= PyEval_SaveThread();
191 PyThread_acquire_lock(import_lock
, 1);
192 PyEval_RestoreThread(tstate
);
194 import_lock_thread
= me
;
195 import_lock_level
= 1;
201 long me
= PyThread_get_thread_ident();
203 return; /* Too bad */
204 if (import_lock_thread
!= me
)
205 Py_FatalError("unlock_import: not holding the import lock");
207 if (import_lock_level
== 0) {
208 import_lock_thread
= -1;
209 PyThread_release_lock(import_lock
);
215 #define lock_import()
216 #define unlock_import()
221 imp_lock_held(PyObject
*self
, PyObject
*args
)
223 if (!PyArg_ParseTuple(args
, ":lock_held"))
226 return PyBool_FromLong(import_lock_thread
!= -1);
228 return PyBool_FromLong(0);
235 PyImport_GetModuleDict(void)
237 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
238 if (interp
->modules
== NULL
)
239 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
240 return interp
->modules
;
244 /* List of names to clear in sys */
245 static char* sys_deletes
[] = {
246 "path", "argv", "ps1", "ps2", "exitfunc",
247 "exc_type", "exc_value", "exc_traceback",
248 "last_type", "last_value", "last_traceback",
252 static char* sys_files
[] = {
253 "stdin", "__stdin__",
254 "stdout", "__stdout__",
255 "stderr", "__stderr__",
260 /* Un-initialize things, as good as we can */
263 PyImport_Cleanup(void)
267 PyObject
*key
, *value
, *dict
;
268 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
269 PyObject
*modules
= interp
->modules
;
272 return; /* Already done */
274 /* Delete some special variables first. These are common
275 places where user values hide and people complain when their
276 destructors fail. Since the modules containing them are
277 deleted *last* of all, they would come too late in the normal
278 destruction order. Sigh. */
280 value
= PyDict_GetItemString(modules
, "__builtin__");
281 if (value
!= NULL
&& PyModule_Check(value
)) {
282 dict
= PyModule_GetDict(value
);
284 PySys_WriteStderr("# clear __builtin__._\n");
285 PyDict_SetItemString(dict
, "_", Py_None
);
287 value
= PyDict_GetItemString(modules
, "sys");
288 if (value
!= NULL
&& PyModule_Check(value
)) {
291 dict
= PyModule_GetDict(value
);
292 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
294 PySys_WriteStderr("# clear sys.%s\n", *p
);
295 PyDict_SetItemString(dict
, *p
, Py_None
);
297 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
299 PySys_WriteStderr("# restore sys.%s\n", *p
);
300 v
= PyDict_GetItemString(dict
, *(p
+1));
303 PyDict_SetItemString(dict
, *p
, v
);
307 /* First, delete __main__ */
308 value
= PyDict_GetItemString(modules
, "__main__");
309 if (value
!= NULL
&& PyModule_Check(value
)) {
311 PySys_WriteStderr("# cleanup __main__\n");
312 _PyModule_Clear(value
);
313 PyDict_SetItemString(modules
, "__main__", Py_None
);
316 /* The special treatment of __builtin__ here is because even
317 when it's not referenced as a module, its dictionary is
318 referenced by almost every module's __builtins__. Since
319 deleting a module clears its dictionary (even if there are
320 references left to it), we need to delete the __builtin__
321 module last. Likewise, we don't delete sys until the very
322 end because it is implicitly referenced (e.g. by print).
324 Also note that we 'delete' modules by replacing their entry
325 in the modules dict with None, rather than really deleting
326 them; this avoids a rehash of the modules dictionary and
327 also marks them as "non existent" so they won't be
330 /* Next, repeatedly delete modules with a reference count of
331 one (skipping __builtin__ and sys) and delete them */
335 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
336 if (value
->ob_refcnt
!= 1)
338 if (PyString_Check(key
) && PyModule_Check(value
)) {
339 name
= PyString_AS_STRING(key
);
340 if (strcmp(name
, "__builtin__") == 0)
342 if (strcmp(name
, "sys") == 0)
346 "# cleanup[1] %s\n", name
);
347 _PyModule_Clear(value
);
348 PyDict_SetItem(modules
, key
, Py_None
);
354 /* Next, delete all modules (still skipping __builtin__ and sys) */
356 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
357 if (PyString_Check(key
) && PyModule_Check(value
)) {
358 name
= PyString_AS_STRING(key
);
359 if (strcmp(name
, "__builtin__") == 0)
361 if (strcmp(name
, "sys") == 0)
364 PySys_WriteStderr("# cleanup[2] %s\n", name
);
365 _PyModule_Clear(value
);
366 PyDict_SetItem(modules
, key
, Py_None
);
370 /* Next, delete sys and __builtin__ (in that order) */
371 value
= PyDict_GetItemString(modules
, "sys");
372 if (value
!= NULL
&& PyModule_Check(value
)) {
374 PySys_WriteStderr("# cleanup sys\n");
375 _PyModule_Clear(value
);
376 PyDict_SetItemString(modules
, "sys", Py_None
);
378 value
= PyDict_GetItemString(modules
, "__builtin__");
379 if (value
!= NULL
&& PyModule_Check(value
)) {
381 PySys_WriteStderr("# cleanup __builtin__\n");
382 _PyModule_Clear(value
);
383 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
386 /* Finally, clear and delete the modules directory */
387 PyDict_Clear(modules
);
388 interp
->modules
= NULL
;
393 /* Helper for pythonrun.c -- return magic number */
396 PyImport_GetMagicNumber(void)
402 /* Magic for extension modules (built-in as well as dynamically
403 loaded). To prevent initializing an extension module more than
404 once, we keep a static dictionary 'extensions' keyed by module name
405 (for built-in modules) or by filename (for dynamically loaded
406 modules), containing these modules. A copy of the module's
407 dictionary is stored by calling _PyImport_FixupExtension()
408 immediately after the module initialization function succeeds. A
409 copy can be retrieved from there by calling
410 _PyImport_FindExtension(). */
413 _PyImport_FixupExtension(char *name
, char *filename
)
415 PyObject
*modules
, *mod
, *dict
, *copy
;
416 if (extensions
== NULL
) {
417 extensions
= PyDict_New();
418 if (extensions
== NULL
)
421 modules
= PyImport_GetModuleDict();
422 mod
= PyDict_GetItemString(modules
, name
);
423 if (mod
== NULL
|| !PyModule_Check(mod
)) {
424 PyErr_Format(PyExc_SystemError
,
425 "_PyImport_FixupExtension: module %.200s not loaded", name
);
428 dict
= PyModule_GetDict(mod
);
431 copy
= PyDict_Copy(dict
);
434 PyDict_SetItemString(extensions
, filename
, copy
);
440 _PyImport_FindExtension(char *name
, char *filename
)
442 PyObject
*dict
, *mod
, *mdict
;
443 if (extensions
== NULL
)
445 dict
= PyDict_GetItemString(extensions
, filename
);
448 mod
= PyImport_AddModule(name
);
451 mdict
= PyModule_GetDict(mod
);
454 if (PyDict_Update(mdict
, dict
))
457 PySys_WriteStderr("import %s # previously loaded (%s)\n",
463 /* Get the module object corresponding to a module name.
464 First check the modules dictionary if there's one there,
465 if not, create a new one and insert in in the modules dictionary.
466 Because the former action is most common, THIS DOES NOT RETURN A
470 PyImport_AddModule(char *name
)
472 PyObject
*modules
= PyImport_GetModuleDict();
475 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
478 m
= PyModule_New(name
);
481 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
485 Py_DECREF(m
); /* Yes, it still exists, in modules! */
491 /* Execute a code object in a module and return the module object
492 WITH INCREMENTED REFERENCE COUNT */
495 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
497 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
501 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
503 PyObject
*modules
= PyImport_GetModuleDict();
506 m
= PyImport_AddModule(name
);
509 d
= PyModule_GetDict(m
);
510 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
511 if (PyDict_SetItemString(d
, "__builtins__",
512 PyEval_GetBuiltins()) != 0)
515 /* Remember the filename as the __file__ attribute */
517 if (pathname
!= NULL
) {
518 v
= PyString_FromString(pathname
);
523 v
= ((PyCodeObject
*)co
)->co_filename
;
526 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
527 PyErr_Clear(); /* Not important enough to report */
530 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
535 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
536 PyErr_Format(PyExc_ImportError
,
537 "Loaded module %.200s not found in sys.modules",
548 /* Given a pathname for a Python source file, fill a buffer with the
549 pathname for the corresponding compiled file. Return the pathname
550 for the compiled file, or NULL if there's no space in the buffer.
551 Doesn't set an exception. */
554 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
556 size_t len
= strlen(pathname
);
561 /* Treat .pyw as if it were .py. The case of ".pyw" must match
562 that used in _PyImport_StandardFiletab. */
563 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
564 --len
; /* pretend 'w' isn't there */
566 memcpy(buf
, pathname
, len
);
567 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
574 /* Given a pathname for a Python source file, its time of last
575 modification, and a pathname for a compiled file, check whether the
576 compiled file represents the same version of the source. If so,
577 return a FILE pointer for the compiled file, positioned just after
578 the header; if not, return NULL.
579 Doesn't set an exception. */
582 check_compiled_module(char *pathname
, long mtime
, char *cpathname
)
588 fp
= fopen(cpathname
, "rb");
591 magic
= PyMarshal_ReadLongFromFile(fp
);
592 if (magic
!= pyc_magic
) {
594 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
598 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
599 if (pyc_mtime
!= mtime
) {
601 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
606 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
611 /* Read a code object from a file and check it for validity */
613 static PyCodeObject
*
614 read_compiled_module(char *cpathname
, FILE *fp
)
618 co
= PyMarshal_ReadLastObjectFromFile(fp
);
619 /* Ugly: rd_object() may return NULL with or without error */
620 if (co
== NULL
|| !PyCode_Check(co
)) {
621 if (!PyErr_Occurred())
622 PyErr_Format(PyExc_ImportError
,
623 "Non-code object in %.200s", cpathname
);
627 return (PyCodeObject
*)co
;
631 /* Load a module from a compiled file, execute it, and return its
632 module object WITH INCREMENTED REFERENCE COUNT */
635 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
641 magic
= PyMarshal_ReadLongFromFile(fp
);
642 if (magic
!= pyc_magic
) {
643 PyErr_Format(PyExc_ImportError
,
644 "Bad magic number in %.200s", cpathname
);
647 (void) PyMarshal_ReadLongFromFile(fp
);
648 co
= read_compiled_module(cpathname
, fp
);
652 PySys_WriteStderr("import %s # precompiled from %s\n",
654 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
660 /* Parse a source file and return the corresponding code object */
662 static PyCodeObject
*
663 parse_source_module(char *pathname
, FILE *fp
)
668 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
671 co
= PyNode_Compile(n
, pathname
);
678 /* Helper to open a bytecode file for writing in exclusive mode */
681 open_exclusive(char *filename
)
683 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
684 /* Use O_EXCL to avoid a race condition when another process tries to
685 write the same file. When that happens, our open() call fails,
686 which is just fine (since it's only a cache).
687 XXX If the file exists and is writable but the directory is not
688 writable, the file will never be written. Oh well.
691 (void) unlink(filename
);
692 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
694 |O_BINARY
/* necessary for Windows */
700 return fdopen(fd
, "wb");
702 /* Best we can do -- on Windows this can't happen anyway */
703 return fopen(filename
, "wb");
708 /* Write a compiled module to a file, placing the time of last
709 modification of its source into the header.
710 Errors are ignored, if a write error occurs an attempt is made to
714 write_compiled_module(PyCodeObject
*co
, char *cpathname
, long mtime
)
718 fp
= open_exclusive(cpathname
);
722 "# can't create %s\n", cpathname
);
725 PyMarshal_WriteLongToFile(pyc_magic
, fp
);
726 /* First write a 0 for mtime */
727 PyMarshal_WriteLongToFile(0L, fp
);
728 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
731 PySys_WriteStderr("# can't write %s\n", cpathname
);
732 /* Don't keep partial file */
734 (void) unlink(cpathname
);
737 /* Now write the true mtime */
739 PyMarshal_WriteLongToFile(mtime
, fp
);
743 PySys_WriteStderr("# wrote %s\n", cpathname
);
745 PyMac_setfiletype(cpathname
, 'Pyth', 'PYC ');
750 /* Load a source module from a given file and return its module
751 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
752 byte-compiled file, use that instead. */
755 load_source_module(char *name
, char *pathname
, FILE *fp
)
759 char buf
[MAXPATHLEN
+1];
764 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
765 if (mtime
== (time_t)(-1))
767 #if SIZEOF_TIME_T > 4
768 /* Python's .pyc timestamp handling presumes that the timestamp fits
769 in 4 bytes. This will be fine until sometime in the year 2038,
770 when a 4-byte signed time_t will overflow.
773 PyErr_SetString(PyExc_OverflowError
,
774 "modification time overflows a 4 byte field");
778 cpathname
= make_compiled_pathname(pathname
, buf
,
779 (size_t)MAXPATHLEN
+ 1);
780 if (cpathname
!= NULL
&&
781 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
782 co
= read_compiled_module(cpathname
, fpc
);
787 PySys_WriteStderr("import %s # precompiled from %s\n",
789 pathname
= cpathname
;
792 co
= parse_source_module(pathname
, fp
);
796 PySys_WriteStderr("import %s # from %s\n",
798 write_compiled_module(co
, cpathname
, mtime
);
800 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
808 static PyObject
*load_module(char *, FILE *, char *, int);
809 static struct filedescr
*find_module(char *, PyObject
*,
810 char *, size_t, FILE **);
811 static struct _frozen
*find_frozen(char *name
);
813 /* Load a package and return its module object WITH INCREMENTED
817 load_package(char *name
, char *pathname
)
819 PyObject
*m
, *d
, *file
, *path
;
821 char buf
[MAXPATHLEN
+1];
823 struct filedescr
*fdp
;
825 m
= PyImport_AddModule(name
);
829 PySys_WriteStderr("import %s # directory %s\n",
831 d
= PyModule_GetDict(m
);
832 file
= PyString_FromString(pathname
);
835 path
= Py_BuildValue("[O]", file
);
840 err
= PyDict_SetItemString(d
, "__file__", file
);
842 err
= PyDict_SetItemString(d
, "__path__", path
);
848 fdp
= find_module("__init__", path
, buf
, sizeof(buf
), &fp
);
850 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
857 m
= load_module(name
, fp
, buf
, fdp
->type
);
867 /* Helper to test for built-in module */
870 is_builtin(char *name
)
873 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
874 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
875 if (PyImport_Inittab
[i
].initfunc
== NULL
)
885 /* Search the path (default sys.path) for a module. Return the
886 corresponding filedescr struct, and (via return arguments) the
887 pathname and an open file. Return NULL if the module is not found. */
890 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
894 static int case_ok(char *, int, int, char *);
895 static int find_init_module(char *); /* Forward */
897 static struct filedescr
*
898 find_module(char *realname
, PyObject
*path
, char *buf
, size_t buflen
,
903 struct filedescr
*fdp
= NULL
;
909 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
910 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
911 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
912 char name
[MAXPATHLEN
+1];
913 #if defined(PYOS_OS2)
915 size_t saved_namelen
;
916 char *saved_buf
= NULL
;
919 if (strlen(realname
) > MAXPATHLEN
) {
920 PyErr_SetString(PyExc_OverflowError
,
921 "module name is too long");
924 strcpy(name
, realname
);
926 if (path
!= NULL
&& PyString_Check(path
)) {
927 /* The only type of submodule allowed inside a "frozen"
928 package are other frozen modules or packages. */
929 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
930 PyErr_SetString(PyExc_ImportError
,
931 "full frozen module name too long");
934 strcpy(buf
, PyString_AsString(path
));
939 /* Freezing on the mac works different, and the modules are
940 ** actually on sys.path. So we don't take the quick exit but
941 ** continue with the normal flow.
945 if (find_frozen(name
) != NULL
) {
949 PyErr_Format(PyExc_ImportError
,
950 "No frozen submodule named %.200s", name
);
955 if (is_builtin(name
)) {
959 if ((find_frozen(name
)) != NULL
) {
965 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
971 path
= PySys_GetObject("path");
973 if (path
== NULL
|| !PyList_Check(path
)) {
974 PyErr_SetString(PyExc_ImportError
,
975 "sys.path must be a list of directory names");
978 npath
= PyList_Size(path
);
979 namelen
= strlen(name
);
980 for (i
= 0; i
< npath
; i
++) {
981 PyObject
*copy
= NULL
;
982 PyObject
*v
= PyList_GetItem(path
, i
);
983 #ifdef Py_USING_UNICODE
984 if (PyUnicode_Check(v
)) {
985 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
986 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
993 if (!PyString_Check(v
))
995 len
= PyString_Size(v
);
996 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
998 continue; /* Too long */
1000 strcpy(buf
, PyString_AsString(v
));
1001 if (strlen(buf
) != len
) {
1003 continue; /* v contains '\0' */
1007 ** Speedup: each sys.path item is interned, and
1008 ** FindResourceModule remembers which items refer to
1009 ** folders (so we don't have to bother trying to look
1010 ** into them for resources).
1012 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
1013 v
= PyList_GET_ITEM(path
, i
);
1014 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
1015 static struct filedescr resfiledescr
=
1016 {"", "", PY_RESOURCE
};
1019 return &resfiledescr
;
1021 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
1022 static struct filedescr resfiledescr
=
1023 {"", "", PY_CODERESOURCE
};
1026 return &resfiledescr
;
1029 if (len
> 0 && buf
[len
-1] != SEP
1031 && buf
[len
-1] != ALTSEP
1035 strcpy(buf
+len
, name
);
1038 /* Check for package import (buf holds a directory name,
1039 and there's an __init__ module in that directory */
1041 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1042 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1043 find_init_module(buf
) && /* it has __init__.py */
1044 case_ok(buf
, len
, namelen
, name
)) { /* and case matches */
1049 /* XXX How are you going to test for directories? */
1052 find_init_module(buf
) &&
1053 case_ok(buf
, len
, namelen
, name
)) {
1060 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
1063 #if defined(PYOS_OS2)
1064 /* take a snapshot of the module spec for restoration
1065 * after the 8 character DLL hackery
1067 saved_buf
= strdup(buf
);
1069 saved_namelen
= namelen
;
1070 #endif /* PYOS_OS2 */
1071 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1072 #if defined(PYOS_OS2)
1073 /* OS/2 limits DLLs to 8 character names (w/o
1075 * so if the name is longer than that and its a
1076 * dynamically loaded module we're going to try,
1077 * truncate the name before trying
1079 if (strlen(realname
) > 8) {
1080 /* is this an attempt to load a C extension? */
1081 const struct filedescr
*scan
;
1082 scan
= _PyImport_DynLoadFiletab
;
1083 while (scan
->suffix
!= NULL
) {
1084 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1089 if (scan
->suffix
!= NULL
) {
1090 /* yes, so truncate the name */
1092 len
-= strlen(realname
) - namelen
;
1096 #endif /* PYOS_OS2 */
1097 strcpy(buf
+len
, fdp
->suffix
);
1098 if (Py_VerboseFlag
> 1)
1099 PySys_WriteStderr("# trying %s\n", buf
);
1100 #endif /* !macintosh */
1101 filemode
= fdp
->mode
;
1102 if (filemode
[0] == 'U')
1103 filemode
= "r" PY_STDIOTEXTMODE
;
1104 fp
= fopen(buf
, filemode
);
1106 if (case_ok(buf
, len
, namelen
, name
))
1108 else { /* continue search */
1113 #if defined(PYOS_OS2)
1114 /* restore the saved snapshot */
1115 strcpy(buf
, saved_buf
);
1117 namelen
= saved_namelen
;
1120 #if defined(PYOS_OS2)
1121 /* don't need/want the module name snapshot anymore */
1133 PyErr_Format(PyExc_ImportError
,
1134 "No module named %.200s", name
);
1141 /* case_ok(char* buf, int len, int namelen, char* name)
1142 * The arguments here are tricky, best shown by example:
1143 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1145 * |--------------------- buf ---------------------|
1146 * |------------------- len ------------------|
1147 * |------ name -------|
1148 * |----- namelen -----|
1149 * buf is the full path, but len only counts up to (& exclusive of) the
1150 * extension. name is the module name, also exclusive of extension.
1152 * We've already done a successful stat() or fopen() on buf, so know that
1153 * there's some match, possibly case-insensitive.
1155 * case_ok() is to return 1 if there's a case-sensitive match for
1156 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1159 * case_ok() is used to implement case-sensitive import semantics even
1160 * on platforms with case-insensitive filesystems. It's trivial to implement
1161 * for case-sensitive filesystems. It's pretty much a cross-platform
1162 * nightmare for systems with case-insensitive filesystems.
1165 /* First we may need a pile of platform-specific header files; the sequence
1166 * of #if's here should match the sequence in the body of case_ok().
1168 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1169 #include <windows.h>
1171 #include <sys/cygwin.h>
1174 #elif defined(DJGPP)
1177 #elif defined(macintosh)
1178 #include <TextUtils.h>
1180 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1181 #include <sys/types.h>
1184 #elif defined(PYOS_OS2)
1186 #define INCL_DOSERRORS
1187 #define INCL_NOPMAPI
1190 #elif defined(RISCOS)
1191 #include "oslib/osfscontrol.h"
1195 case_ok(char *buf
, int len
, int namelen
, char *name
)
1197 /* Pick a platform-specific implementation; the sequence of #if's here should
1198 * match the sequence just above.
1201 /* MS_WINDOWS || __CYGWIN__ */
1202 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1203 WIN32_FIND_DATA data
;
1206 char tempbuf
[MAX_PATH
];
1209 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1213 cygwin32_conv_to_win32_path(buf
, tempbuf
);
1214 h
= FindFirstFile(tempbuf
, &data
);
1216 h
= FindFirstFile(buf
, &data
);
1218 if (h
== INVALID_HANDLE_VALUE
) {
1219 PyErr_Format(PyExc_NameError
,
1220 "Can't find file for module %.100s\n(filename %.300s)",
1225 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1228 #elif defined(DJGPP)
1232 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1235 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1237 PyErr_Format(PyExc_NameError
,
1238 "Can't find file for module %.100s\n(filename %.300s)",
1242 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1245 #elif defined(macintosh)
1249 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1252 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1254 PyErr_Format(PyExc_NameError
,
1255 "Can't find file for module %.100s\n(filename %.300s)",
1259 return fss
.name
[0] >= namelen
&&
1260 strncmp(name
, (char *)fss
.name
+1, namelen
) == 0;
1262 /* new-fangled macintosh (macosx) */
1263 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1266 char dirname
[MAXPATHLEN
+ 1];
1267 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1269 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1272 /* Copy the dir component into dirname; substitute "." if empty */
1278 assert(dirlen
<= MAXPATHLEN
);
1279 memcpy(dirname
, buf
, dirlen
);
1280 dirname
[dirlen
] = '\0';
1282 /* Open the directory and search the entries for an exact match. */
1283 dirp
= opendir(dirname
);
1285 char *nameWithExt
= buf
+ len
- namelen
;
1286 while ((dp
= readdir(dirp
)) != NULL
) {
1288 #ifdef _DIRENT_HAVE_D_NAMELEN
1293 if (thislen
>= namelen
&&
1294 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1295 (void)closedir(dirp
);
1296 return 1; /* Found */
1299 (void)closedir(dirp
);
1301 return 0 ; /* Not found */
1304 #elif defined(RISCOS)
1305 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1306 char buf2
[MAXPATHLEN
+2];
1307 char *nameWithExt
= buf
+len
-namelen
;
1311 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1315 append wildcard, otherwise case of filename wouldn't be touched */
1319 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1320 canonlen
= MAXPATHLEN
+1-canonlen
;
1321 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1323 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1324 return 1; /* match */
1329 #elif defined(PYOS_OS2)
1335 if (getenv("PYTHONCASEOK") != NULL
)
1338 rc
= DosFindFirst(buf
,
1340 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1341 &ffbuf
, sizeof(ffbuf
),
1346 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1348 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1357 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1359 find_init_module(char *buf
)
1361 const size_t save_len
= strlen(buf
);
1362 size_t i
= save_len
;
1363 char *pname
; /* pointer to start of __init__ */
1364 struct stat statbuf
;
1366 /* For calling case_ok(buf, len, namelen, name):
1367 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1369 * |--------------------- buf ---------------------|
1370 * |------------------- len ------------------|
1371 * |------ name -------|
1372 * |----- namelen -----|
1374 if (save_len
+ 13 >= MAXPATHLEN
)
1378 strcpy(pname
, "__init__.py");
1379 if (stat(buf
, &statbuf
) == 0) {
1381 save_len
+ 9, /* len("/__init__") */
1382 8, /* len("__init__") */
1384 buf
[save_len
] = '\0';
1389 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1390 if (stat(buf
, &statbuf
) == 0) {
1392 save_len
+ 9, /* len("/__init__") */
1393 8, /* len("__init__") */
1395 buf
[save_len
] = '\0';
1399 buf
[save_len
] = '\0';
1407 find_init_module(buf
)
1410 int save_len
= strlen(buf
);
1413 if (save_len
+ 13 >= MAXPATHLEN
)
1416 strcpy(buf
+i
, "__init__/py");
1418 buf
[save_len
] = '\0';
1422 if (Py_OptimizeFlag
)
1427 buf
[save_len
] = '\0';
1430 buf
[save_len
] = '\0';
1435 #endif /* HAVE_STAT */
1438 static int init_builtin(char *); /* Forward */
1440 /* Load an external module using the default search path and return
1441 its module object WITH INCREMENTED REFERENCE COUNT */
1444 load_module(char *name
, FILE *fp
, char *buf
, int type
)
1450 /* First check that there's an open file (if we need one) */
1455 PyErr_Format(PyExc_ValueError
,
1456 "file object required for import (type code %d)",
1465 m
= load_source_module(name
, buf
, fp
);
1469 m
= load_compiled_module(name
, buf
, fp
);
1472 #ifdef HAVE_DYNAMIC_LOADING
1474 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1480 m
= PyMac_LoadResourceModule(name
, buf
);
1482 case PY_CODERESOURCE
:
1483 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1488 m
= load_package(name
, buf
);
1493 if (buf
!= NULL
&& buf
[0] != '\0')
1495 if (type
== C_BUILTIN
)
1496 err
= init_builtin(name
);
1498 err
= PyImport_ImportFrozenModule(name
);
1502 PyErr_Format(PyExc_ImportError
,
1503 "Purported %s module %.200s not found",
1505 "builtin" : "frozen",
1509 modules
= PyImport_GetModuleDict();
1510 m
= PyDict_GetItemString(modules
, name
);
1514 "%s module %.200s not properly initialized",
1516 "builtin" : "frozen",
1524 PyErr_Format(PyExc_ImportError
,
1525 "Don't know how to import %.200s (type code %d)",
1535 /* Initialize a built-in module.
1536 Return 1 for succes, 0 if the module is not found, and -1 with
1537 an exception set if the initialization failed. */
1540 init_builtin(char *name
)
1544 if (_PyImport_FindExtension(name
, name
) != NULL
)
1547 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1548 if (strcmp(name
, p
->name
) == 0) {
1549 if (p
->initfunc
== NULL
) {
1550 PyErr_Format(PyExc_ImportError
,
1551 "Cannot re-init internal module %.200s",
1556 PySys_WriteStderr("import %s # builtin\n", name
);
1558 if (PyErr_Occurred())
1560 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1569 /* Frozen modules */
1571 static struct _frozen
*
1572 find_frozen(char *name
)
1576 for (p
= PyImport_FrozenModules
; ; p
++) {
1577 if (p
->name
== NULL
)
1579 if (strcmp(p
->name
, name
) == 0)
1586 get_frozen_object(char *name
)
1588 struct _frozen
*p
= find_frozen(name
);
1592 PyErr_Format(PyExc_ImportError
,
1593 "No such frozen object named %.200s",
1597 if (p
->code
== NULL
) {
1598 PyErr_Format(PyExc_ImportError
,
1599 "Excluded frozen object named %.200s",
1606 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1609 /* Initialize a frozen module.
1610 Return 1 for succes, 0 if the module is not found, and -1 with
1611 an exception set if the initialization failed.
1612 This function is also used from frozenmain.c */
1615 PyImport_ImportFrozenModule(char *name
)
1617 struct _frozen
*p
= find_frozen(name
);
1625 if (p
->code
== NULL
) {
1626 PyErr_Format(PyExc_ImportError
,
1627 "Excluded frozen object named %.200s",
1632 ispackage
= (size
< 0);
1636 PySys_WriteStderr("import %s # frozen%s\n",
1637 name
, ispackage
? " package" : "");
1638 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1641 if (!PyCode_Check(co
)) {
1643 PyErr_Format(PyExc_TypeError
,
1644 "frozen object %.200s is not a code object",
1649 /* Set __path__ to the package name */
1652 m
= PyImport_AddModule(name
);
1655 d
= PyModule_GetDict(m
);
1656 s
= PyString_InternFromString(name
);
1659 err
= PyDict_SetItemString(d
, "__path__", s
);
1664 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1673 /* Import a module, either built-in, frozen, or external, and return
1674 its module object WITH INCREMENTED REFERENCE COUNT */
1677 PyImport_ImportModule(char *name
)
1682 pname
= PyString_FromString(name
);
1683 result
= PyImport_Import(pname
);
1688 /* Forward declarations for helper routines */
1689 static PyObject
*get_parent(PyObject
*globals
, char *buf
, int *p_buflen
);
1690 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1691 char **p_name
, char *buf
, int *p_buflen
);
1692 static int mark_miss(char *name
);
1693 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1694 char *buf
, int buflen
, int recursive
);
1695 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1697 /* The Magnum Opus of dotted-name import :-) */
1700 import_module_ex(char *name
, PyObject
*globals
, PyObject
*locals
,
1703 char buf
[MAXPATHLEN
+1];
1705 PyObject
*parent
, *head
, *next
, *tail
;
1707 parent
= get_parent(globals
, buf
, &buflen
);
1711 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1718 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1727 if (fromlist
!= NULL
) {
1728 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1732 if (fromlist
== NULL
) {
1738 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1747 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
1752 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1758 get_parent(PyObject
*globals
, char *buf
, int *p_buflen
)
1760 static PyObject
*namestr
= NULL
;
1761 static PyObject
*pathstr
= NULL
;
1762 PyObject
*modname
, *modpath
, *modules
, *parent
;
1764 if (globals
== NULL
|| !PyDict_Check(globals
))
1767 if (namestr
== NULL
) {
1768 namestr
= PyString_InternFromString("__name__");
1769 if (namestr
== NULL
)
1772 if (pathstr
== NULL
) {
1773 pathstr
= PyString_InternFromString("__path__");
1774 if (pathstr
== NULL
)
1780 modname
= PyDict_GetItem(globals
, namestr
);
1781 if (modname
== NULL
|| !PyString_Check(modname
))
1784 modpath
= PyDict_GetItem(globals
, pathstr
);
1785 if (modpath
!= NULL
) {
1786 int len
= PyString_GET_SIZE(modname
);
1787 if (len
> MAXPATHLEN
) {
1788 PyErr_SetString(PyExc_ValueError
,
1789 "Module name too long");
1792 strcpy(buf
, PyString_AS_STRING(modname
));
1796 char *start
= PyString_AS_STRING(modname
);
1797 char *lastdot
= strrchr(start
, '.');
1799 if (lastdot
== NULL
)
1801 len
= lastdot
- start
;
1802 if (len
>= MAXPATHLEN
) {
1803 PyErr_SetString(PyExc_ValueError
,
1804 "Module name too long");
1807 strncpy(buf
, start
, len
);
1812 modules
= PyImport_GetModuleDict();
1813 parent
= PyDict_GetItemString(modules
, buf
);
1817 /* We expect, but can't guarantee, if parent != None, that:
1818 - parent.__name__ == buf
1819 - parent.__dict__ is globals
1820 If this is violated... Who cares? */
1823 /* altmod is either None or same as mod */
1825 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
1828 char *name
= *p_name
;
1829 char *dot
= strchr(name
, '.');
1843 PyErr_SetString(PyExc_ValueError
,
1844 "Empty module name");
1848 p
= buf
+ *p_buflen
;
1851 if (p
+len
-buf
>= MAXPATHLEN
) {
1852 PyErr_SetString(PyExc_ValueError
,
1853 "Module name too long");
1856 strncpy(p
, name
, len
);
1858 *p_buflen
= p
+len
-buf
;
1860 result
= import_submodule(mod
, p
, buf
);
1861 if (result
== Py_None
&& altmod
!= mod
) {
1863 /* Here, altmod must be None and mod must not be None */
1864 result
= import_submodule(altmod
, p
, p
);
1865 if (result
!= NULL
&& result
!= Py_None
) {
1866 if (mark_miss(buf
) != 0) {
1870 strncpy(buf
, name
, len
);
1878 if (result
== Py_None
) {
1880 PyErr_Format(PyExc_ImportError
,
1881 "No module named %.200s", name
);
1889 mark_miss(char *name
)
1891 PyObject
*modules
= PyImport_GetModuleDict();
1892 return PyDict_SetItemString(modules
, name
, Py_None
);
1896 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, int buflen
,
1901 if (!PyObject_HasAttrString(mod
, "__path__"))
1904 for (i
= 0; ; i
++) {
1905 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
1908 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
1914 if (!PyString_Check(item
)) {
1915 PyErr_SetString(PyExc_TypeError
,
1916 "Item in ``from list'' not a string");
1920 if (PyString_AS_STRING(item
)[0] == '*') {
1923 /* See if the package defines __all__ */
1925 continue; /* Avoid endless recursion */
1926 all
= PyObject_GetAttrString(mod
, "__all__");
1930 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
1936 hasit
= PyObject_HasAttr(mod
, item
);
1938 char *subname
= PyString_AS_STRING(item
);
1941 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
1942 PyErr_SetString(PyExc_ValueError
,
1943 "Module name too long");
1950 submod
= import_submodule(mod
, subname
, buf
);
1952 if (submod
== NULL
) {
1964 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
1966 PyObject
*modules
= PyImport_GetModuleDict();
1967 PyObject
*m
, *res
= NULL
;
1970 if mod == None: subname == fullname
1971 else: mod.__name__ + "." + subname == fullname
1974 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
1979 char buf
[MAXPATHLEN
+1];
1980 struct filedescr
*fdp
;
1986 path
= PyObject_GetAttrString(mod
, "__path__");
1995 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
1998 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2004 m
= load_module(fullname
, fp
, buf
, fdp
->type
);
2007 if (mod
!= Py_None
) {
2008 /* Irrespective of the success of this load, make a
2009 reference to it in the parent package module.
2010 A copy gets saved in the modules dictionary
2011 under the full name, so get a reference from
2012 there, if need be. (The exception is when
2013 the load failed with a SyntaxError -- then
2014 there's no trace in sys.modules. In that case,
2015 of course, do nothing extra.) */
2018 res
= PyDict_GetItemString(modules
, fullname
);
2020 PyObject_SetAttrString(mod
, subname
, res
) < 0) {
2031 /* Re-import a module of any kind and return its module object, WITH
2032 INCREMENTED REFERENCE COUNT */
2035 PyImport_ReloadModule(PyObject
*m
)
2037 PyObject
*modules
= PyImport_GetModuleDict();
2038 PyObject
*path
= NULL
;
2039 char *name
, *subname
;
2040 char buf
[MAXPATHLEN
+1];
2041 struct filedescr
*fdp
;
2044 if (m
== NULL
|| !PyModule_Check(m
)) {
2045 PyErr_SetString(PyExc_TypeError
,
2046 "reload() argument must be module");
2049 name
= PyModule_GetName(m
);
2052 if (m
!= PyDict_GetItemString(modules
, name
)) {
2053 PyErr_Format(PyExc_ImportError
,
2054 "reload(): module %.200s not in sys.modules",
2058 subname
= strrchr(name
, '.');
2059 if (subname
== NULL
)
2062 PyObject
*parentname
, *parent
;
2063 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2064 if (parentname
== NULL
)
2066 parent
= PyDict_GetItem(modules
, parentname
);
2067 Py_DECREF(parentname
);
2068 if (parent
== NULL
) {
2069 PyErr_Format(PyExc_ImportError
,
2070 "reload(): parent %.200s not in sys.modules",
2075 path
= PyObject_GetAttrString(parent
, "__path__");
2080 fdp
= find_module(subname
, path
, buf
, MAXPATHLEN
+1, &fp
);
2084 m
= load_module(name
, fp
, buf
, fdp
->type
);
2091 /* Higher-level import emulator which emulates the "import" statement
2092 more accurately -- it invokes the __import__() function from the
2093 builtins of the current globals. This means that the import is
2094 done using whatever import hooks are installed in the current
2095 environment, e.g. by "rexec".
2096 A dummy list ["__doc__"] is passed as the 4th argument so that
2097 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2098 will return <module "gencache"> instead of <module "win32com">. */
2101 PyImport_Import(PyObject
*module_name
)
2103 static PyObject
*silly_list
= NULL
;
2104 static PyObject
*builtins_str
= NULL
;
2105 static PyObject
*import_str
= NULL
;
2106 PyObject
*globals
= NULL
;
2107 PyObject
*import
= NULL
;
2108 PyObject
*builtins
= NULL
;
2111 /* Initialize constant string objects */
2112 if (silly_list
== NULL
) {
2113 import_str
= PyString_InternFromString("__import__");
2114 if (import_str
== NULL
)
2116 builtins_str
= PyString_InternFromString("__builtins__");
2117 if (builtins_str
== NULL
)
2119 silly_list
= Py_BuildValue("[s]", "__doc__");
2120 if (silly_list
== NULL
)
2124 /* Get the builtins from current globals */
2125 globals
= PyEval_GetGlobals();
2126 if (globals
!= NULL
) {
2128 builtins
= PyObject_GetItem(globals
, builtins_str
);
2129 if (builtins
== NULL
)
2133 /* No globals -- use standard builtins, and fake globals */
2136 builtins
= PyImport_ImportModuleEx("__builtin__",
2138 if (builtins
== NULL
)
2140 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2141 if (globals
== NULL
)
2145 /* Get the __import__ function from the builtins */
2146 if (PyDict_Check(builtins
)) {
2147 import
= PyObject_GetItem(builtins
, import_str
);
2149 PyErr_SetObject(PyExc_KeyError
, import_str
);
2152 import
= PyObject_GetAttr(builtins
, import_str
);
2156 /* Call the _import__ function with the proper argument list */
2157 r
= PyObject_CallFunction(import
, "OOOO",
2158 module_name
, globals
, globals
, silly_list
);
2161 Py_XDECREF(globals
);
2162 Py_XDECREF(builtins
);
2169 /* Module 'imp' provides Python access to the primitives used for
2174 imp_get_magic(PyObject
*self
, PyObject
*args
)
2178 if (!PyArg_ParseTuple(args
, ":get_magic"))
2180 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2181 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2182 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2183 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2185 return PyString_FromStringAndSize(buf
, 4);
2189 imp_get_suffixes(PyObject
*self
, PyObject
*args
)
2192 struct filedescr
*fdp
;
2194 if (!PyArg_ParseTuple(args
, ":get_suffixes"))
2196 list
= PyList_New(0);
2199 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2200 PyObject
*item
= Py_BuildValue("ssi",
2201 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2206 if (PyList_Append(list
, item
) < 0) {
2217 call_find_module(char *name
, PyObject
*path
)
2219 extern int fclose(FILE *);
2220 PyObject
*fob
, *ret
;
2221 struct filedescr
*fdp
;
2222 char pathname
[MAXPATHLEN
+1];
2226 if (path
== Py_None
)
2228 fdp
= find_module(name
, path
, pathname
, MAXPATHLEN
+1, &fp
);
2232 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2242 ret
= Py_BuildValue("Os(ssi)",
2243 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2249 imp_find_module(PyObject
*self
, PyObject
*args
)
2252 PyObject
*path
= NULL
;
2253 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2255 return call_find_module(name
, path
);
2259 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2264 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2266 ret
= init_builtin(name
);
2273 m
= PyImport_AddModule(name
);
2279 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2284 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2286 ret
= PyImport_ImportFrozenModule(name
);
2293 m
= PyImport_AddModule(name
);
2299 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2303 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2305 return get_frozen_object(name
);
2309 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2312 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2314 return PyInt_FromLong(is_builtin(name
));
2318 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2322 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2324 p
= find_frozen(name
);
2325 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2329 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2334 mode
= "r" PY_STDIOTEXTMODE
;
2335 fp
= fopen(pathname
, mode
);
2337 PyErr_SetFromErrno(PyExc_IOError
);
2340 fp
= PyFile_AsFile(fob
);
2342 PyErr_SetString(PyExc_ValueError
,
2343 "bad/closed file object");
2349 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2353 PyObject
*fob
= NULL
;
2356 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2357 &PyFile_Type
, &fob
))
2359 fp
= get_file(pathname
, fob
, "rb");
2362 m
= load_compiled_module(name
, pathname
, fp
);
2368 #ifdef HAVE_DYNAMIC_LOADING
2371 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2375 PyObject
*fob
= NULL
;
2378 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2379 &PyFile_Type
, &fob
))
2382 fp
= get_file(pathname
, fob
, "r");
2386 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2390 #endif /* HAVE_DYNAMIC_LOADING */
2393 imp_load_source(PyObject
*self
, PyObject
*args
)
2397 PyObject
*fob
= NULL
;
2400 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2401 &PyFile_Type
, &fob
))
2403 fp
= get_file(pathname
, fob
, "r");
2406 m
= load_source_module(name
, pathname
, fp
);
2414 imp_load_resource(PyObject
*self
, PyObject
*args
)
2420 if (!PyArg_ParseTuple(args
, "ss:load_resource", &name
, &pathname
))
2422 m
= PyMac_LoadResourceModule(name
, pathname
);
2425 #endif /* macintosh */
2428 imp_load_module(PyObject
*self
, PyObject
*args
)
2433 char *suffix
; /* Unused */
2438 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2439 &name
, &fob
, &pathname
,
2440 &suffix
, &mode
, &type
))
2443 /* Mode must start with 'r' or 'U' and must not contain '+'.
2444 Implicit in this test is the assumption that the mode
2445 may contain other modifiers like 'b' or 't'. */
2447 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2448 PyErr_Format(PyExc_ValueError
,
2449 "invalid file open mode %.200s", mode
);
2456 if (!PyFile_Check(fob
)) {
2457 PyErr_SetString(PyExc_ValueError
,
2458 "load_module arg#2 should be a file or None");
2461 fp
= get_file(pathname
, fob
, mode
);
2465 return load_module(name
, fp
, pathname
, type
);
2469 imp_load_package(PyObject
*self
, PyObject
*args
)
2473 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2475 return load_package(name
, pathname
);
2479 imp_new_module(PyObject
*self
, PyObject
*args
)
2482 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2484 return PyModule_New(name
);
2489 PyDoc_STRVAR(doc_imp
,
2490 "This module provides the components needed to build your own\n\
2491 __import__ function. Undocumented functions are obsolete.");
2493 PyDoc_STRVAR(doc_find_module
,
2494 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2495 Search for a module. If path is omitted or None, search for a\n\
2496 built-in, frozen or special module and continue search in sys.path.\n\
2497 The module name cannot contain '.'; to search for a submodule of a\n\
2498 package, pass the submodule name and the package's __path__.");
2500 PyDoc_STRVAR(doc_load_module
,
2501 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2502 Load a module, given information returned by find_module().\n\
2503 The module name must include the full package name, if any.");
2505 PyDoc_STRVAR(doc_get_magic
,
2506 "get_magic() -> string\n\
2507 Return the magic number for .pyc or .pyo files.");
2509 PyDoc_STRVAR(doc_get_suffixes
,
2510 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2511 Return a list of (suffix, mode, type) tuples describing the files\n\
2512 that find_module() looks for.");
2514 PyDoc_STRVAR(doc_new_module
,
2515 "new_module(name) -> module\n\
2516 Create a new module. Do not enter it in sys.modules.\n\
2517 The module name must include the full package name, if any.");
2519 PyDoc_STRVAR(doc_lock_held
,
2520 "lock_held() -> 0 or 1\n\
2521 Return 1 if the import lock is currently held.\n\
2522 On platforms without threads, return 0.");
2524 static PyMethodDef imp_methods
[] = {
2525 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
2526 {"get_magic", imp_get_magic
, METH_VARARGS
, doc_get_magic
},
2527 {"get_suffixes", imp_get_suffixes
, METH_VARARGS
, doc_get_suffixes
},
2528 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
2529 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
2530 {"lock_held", imp_lock_held
, METH_VARARGS
, doc_lock_held
},
2531 /* The rest are obsolete */
2532 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
2533 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
2534 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
2535 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
2536 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
2537 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
2538 #ifdef HAVE_DYNAMIC_LOADING
2539 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
2541 {"load_package", imp_load_package
, METH_VARARGS
},
2543 {"load_resource", imp_load_resource
, METH_VARARGS
},
2545 {"load_source", imp_load_source
, METH_VARARGS
},
2546 {NULL
, NULL
} /* sentinel */
2550 setint(PyObject
*d
, char *name
, int value
)
2555 v
= PyInt_FromLong((long)value
);
2556 err
= PyDict_SetItemString(d
, name
, v
);
2566 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2567 NULL
, PYTHON_API_VERSION
);
2568 d
= PyModule_GetDict(m
);
2570 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2571 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2572 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2573 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2574 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2575 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2576 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2577 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2578 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2585 /* API for embedding applications that want to add their own entries
2586 to the table of built-in modules. This should normally be called
2587 *before* Py_Initialize(). When the table resize fails, -1 is
2588 returned and the existing table is unchanged.
2590 After a similar function by Just van Rossum. */
2593 PyImport_ExtendInittab(struct _inittab
*newtab
)
2595 static struct _inittab
*our_copy
= NULL
;
2599 /* Count the number of entries in both tables */
2600 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2603 return 0; /* Nothing to do */
2604 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2607 /* Allocate new memory for the combined table */
2609 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
2613 /* Copy the tables into the new memory */
2614 if (our_copy
!= PyImport_Inittab
)
2615 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2616 PyImport_Inittab
= our_copy
= p
;
2617 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2622 /* Shorthand to add a single entry given a name and a function */
2625 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
2627 struct _inittab newtab
[2];
2629 memset(newtab
, '\0', sizeof newtab
);
2631 newtab
[0].name
= name
;
2632 newtab
[0].initfunc
= initfunc
;
2634 return PyImport_ExtendInittab(newtab
);