2 /* Module definition and import implementation */
6 #include "Python-ast.h"
7 #undef Yield /* undefine macro conflicting with winbase.h */
25 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
28 /* Magic word to reject .pyc files generated by other Python versions.
29 It should change for each incompatible change to the bytecode.
31 The value of CR and LF is incorporated so if you ever read or write
32 a .pyc file in text mode the magic number will be wrong; also, the
33 Apple MPW compiler swaps their values, botching string constants.
35 The magic numbers must be spaced apart atleast 2 values, as the
36 -U interpeter flag will cause MAGIC+1 being used. They have been
37 odd numbers for some time now.
39 There were a variety of old schemes for setting the magic number.
40 The current working scheme is to increment the previous value by
56 Python 2.3a0: 62011 (!)
61 Python 2.5a0: 62081 (ast-branch)
62 Python 2.5a0: 62091 (with)
63 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
64 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
65 Python 2.5b3: 62111 (fix wrong code: x += yield)
66 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
67 storing constants that should have been removed)
68 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
69 Python 2.6a0: 62141 (peephole optimizations)
72 #define MAGIC (62141 | ((long)'\r'<<16) | ((long)'\n'<<24))
74 /* Magic word as global; note that _PyImport_Init() can change the
75 value of this global to accommodate for alterations of how the
76 compiler works which are enabled by command line switches. */
77 static long pyc_magic
= MAGIC
;
79 /* See _PyImport_FixupExtension() below */
80 static PyObject
*extensions
= NULL
;
82 /* This table is defined in config.c: */
83 extern struct _inittab _PyImport_Inittab
[];
85 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
87 /* these tables define the module suffixes that Python recognizes */
88 struct filedescr
* _PyImport_Filetab
= NULL
;
91 static const struct filedescr _PyImport_StandardFiletab
[] = {
92 {"/py", "U", PY_SOURCE
},
93 {"/pyc", "rb", PY_COMPILED
},
97 static const struct filedescr _PyImport_StandardFiletab
[] = {
98 {".py", "U", PY_SOURCE
},
100 {".pyw", "U", PY_SOURCE
},
102 {".pyc", "rb", PY_COMPILED
},
107 static PyTypeObject NullImporterType
; /* Forward reference */
109 /* Initialize things */
114 const struct filedescr
*scan
;
115 struct filedescr
*filetab
;
119 /* prepare _PyImport_Filetab: copy entries from
120 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
122 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
124 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
126 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
128 Py_FatalError("Can't initialize import file table.");
129 memcpy(filetab
, _PyImport_DynLoadFiletab
,
130 countD
* sizeof(struct filedescr
));
131 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
132 countS
* sizeof(struct filedescr
));
133 filetab
[countD
+ countS
].suffix
= NULL
;
135 _PyImport_Filetab
= filetab
;
137 if (Py_OptimizeFlag
) {
138 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
139 for (; filetab
->suffix
!= NULL
; filetab
++) {
141 if (strcmp(filetab
->suffix
, ".pyc") == 0)
142 filetab
->suffix
= ".pyo";
144 if (strcmp(filetab
->suffix
, "/pyc") == 0)
145 filetab
->suffix
= "/pyo";
150 if (Py_UnicodeFlag
) {
151 /* Fix the pyc_magic so that byte compiled code created
152 using the all-Unicode method doesn't interfere with
153 code created in normal operation mode. */
154 pyc_magic
= MAGIC
+ 1;
159 _PyImportHooks_Init(void)
161 PyObject
*v
, *path_hooks
= NULL
, *zimpimport
;
164 /* adding sys.path_hooks and sys.path_importer_cache, setting up
166 if (PyType_Ready(&NullImporterType
) < 0)
170 PySys_WriteStderr("# installing zipimport hook\n");
175 err
= PySys_SetObject("meta_path", v
);
182 err
= PySys_SetObject("path_importer_cache", v
);
186 path_hooks
= PyList_New(0);
187 if (path_hooks
== NULL
)
189 err
= PySys_SetObject("path_hooks", path_hooks
);
193 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
194 "path_importer_cache, or NullImporter failed"
198 zimpimport
= PyImport_ImportModule("zipimport");
199 if (zimpimport
== NULL
) {
200 PyErr_Clear(); /* No zip import module -- okay */
202 PySys_WriteStderr("# can't import zipimport\n");
205 PyObject
*zipimporter
= PyObject_GetAttrString(zimpimport
,
207 Py_DECREF(zimpimport
);
208 if (zipimporter
== NULL
) {
209 PyErr_Clear(); /* No zipimporter object -- okay */
212 "# can't import zipimport.zipimporter\n");
215 /* sys.path_hooks.append(zipimporter) */
216 err
= PyList_Append(path_hooks
, zipimporter
);
217 Py_DECREF(zipimporter
);
222 "# installed zipimport hook\n");
225 Py_DECREF(path_hooks
);
231 Py_XDECREF(extensions
);
233 PyMem_DEL(_PyImport_Filetab
);
234 _PyImport_Filetab
= NULL
;
238 /* Locking primitives to prevent parallel imports of the same module
239 in different threads to return with a partially loaded module.
240 These calls are serialized by the global interpreter lock. */
244 #include "pythread.h"
246 static PyThread_type_lock import_lock
= 0;
247 static long import_lock_thread
= -1;
248 static int import_lock_level
= 0;
253 long me
= PyThread_get_thread_ident();
255 return; /* Too bad */
256 if (import_lock
== NULL
) {
257 import_lock
= PyThread_allocate_lock();
258 if (import_lock
== NULL
)
259 return; /* Nothing much we can do. */
261 if (import_lock_thread
== me
) {
265 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0))
267 PyThreadState
*tstate
= PyEval_SaveThread();
268 PyThread_acquire_lock(import_lock
, 1);
269 PyEval_RestoreThread(tstate
);
271 import_lock_thread
= me
;
272 import_lock_level
= 1;
278 long me
= PyThread_get_thread_ident();
279 if (me
== -1 || import_lock
== NULL
)
280 return 0; /* Too bad */
281 if (import_lock_thread
!= me
)
284 if (import_lock_level
== 0) {
285 import_lock_thread
= -1;
286 PyThread_release_lock(import_lock
);
291 /* This function is called from PyOS_AfterFork to ensure that newly
292 created child processes do not share locks with the parent. */
295 _PyImport_ReInitLock(void)
298 if (import_lock
!= NULL
)
299 import_lock
= PyThread_allocate_lock();
305 #define lock_import()
306 #define unlock_import() 0
311 imp_lock_held(PyObject
*self
, PyObject
*noargs
)
314 return PyBool_FromLong(import_lock_thread
!= -1);
316 return PyBool_FromLong(0);
321 imp_acquire_lock(PyObject
*self
, PyObject
*noargs
)
331 imp_release_lock(PyObject
*self
, PyObject
*noargs
)
334 if (unlock_import() < 0) {
335 PyErr_SetString(PyExc_RuntimeError
,
336 "not holding the import lock");
345 imp_modules_reloading_clear(void)
347 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
348 if (interp
->modules_reloading
!= NULL
)
349 PyDict_Clear(interp
->modules_reloading
);
355 PyImport_GetModuleDict(void)
357 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
358 if (interp
->modules
== NULL
)
359 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
360 return interp
->modules
;
364 /* List of names to clear in sys */
365 static char* sys_deletes
[] = {
366 "path", "argv", "ps1", "ps2", "exitfunc",
367 "exc_type", "exc_value", "exc_traceback",
368 "last_type", "last_value", "last_traceback",
369 "path_hooks", "path_importer_cache", "meta_path",
373 static char* sys_files
[] = {
374 "stdin", "__stdin__",
375 "stdout", "__stdout__",
376 "stderr", "__stderr__",
381 /* Un-initialize things, as good as we can */
384 PyImport_Cleanup(void)
386 Py_ssize_t pos
, ndone
;
388 PyObject
*key
, *value
, *dict
;
389 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
390 PyObject
*modules
= interp
->modules
;
393 return; /* Already done */
395 /* Delete some special variables first. These are common
396 places where user values hide and people complain when their
397 destructors fail. Since the modules containing them are
398 deleted *last* of all, they would come too late in the normal
399 destruction order. Sigh. */
401 value
= PyDict_GetItemString(modules
, "__builtin__");
402 if (value
!= NULL
&& PyModule_Check(value
)) {
403 dict
= PyModule_GetDict(value
);
405 PySys_WriteStderr("# clear __builtin__._\n");
406 PyDict_SetItemString(dict
, "_", Py_None
);
408 value
= PyDict_GetItemString(modules
, "sys");
409 if (value
!= NULL
&& PyModule_Check(value
)) {
412 dict
= PyModule_GetDict(value
);
413 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
415 PySys_WriteStderr("# clear sys.%s\n", *p
);
416 PyDict_SetItemString(dict
, *p
, Py_None
);
418 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
420 PySys_WriteStderr("# restore sys.%s\n", *p
);
421 v
= PyDict_GetItemString(dict
, *(p
+1));
424 PyDict_SetItemString(dict
, *p
, v
);
428 /* First, delete __main__ */
429 value
= PyDict_GetItemString(modules
, "__main__");
430 if (value
!= NULL
&& PyModule_Check(value
)) {
432 PySys_WriteStderr("# cleanup __main__\n");
433 _PyModule_Clear(value
);
434 PyDict_SetItemString(modules
, "__main__", Py_None
);
437 /* The special treatment of __builtin__ here is because even
438 when it's not referenced as a module, its dictionary is
439 referenced by almost every module's __builtins__. Since
440 deleting a module clears its dictionary (even if there are
441 references left to it), we need to delete the __builtin__
442 module last. Likewise, we don't delete sys until the very
443 end because it is implicitly referenced (e.g. by print).
445 Also note that we 'delete' modules by replacing their entry
446 in the modules dict with None, rather than really deleting
447 them; this avoids a rehash of the modules dictionary and
448 also marks them as "non existent" so they won't be
451 /* Next, repeatedly delete modules with a reference count of
452 one (skipping __builtin__ and sys) and delete them */
456 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
457 if (value
->ob_refcnt
!= 1)
459 if (PyString_Check(key
) && PyModule_Check(value
)) {
460 name
= PyString_AS_STRING(key
);
461 if (strcmp(name
, "__builtin__") == 0)
463 if (strcmp(name
, "sys") == 0)
467 "# cleanup[1] %s\n", name
);
468 _PyModule_Clear(value
);
469 PyDict_SetItem(modules
, key
, Py_None
);
475 /* Next, delete all modules (still skipping __builtin__ and sys) */
477 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
478 if (PyString_Check(key
) && PyModule_Check(value
)) {
479 name
= PyString_AS_STRING(key
);
480 if (strcmp(name
, "__builtin__") == 0)
482 if (strcmp(name
, "sys") == 0)
485 PySys_WriteStderr("# cleanup[2] %s\n", name
);
486 _PyModule_Clear(value
);
487 PyDict_SetItem(modules
, key
, Py_None
);
491 /* Next, delete sys and __builtin__ (in that order) */
492 value
= PyDict_GetItemString(modules
, "sys");
493 if (value
!= NULL
&& PyModule_Check(value
)) {
495 PySys_WriteStderr("# cleanup sys\n");
496 _PyModule_Clear(value
);
497 PyDict_SetItemString(modules
, "sys", Py_None
);
499 value
= PyDict_GetItemString(modules
, "__builtin__");
500 if (value
!= NULL
&& PyModule_Check(value
)) {
502 PySys_WriteStderr("# cleanup __builtin__\n");
503 _PyModule_Clear(value
);
504 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
507 /* Finally, clear and delete the modules directory */
508 PyDict_Clear(modules
);
509 interp
->modules
= NULL
;
511 Py_CLEAR(interp
->modules_reloading
);
515 /* Helper for pythonrun.c -- return magic number */
518 PyImport_GetMagicNumber(void)
524 /* Magic for extension modules (built-in as well as dynamically
525 loaded). To prevent initializing an extension module more than
526 once, we keep a static dictionary 'extensions' keyed by module name
527 (for built-in modules) or by filename (for dynamically loaded
528 modules), containing these modules. A copy of the module's
529 dictionary is stored by calling _PyImport_FixupExtension()
530 immediately after the module initialization function succeeds. A
531 copy can be retrieved from there by calling
532 _PyImport_FindExtension(). */
535 _PyImport_FixupExtension(char *name
, char *filename
)
537 PyObject
*modules
, *mod
, *dict
, *copy
;
538 if (extensions
== NULL
) {
539 extensions
= PyDict_New();
540 if (extensions
== NULL
)
543 modules
= PyImport_GetModuleDict();
544 mod
= PyDict_GetItemString(modules
, name
);
545 if (mod
== NULL
|| !PyModule_Check(mod
)) {
546 PyErr_Format(PyExc_SystemError
,
547 "_PyImport_FixupExtension: module %.200s not loaded", name
);
550 dict
= PyModule_GetDict(mod
);
553 copy
= PyDict_Copy(dict
);
556 PyDict_SetItemString(extensions
, filename
, copy
);
562 _PyImport_FindExtension(char *name
, char *filename
)
564 PyObject
*dict
, *mod
, *mdict
;
565 if (extensions
== NULL
)
567 dict
= PyDict_GetItemString(extensions
, filename
);
570 mod
= PyImport_AddModule(name
);
573 mdict
= PyModule_GetDict(mod
);
576 if (PyDict_Update(mdict
, dict
))
579 PySys_WriteStderr("import %s # previously loaded (%s)\n",
585 /* Get the module object corresponding to a module name.
586 First check the modules dictionary if there's one there,
587 if not, create a new one and insert it in the modules dictionary.
588 Because the former action is most common, THIS DOES NOT RETURN A
592 PyImport_AddModule(const char *name
)
594 PyObject
*modules
= PyImport_GetModuleDict();
597 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
600 m
= PyModule_New(name
);
603 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
607 Py_DECREF(m
); /* Yes, it still exists, in modules! */
612 /* Remove name from sys.modules, if it's there. */
614 _RemoveModule(const char *name
)
616 PyObject
*modules
= PyImport_GetModuleDict();
617 if (PyDict_GetItemString(modules
, name
) == NULL
)
619 if (PyDict_DelItemString(modules
, name
) < 0)
620 Py_FatalError("import: deleting existing key in"
621 "sys.modules failed");
624 /* Execute a code object in a module and return the module object
625 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
626 * removed from sys.modules, to avoid leaving damaged module objects
627 * in sys.modules. The caller may wish to restore the original
628 * module object (if any) in this case; PyImport_ReloadModule is an
632 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
634 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
638 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
640 PyObject
*modules
= PyImport_GetModuleDict();
643 m
= PyImport_AddModule(name
);
646 /* If the module is being reloaded, we get the old module back
647 and re-use its dict to exec the new code. */
648 d
= PyModule_GetDict(m
);
649 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
650 if (PyDict_SetItemString(d
, "__builtins__",
651 PyEval_GetBuiltins()) != 0)
654 /* Remember the filename as the __file__ attribute */
656 if (pathname
!= NULL
) {
657 v
= PyString_FromString(pathname
);
662 v
= ((PyCodeObject
*)co
)->co_filename
;
665 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
666 PyErr_Clear(); /* Not important enough to report */
669 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
674 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
675 PyErr_Format(PyExc_ImportError
,
676 "Loaded module %.200s not found in sys.modules",
691 /* Given a pathname for a Python source file, fill a buffer with the
692 pathname for the corresponding compiled file. Return the pathname
693 for the compiled file, or NULL if there's no space in the buffer.
694 Doesn't set an exception. */
697 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
699 size_t len
= strlen(pathname
);
704 /* Treat .pyw as if it were .py. The case of ".pyw" must match
705 that used in _PyImport_StandardFiletab. */
706 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
707 --len
; /* pretend 'w' isn't there */
709 memcpy(buf
, pathname
, len
);
710 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
717 /* Given a pathname for a Python source file, its time of last
718 modification, and a pathname for a compiled file, check whether the
719 compiled file represents the same version of the source. If so,
720 return a FILE pointer for the compiled file, positioned just after
721 the header; if not, return NULL.
722 Doesn't set an exception. */
725 check_compiled_module(char *pathname
, time_t mtime
, char *cpathname
)
731 fp
= fopen(cpathname
, "rb");
734 magic
= PyMarshal_ReadLongFromFile(fp
);
735 if (magic
!= pyc_magic
) {
737 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
741 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
742 if (pyc_mtime
!= mtime
) {
744 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
749 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
754 /* Read a code object from a file and check it for validity */
756 static PyCodeObject
*
757 read_compiled_module(char *cpathname
, FILE *fp
)
761 co
= PyMarshal_ReadLastObjectFromFile(fp
);
764 if (!PyCode_Check(co
)) {
765 PyErr_Format(PyExc_ImportError
,
766 "Non-code object in %.200s", cpathname
);
770 return (PyCodeObject
*)co
;
774 /* Load a module from a compiled file, execute it, and return its
775 module object WITH INCREMENTED REFERENCE COUNT */
778 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
784 magic
= PyMarshal_ReadLongFromFile(fp
);
785 if (magic
!= pyc_magic
) {
786 PyErr_Format(PyExc_ImportError
,
787 "Bad magic number in %.200s", cpathname
);
790 (void) PyMarshal_ReadLongFromFile(fp
);
791 co
= read_compiled_module(cpathname
, fp
);
795 PySys_WriteStderr("import %s # precompiled from %s\n",
797 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
803 /* Parse a source file and return the corresponding code object */
805 static PyCodeObject
*
806 parse_source_module(const char *pathname
, FILE *fp
)
808 PyCodeObject
*co
= NULL
;
810 PyArena
*arena
= PyArena_New();
814 mod
= PyParser_ASTFromFile(fp
, pathname
, Py_file_input
, 0, 0, 0,
817 co
= PyAST_Compile(mod
, pathname
, NULL
, arena
);
824 /* Helper to open a bytecode file for writing in exclusive mode */
827 open_exclusive(char *filename
)
829 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
830 /* Use O_EXCL to avoid a race condition when another process tries to
831 write the same file. When that happens, our open() call fails,
832 which is just fine (since it's only a cache).
833 XXX If the file exists and is writable but the directory is not
834 writable, the file will never be written. Oh well.
837 (void) unlink(filename
);
838 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
840 |O_BINARY
/* necessary for Windows */
843 , 0666, "ctxt=bin", "shr=nil"
850 return fdopen(fd
, "wb");
852 /* Best we can do -- on Windows this can't happen anyway */
853 return fopen(filename
, "wb");
858 /* Write a compiled module to a file, placing the time of last
859 modification of its source into the header.
860 Errors are ignored, if a write error occurs an attempt is made to
864 write_compiled_module(PyCodeObject
*co
, char *cpathname
, time_t mtime
)
868 fp
= open_exclusive(cpathname
);
872 "# can't create %s\n", cpathname
);
875 PyMarshal_WriteLongToFile(pyc_magic
, fp
, Py_MARSHAL_VERSION
);
876 /* First write a 0 for mtime */
877 PyMarshal_WriteLongToFile(0L, fp
, Py_MARSHAL_VERSION
);
878 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
, Py_MARSHAL_VERSION
);
879 if (fflush(fp
) != 0 || ferror(fp
)) {
881 PySys_WriteStderr("# can't write %s\n", cpathname
);
882 /* Don't keep partial file */
884 (void) unlink(cpathname
);
887 /* Now write the true mtime */
889 assert(mtime
< LONG_MAX
);
890 PyMarshal_WriteLongToFile((long)mtime
, fp
, Py_MARSHAL_VERSION
);
894 PySys_WriteStderr("# wrote %s\n", cpathname
);
898 /* Load a source module from a given file and return its module
899 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
900 byte-compiled file, use that instead. */
903 load_source_module(char *name
, char *pathname
, FILE *fp
)
907 char buf
[MAXPATHLEN
+1];
912 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
913 if (mtime
== (time_t)(-1)) {
914 PyErr_Format(PyExc_RuntimeError
,
915 "unable to get modification time from '%s'",
919 #if SIZEOF_TIME_T > 4
920 /* Python's .pyc timestamp handling presumes that the timestamp fits
921 in 4 bytes. This will be fine until sometime in the year 2038,
922 when a 4-byte signed time_t will overflow.
925 PyErr_SetString(PyExc_OverflowError
,
926 "modification time overflows a 4 byte field");
930 cpathname
= make_compiled_pathname(pathname
, buf
,
931 (size_t)MAXPATHLEN
+ 1);
932 if (cpathname
!= NULL
&&
933 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
934 co
= read_compiled_module(cpathname
, fpc
);
939 PySys_WriteStderr("import %s # precompiled from %s\n",
941 pathname
= cpathname
;
944 co
= parse_source_module(pathname
, fp
);
948 PySys_WriteStderr("import %s # from %s\n",
951 write_compiled_module(co
, cpathname
, mtime
);
953 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
961 static PyObject
*load_module(char *, FILE *, char *, int, PyObject
*);
962 static struct filedescr
*find_module(char *, char *, PyObject
*,
963 char *, size_t, FILE **, PyObject
**);
964 static struct _frozen
*find_frozen(char *name
);
966 /* Load a package and return its module object WITH INCREMENTED
970 load_package(char *name
, char *pathname
)
973 PyObject
*file
= NULL
;
974 PyObject
*path
= NULL
;
976 char buf
[MAXPATHLEN
+1];
978 struct filedescr
*fdp
;
980 m
= PyImport_AddModule(name
);
984 PySys_WriteStderr("import %s # directory %s\n",
986 d
= PyModule_GetDict(m
);
987 file
= PyString_FromString(pathname
);
990 path
= Py_BuildValue("[O]", file
);
993 err
= PyDict_SetItemString(d
, "__file__", file
);
995 err
= PyDict_SetItemString(d
, "__path__", path
);
999 fdp
= find_module(name
, "__init__", path
, buf
, sizeof(buf
), &fp
, NULL
);
1001 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1009 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
1023 /* Helper to test for built-in module */
1026 is_builtin(char *name
)
1029 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
1030 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
1031 if (PyImport_Inittab
[i
].initfunc
== NULL
)
1041 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1042 possibly by fetching it from the path_importer_cache dict. If it
1043 wasn't yet cached, traverse path_hooks until a hook is found
1044 that can handle the path item. Return None if no hook could;
1045 this tells our caller it should fall back to the builtin
1046 import mechanism. Cache the result in path_importer_cache.
1047 Returns a borrowed reference. */
1050 get_path_importer(PyObject
*path_importer_cache
, PyObject
*path_hooks
,
1054 Py_ssize_t j
, nhooks
;
1056 /* These conditions are the caller's responsibility: */
1057 assert(PyList_Check(path_hooks
));
1058 assert(PyDict_Check(path_importer_cache
));
1060 nhooks
= PyList_Size(path_hooks
);
1062 return NULL
; /* Shouldn't happen */
1064 importer
= PyDict_GetItem(path_importer_cache
, p
);
1065 if (importer
!= NULL
)
1068 /* set path_importer_cache[p] to None to avoid recursion */
1069 if (PyDict_SetItem(path_importer_cache
, p
, Py_None
) != 0)
1072 for (j
= 0; j
< nhooks
; j
++) {
1073 PyObject
*hook
= PyList_GetItem(path_hooks
, j
);
1076 importer
= PyObject_CallFunctionObjArgs(hook
, p
, NULL
);
1077 if (importer
!= NULL
)
1080 if (!PyErr_ExceptionMatches(PyExc_ImportError
)) {
1085 if (importer
== NULL
) {
1086 importer
= PyObject_CallFunctionObjArgs(
1087 (PyObject
*)&NullImporterType
, p
, NULL
1089 if (importer
== NULL
) {
1090 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
1096 if (importer
!= NULL
) {
1097 int err
= PyDict_SetItem(path_importer_cache
, p
, importer
);
1098 Py_DECREF(importer
);
1105 /* Search the path (default sys.path) for a module. Return the
1106 corresponding filedescr struct, and (via return arguments) the
1107 pathname and an open file. Return NULL if the module is not found. */
1110 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
1111 char *, Py_ssize_t
);
1114 static int case_ok(char *, Py_ssize_t
, Py_ssize_t
, char *);
1115 static int find_init_module(char *); /* Forward */
1116 static struct filedescr importhookdescr
= {"", "", IMP_HOOK
};
1118 static struct filedescr
*
1119 find_module(char *fullname
, char *subname
, PyObject
*path
, char *buf
,
1120 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1122 Py_ssize_t i
, npath
;
1123 size_t len
, namelen
;
1124 struct filedescr
*fdp
= NULL
;
1127 PyObject
*path_hooks
, *path_importer_cache
;
1129 struct stat statbuf
;
1131 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
1132 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
1133 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
1134 char name
[MAXPATHLEN
+1];
1135 #if defined(PYOS_OS2)
1137 size_t saved_namelen
;
1138 char *saved_buf
= NULL
;
1140 if (p_loader
!= NULL
)
1143 if (strlen(subname
) > MAXPATHLEN
) {
1144 PyErr_SetString(PyExc_OverflowError
,
1145 "module name is too long");
1148 strcpy(name
, subname
);
1150 /* sys.meta_path import hook */
1151 if (p_loader
!= NULL
) {
1152 PyObject
*meta_path
;
1154 meta_path
= PySys_GetObject("meta_path");
1155 if (meta_path
== NULL
|| !PyList_Check(meta_path
)) {
1156 PyErr_SetString(PyExc_ImportError
,
1157 "sys.meta_path must be a list of "
1161 Py_INCREF(meta_path
); /* zap guard */
1162 npath
= PyList_Size(meta_path
);
1163 for (i
= 0; i
< npath
; i
++) {
1165 PyObject
*hook
= PyList_GetItem(meta_path
, i
);
1166 loader
= PyObject_CallMethod(hook
, "find_module",
1170 if (loader
== NULL
) {
1171 Py_DECREF(meta_path
);
1172 return NULL
; /* true error */
1174 if (loader
!= Py_None
) {
1175 /* a loader was found */
1177 Py_DECREF(meta_path
);
1178 return &importhookdescr
;
1182 Py_DECREF(meta_path
);
1185 if (path
!= NULL
&& PyString_Check(path
)) {
1186 /* The only type of submodule allowed inside a "frozen"
1187 package are other frozen modules or packages. */
1188 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
1189 PyErr_SetString(PyExc_ImportError
,
1190 "full frozen module name too long");
1193 strcpy(buf
, PyString_AsString(path
));
1197 if (find_frozen(name
) != NULL
) {
1201 PyErr_Format(PyExc_ImportError
,
1202 "No frozen submodule named %.200s", name
);
1206 if (is_builtin(name
)) {
1210 if ((find_frozen(name
)) != NULL
) {
1216 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
1222 path
= PySys_GetObject("path");
1224 if (path
== NULL
|| !PyList_Check(path
)) {
1225 PyErr_SetString(PyExc_ImportError
,
1226 "sys.path must be a list of directory names");
1230 path_hooks
= PySys_GetObject("path_hooks");
1231 if (path_hooks
== NULL
|| !PyList_Check(path_hooks
)) {
1232 PyErr_SetString(PyExc_ImportError
,
1233 "sys.path_hooks must be a list of "
1237 path_importer_cache
= PySys_GetObject("path_importer_cache");
1238 if (path_importer_cache
== NULL
||
1239 !PyDict_Check(path_importer_cache
)) {
1240 PyErr_SetString(PyExc_ImportError
,
1241 "sys.path_importer_cache must be a dict");
1245 npath
= PyList_Size(path
);
1246 namelen
= strlen(name
);
1247 for (i
= 0; i
< npath
; i
++) {
1248 PyObject
*copy
= NULL
;
1249 PyObject
*v
= PyList_GetItem(path
, i
);
1252 #ifdef Py_USING_UNICODE
1253 if (PyUnicode_Check(v
)) {
1254 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
1255 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
1262 if (!PyString_Check(v
))
1264 len
= PyString_GET_SIZE(v
);
1265 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
1267 continue; /* Too long */
1269 strcpy(buf
, PyString_AS_STRING(v
));
1270 if (strlen(buf
) != len
) {
1272 continue; /* v contains '\0' */
1275 /* sys.path_hooks import hook */
1276 if (p_loader
!= NULL
) {
1279 importer
= get_path_importer(path_importer_cache
,
1281 if (importer
== NULL
) {
1285 /* Note: importer is a borrowed reference */
1286 if (importer
!= Py_None
) {
1288 loader
= PyObject_CallMethod(importer
,
1293 return NULL
; /* error */
1294 if (loader
!= Py_None
) {
1295 /* a loader was found */
1297 return &importhookdescr
;
1303 /* no hook was found, use builtin import */
1305 if (len
> 0 && buf
[len
-1] != SEP
1307 && buf
[len
-1] != ALTSEP
1311 strcpy(buf
+len
, name
);
1314 /* Check for package import (buf holds a directory name,
1315 and there's an __init__ module in that directory */
1317 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1318 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1319 case_ok(buf
, len
, namelen
, name
)) { /* case matches */
1320 if (find_init_module(buf
)) { /* and has __init__.py */
1325 char warnstr
[MAXPATHLEN
+80];
1326 sprintf(warnstr
, "Not importing directory "
1327 "'%.*s': missing __init__.py",
1329 if (PyErr_Warn(PyExc_ImportWarning
,
1337 /* XXX How are you going to test for directories? */
1340 case_ok(buf
, len
, namelen
, name
)) {
1341 if (find_init_module(buf
)) {
1346 char warnstr
[MAXPATHLEN
+80];
1347 sprintf(warnstr
, "Not importing directory "
1348 "'%.*s': missing __init__.py",
1350 if (PyErr_Warn(PyExc_ImportWarning
,
1358 #if defined(PYOS_OS2)
1359 /* take a snapshot of the module spec for restoration
1360 * after the 8 character DLL hackery
1362 saved_buf
= strdup(buf
);
1364 saved_namelen
= namelen
;
1365 #endif /* PYOS_OS2 */
1366 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1367 #if defined(PYOS_OS2)
1368 /* OS/2 limits DLLs to 8 character names (w/o
1370 * so if the name is longer than that and its a
1371 * dynamically loaded module we're going to try,
1372 * truncate the name before trying
1374 if (strlen(subname
) > 8) {
1375 /* is this an attempt to load a C extension? */
1376 const struct filedescr
*scan
;
1377 scan
= _PyImport_DynLoadFiletab
;
1378 while (scan
->suffix
!= NULL
) {
1379 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1384 if (scan
->suffix
!= NULL
) {
1385 /* yes, so truncate the name */
1387 len
-= strlen(subname
) - namelen
;
1391 #endif /* PYOS_OS2 */
1392 strcpy(buf
+len
, fdp
->suffix
);
1393 if (Py_VerboseFlag
> 1)
1394 PySys_WriteStderr("# trying %s\n", buf
);
1395 filemode
= fdp
->mode
;
1396 if (filemode
[0] == 'U')
1397 filemode
= "r" PY_STDIOTEXTMODE
;
1398 fp
= fopen(buf
, filemode
);
1400 if (case_ok(buf
, len
, namelen
, name
))
1402 else { /* continue search */
1407 #if defined(PYOS_OS2)
1408 /* restore the saved snapshot */
1409 strcpy(buf
, saved_buf
);
1411 namelen
= saved_namelen
;
1414 #if defined(PYOS_OS2)
1415 /* don't need/want the module name snapshot anymore */
1427 PyErr_Format(PyExc_ImportError
,
1428 "No module named %.200s", name
);
1435 /* Helpers for main.c
1436 * Find the source file corresponding to a named module
1439 _PyImport_FindModule(const char *name
, PyObject
*path
, char *buf
,
1440 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1442 return find_module((char *) name
, (char *) name
, path
,
1443 buf
, buflen
, p_fp
, p_loader
);
1446 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr
* fd
)
1448 return fd
->type
== PY_SOURCE
|| fd
->type
== PY_COMPILED
;
1451 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1452 * The arguments here are tricky, best shown by example:
1453 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1455 * |--------------------- buf ---------------------|
1456 * |------------------- len ------------------|
1457 * |------ name -------|
1458 * |----- namelen -----|
1459 * buf is the full path, but len only counts up to (& exclusive of) the
1460 * extension. name is the module name, also exclusive of extension.
1462 * We've already done a successful stat() or fopen() on buf, so know that
1463 * there's some match, possibly case-insensitive.
1465 * case_ok() is to return 1 if there's a case-sensitive match for
1466 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1469 * case_ok() is used to implement case-sensitive import semantics even
1470 * on platforms with case-insensitive filesystems. It's trivial to implement
1471 * for case-sensitive filesystems. It's pretty much a cross-platform
1472 * nightmare for systems with case-insensitive filesystems.
1475 /* First we may need a pile of platform-specific header files; the sequence
1476 * of #if's here should match the sequence in the body of case_ok().
1478 #if defined(MS_WINDOWS)
1479 #include <windows.h>
1481 #elif defined(DJGPP)
1484 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1485 #include <sys/types.h>
1488 #elif defined(PYOS_OS2)
1490 #define INCL_DOSERRORS
1491 #define INCL_NOPMAPI
1494 #elif defined(RISCOS)
1495 #include "oslib/osfscontrol.h"
1499 case_ok(char *buf
, Py_ssize_t len
, Py_ssize_t namelen
, char *name
)
1501 /* Pick a platform-specific implementation; the sequence of #if's here should
1502 * match the sequence just above.
1506 #if defined(MS_WINDOWS)
1507 WIN32_FIND_DATA data
;
1510 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1513 h
= FindFirstFile(buf
, &data
);
1514 if (h
== INVALID_HANDLE_VALUE
) {
1515 PyErr_Format(PyExc_NameError
,
1516 "Can't find file for module %.100s\n(filename %.300s)",
1521 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1524 #elif defined(DJGPP)
1528 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1531 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1533 PyErr_Format(PyExc_NameError
,
1534 "Can't find file for module %.100s\n(filename %.300s)",
1538 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1540 /* new-fangled macintosh (macosx) or Cygwin */
1541 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1544 char dirname
[MAXPATHLEN
+ 1];
1545 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1547 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1550 /* Copy the dir component into dirname; substitute "." if empty */
1556 assert(dirlen
<= MAXPATHLEN
);
1557 memcpy(dirname
, buf
, dirlen
);
1558 dirname
[dirlen
] = '\0';
1560 /* Open the directory and search the entries for an exact match. */
1561 dirp
= opendir(dirname
);
1563 char *nameWithExt
= buf
+ len
- namelen
;
1564 while ((dp
= readdir(dirp
)) != NULL
) {
1566 #ifdef _DIRENT_HAVE_D_NAMELEN
1571 if (thislen
>= namelen
&&
1572 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1573 (void)closedir(dirp
);
1574 return 1; /* Found */
1577 (void)closedir(dirp
);
1579 return 0 ; /* Not found */
1582 #elif defined(RISCOS)
1583 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1584 char buf2
[MAXPATHLEN
+2];
1585 char *nameWithExt
= buf
+len
-namelen
;
1589 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1593 append wildcard, otherwise case of filename wouldn't be touched */
1597 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1598 canonlen
= MAXPATHLEN
+1-canonlen
;
1599 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1601 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1602 return 1; /* match */
1607 #elif defined(PYOS_OS2)
1613 if (getenv("PYTHONCASEOK") != NULL
)
1616 rc
= DosFindFirst(buf
,
1618 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1619 &ffbuf
, sizeof(ffbuf
),
1624 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1626 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1635 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1637 find_init_module(char *buf
)
1639 const size_t save_len
= strlen(buf
);
1640 size_t i
= save_len
;
1641 char *pname
; /* pointer to start of __init__ */
1642 struct stat statbuf
;
1644 /* For calling case_ok(buf, len, namelen, name):
1645 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1647 * |--------------------- buf ---------------------|
1648 * |------------------- len ------------------|
1649 * |------ name -------|
1650 * |----- namelen -----|
1652 if (save_len
+ 13 >= MAXPATHLEN
)
1656 strcpy(pname
, "__init__.py");
1657 if (stat(buf
, &statbuf
) == 0) {
1659 save_len
+ 9, /* len("/__init__") */
1660 8, /* len("__init__") */
1662 buf
[save_len
] = '\0';
1667 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1668 if (stat(buf
, &statbuf
) == 0) {
1670 save_len
+ 9, /* len("/__init__") */
1671 8, /* len("__init__") */
1673 buf
[save_len
] = '\0';
1677 buf
[save_len
] = '\0';
1685 find_init_module(buf
)
1688 int save_len
= strlen(buf
);
1691 if (save_len
+ 13 >= MAXPATHLEN
)
1694 strcpy(buf
+i
, "__init__/py");
1696 buf
[save_len
] = '\0';
1700 if (Py_OptimizeFlag
)
1705 buf
[save_len
] = '\0';
1708 buf
[save_len
] = '\0';
1713 #endif /* HAVE_STAT */
1716 static int init_builtin(char *); /* Forward */
1718 /* Load an external module using the default search path and return
1719 its module object WITH INCREMENTED REFERENCE COUNT */
1722 load_module(char *name
, FILE *fp
, char *buf
, int type
, PyObject
*loader
)
1728 /* First check that there's an open file (if we need one) */
1733 PyErr_Format(PyExc_ValueError
,
1734 "file object required for import (type code %d)",
1743 m
= load_source_module(name
, buf
, fp
);
1747 m
= load_compiled_module(name
, buf
, fp
);
1750 #ifdef HAVE_DYNAMIC_LOADING
1752 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1757 m
= load_package(name
, buf
);
1762 if (buf
!= NULL
&& buf
[0] != '\0')
1764 if (type
== C_BUILTIN
)
1765 err
= init_builtin(name
);
1767 err
= PyImport_ImportFrozenModule(name
);
1771 PyErr_Format(PyExc_ImportError
,
1772 "Purported %s module %.200s not found",
1774 "builtin" : "frozen",
1778 modules
= PyImport_GetModuleDict();
1779 m
= PyDict_GetItemString(modules
, name
);
1783 "%s module %.200s not properly initialized",
1785 "builtin" : "frozen",
1793 if (loader
== NULL
) {
1794 PyErr_SetString(PyExc_ImportError
,
1795 "import hook without loader");
1798 m
= PyObject_CallMethod(loader
, "load_module", "s", name
);
1803 PyErr_Format(PyExc_ImportError
,
1804 "Don't know how to import %.200s (type code %d)",
1814 /* Initialize a built-in module.
1815 Return 1 for success, 0 if the module is not found, and -1 with
1816 an exception set if the initialization failed. */
1819 init_builtin(char *name
)
1823 if (_PyImport_FindExtension(name
, name
) != NULL
)
1826 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1827 if (strcmp(name
, p
->name
) == 0) {
1828 if (p
->initfunc
== NULL
) {
1829 PyErr_Format(PyExc_ImportError
,
1830 "Cannot re-init internal module %.200s",
1835 PySys_WriteStderr("import %s # builtin\n", name
);
1837 if (PyErr_Occurred())
1839 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1848 /* Frozen modules */
1850 static struct _frozen
*
1851 find_frozen(char *name
)
1855 for (p
= PyImport_FrozenModules
; ; p
++) {
1856 if (p
->name
== NULL
)
1858 if (strcmp(p
->name
, name
) == 0)
1865 get_frozen_object(char *name
)
1867 struct _frozen
*p
= find_frozen(name
);
1871 PyErr_Format(PyExc_ImportError
,
1872 "No such frozen object named %.200s",
1876 if (p
->code
== NULL
) {
1877 PyErr_Format(PyExc_ImportError
,
1878 "Excluded frozen object named %.200s",
1885 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1888 /* Initialize a frozen module.
1889 Return 1 for succes, 0 if the module is not found, and -1 with
1890 an exception set if the initialization failed.
1891 This function is also used from frozenmain.c */
1894 PyImport_ImportFrozenModule(char *name
)
1896 struct _frozen
*p
= find_frozen(name
);
1904 if (p
->code
== NULL
) {
1905 PyErr_Format(PyExc_ImportError
,
1906 "Excluded frozen object named %.200s",
1911 ispackage
= (size
< 0);
1915 PySys_WriteStderr("import %s # frozen%s\n",
1916 name
, ispackage
? " package" : "");
1917 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1920 if (!PyCode_Check(co
)) {
1921 PyErr_Format(PyExc_TypeError
,
1922 "frozen object %.200s is not a code object",
1927 /* Set __path__ to the package name */
1930 m
= PyImport_AddModule(name
);
1933 d
= PyModule_GetDict(m
);
1934 s
= PyString_InternFromString(name
);
1937 err
= PyDict_SetItemString(d
, "__path__", s
);
1942 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1954 /* Import a module, either built-in, frozen, or external, and return
1955 its module object WITH INCREMENTED REFERENCE COUNT */
1958 PyImport_ImportModule(const char *name
)
1963 pname
= PyString_FromString(name
);
1966 result
= PyImport_Import(pname
);
1971 /* Forward declarations for helper routines */
1972 static PyObject
*get_parent(PyObject
*globals
, char *buf
,
1973 Py_ssize_t
*p_buflen
, int level
);
1974 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1975 char **p_name
, char *buf
, Py_ssize_t
*p_buflen
);
1976 static int mark_miss(char *name
);
1977 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1978 char *buf
, Py_ssize_t buflen
, int recursive
);
1979 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1981 /* The Magnum Opus of dotted-name import :-) */
1984 import_module_level(char *name
, PyObject
*globals
, PyObject
*locals
,
1985 PyObject
*fromlist
, int level
)
1987 char buf
[MAXPATHLEN
+1];
1988 Py_ssize_t buflen
= 0;
1989 PyObject
*parent
, *head
, *next
, *tail
;
1991 parent
= get_parent(globals
, buf
, &buflen
, level
);
1995 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
2002 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
2010 if (tail
== Py_None
) {
2011 /* If tail is Py_None, both get_parent and load_next found
2012 an empty module name: someone called __import__("") or
2013 doctored faulty bytecode */
2016 PyErr_SetString(PyExc_ValueError
,
2017 "Empty module name");
2021 if (fromlist
!= NULL
) {
2022 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
2026 if (fromlist
== NULL
) {
2032 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
2040 /* For DLL compatibility */
2041 #undef PyImport_ImportModuleEx
2043 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
2048 result
= import_module_level(name
, globals
, locals
, fromlist
, -1);
2049 if (unlock_import() < 0) {
2051 PyErr_SetString(PyExc_RuntimeError
,
2052 "not holding the import lock");
2057 #define PyImport_ImportModuleEx(n, g, l, f) \
2058 PyImport_ImportModuleLevel(n, g, l, f, -1);
2061 PyImport_ImportModuleLevel(char *name
, PyObject
*globals
, PyObject
*locals
,
2062 PyObject
*fromlist
, int level
)
2066 result
= import_module_level(name
, globals
, locals
, fromlist
, level
);
2067 if (unlock_import() < 0) {
2069 PyErr_SetString(PyExc_RuntimeError
,
2070 "not holding the import lock");
2076 /* Return the package that an import is being performed in. If globals comes
2077 from the module foo.bar.bat (not itself a package), this returns the
2078 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2079 the package's entry in sys.modules is returned, as a borrowed reference.
2081 The *name* of the returned package is returned in buf, with the length of
2082 the name in *p_buflen.
2084 If globals doesn't come from a package or a module in a package, or a
2085 corresponding entry is not found in sys.modules, Py_None is returned.
2088 get_parent(PyObject
*globals
, char *buf
, Py_ssize_t
*p_buflen
, int level
)
2090 static PyObject
*namestr
= NULL
;
2091 static PyObject
*pathstr
= NULL
;
2092 PyObject
*modname
, *modpath
, *modules
, *parent
;
2094 if (globals
== NULL
|| !PyDict_Check(globals
) || !level
)
2097 if (namestr
== NULL
) {
2098 namestr
= PyString_InternFromString("__name__");
2099 if (namestr
== NULL
)
2102 if (pathstr
== NULL
) {
2103 pathstr
= PyString_InternFromString("__path__");
2104 if (pathstr
== NULL
)
2110 modname
= PyDict_GetItem(globals
, namestr
);
2111 if (modname
== NULL
|| !PyString_Check(modname
))
2114 modpath
= PyDict_GetItem(globals
, pathstr
);
2115 if (modpath
!= NULL
) {
2116 Py_ssize_t len
= PyString_GET_SIZE(modname
);
2117 if (len
> MAXPATHLEN
) {
2118 PyErr_SetString(PyExc_ValueError
,
2119 "Module name too long");
2122 strcpy(buf
, PyString_AS_STRING(modname
));
2125 char *start
= PyString_AS_STRING(modname
);
2126 char *lastdot
= strrchr(start
, '.');
2128 if (lastdot
== NULL
&& level
> 0) {
2129 PyErr_SetString(PyExc_ValueError
,
2130 "Attempted relative import in non-package");
2133 if (lastdot
== NULL
)
2135 len
= lastdot
- start
;
2136 if (len
>= MAXPATHLEN
) {
2137 PyErr_SetString(PyExc_ValueError
,
2138 "Module name too long");
2141 strncpy(buf
, start
, len
);
2145 while (--level
> 0) {
2146 char *dot
= strrchr(buf
, '.');
2148 PyErr_SetString(PyExc_ValueError
,
2149 "Attempted relative import beyond "
2150 "toplevel package");
2155 *p_buflen
= strlen(buf
);
2157 modules
= PyImport_GetModuleDict();
2158 parent
= PyDict_GetItemString(modules
, buf
);
2160 PyErr_Format(PyExc_SystemError
,
2161 "Parent module '%.200s' not loaded", buf
);
2163 /* We expect, but can't guarantee, if parent != None, that:
2164 - parent.__name__ == buf
2165 - parent.__dict__ is globals
2166 If this is violated... Who cares? */
2169 /* altmod is either None or same as mod */
2171 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
2172 Py_ssize_t
*p_buflen
)
2174 char *name
= *p_name
;
2175 char *dot
= strchr(name
, '.');
2180 if (strlen(name
) == 0) {
2181 /* completely empty module name should only happen in
2182 'from . import' (or '__import__("")')*/
2197 PyErr_SetString(PyExc_ValueError
,
2198 "Empty module name");
2202 p
= buf
+ *p_buflen
;
2205 if (p
+len
-buf
>= MAXPATHLEN
) {
2206 PyErr_SetString(PyExc_ValueError
,
2207 "Module name too long");
2210 strncpy(p
, name
, len
);
2212 *p_buflen
= p
+len
-buf
;
2214 result
= import_submodule(mod
, p
, buf
);
2215 if (result
== Py_None
&& altmod
!= mod
) {
2217 /* Here, altmod must be None and mod must not be None */
2218 result
= import_submodule(altmod
, p
, p
);
2219 if (result
!= NULL
&& result
!= Py_None
) {
2220 if (mark_miss(buf
) != 0) {
2224 strncpy(buf
, name
, len
);
2232 if (result
== Py_None
) {
2234 PyErr_Format(PyExc_ImportError
,
2235 "No module named %.200s", name
);
2243 mark_miss(char *name
)
2245 PyObject
*modules
= PyImport_GetModuleDict();
2246 return PyDict_SetItemString(modules
, name
, Py_None
);
2250 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, Py_ssize_t buflen
,
2255 if (!PyObject_HasAttrString(mod
, "__path__"))
2258 for (i
= 0; ; i
++) {
2259 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
2262 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2268 if (!PyString_Check(item
)) {
2269 PyErr_SetString(PyExc_TypeError
,
2270 "Item in ``from list'' not a string");
2274 if (PyString_AS_STRING(item
)[0] == '*') {
2277 /* See if the package defines __all__ */
2279 continue; /* Avoid endless recursion */
2280 all
= PyObject_GetAttrString(mod
, "__all__");
2284 int ret
= ensure_fromlist(mod
, all
, buf
, buflen
, 1);
2291 hasit
= PyObject_HasAttr(mod
, item
);
2293 char *subname
= PyString_AS_STRING(item
);
2296 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
2297 PyErr_SetString(PyExc_ValueError
,
2298 "Module name too long");
2305 submod
= import_submodule(mod
, subname
, buf
);
2307 if (submod
== NULL
) {
2319 add_submodule(PyObject
*mod
, PyObject
*submod
, char *fullname
, char *subname
,
2324 /* Irrespective of the success of this load, make a
2325 reference to it in the parent package module. A copy gets
2326 saved in the modules dictionary under the full name, so get a
2327 reference from there, if need be. (The exception is when the
2328 load failed with a SyntaxError -- then there's no trace in
2329 sys.modules. In that case, of course, do nothing extra.) */
2330 if (submod
== NULL
) {
2331 submod
= PyDict_GetItemString(modules
, fullname
);
2335 if (PyModule_Check(mod
)) {
2336 /* We can't use setattr here since it can give a
2337 * spurious warning if the submodule name shadows a
2339 PyObject
*dict
= PyModule_GetDict(mod
);
2342 if (PyDict_SetItemString(dict
, subname
, submod
) < 0)
2346 if (PyObject_SetAttrString(mod
, subname
, submod
) < 0)
2353 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
2355 PyObject
*modules
= PyImport_GetModuleDict();
2359 if mod == None: subname == fullname
2360 else: mod.__name__ + "." + subname == fullname
2363 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
2367 PyObject
*path
, *loader
= NULL
;
2368 char buf
[MAXPATHLEN
+1];
2369 struct filedescr
*fdp
;
2375 path
= PyObject_GetAttrString(mod
, "__path__");
2384 fdp
= find_module(fullname
, subname
, path
, buf
, MAXPATHLEN
+1,
2388 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2394 m
= load_module(fullname
, fp
, buf
, fdp
->type
, loader
);
2398 if (!add_submodule(mod
, m
, fullname
, subname
, modules
)) {
2408 /* Re-import a module of any kind and return its module object, WITH
2409 INCREMENTED REFERENCE COUNT */
2412 PyImport_ReloadModule(PyObject
*m
)
2414 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
2415 PyObject
*modules_reloading
= interp
->modules_reloading
;
2416 PyObject
*modules
= PyImport_GetModuleDict();
2417 PyObject
*path
= NULL
, *loader
= NULL
, *existing_m
= NULL
;
2418 char *name
, *subname
;
2419 char buf
[MAXPATHLEN
+1];
2420 struct filedescr
*fdp
;
2424 if (modules_reloading
== NULL
) {
2425 Py_FatalError("PyImport_ReloadModule: "
2426 "no modules_reloading dictionary!");
2430 if (m
== NULL
|| !PyModule_Check(m
)) {
2431 PyErr_SetString(PyExc_TypeError
,
2432 "reload() argument must be module");
2435 name
= PyModule_GetName(m
);
2438 if (m
!= PyDict_GetItemString(modules
, name
)) {
2439 PyErr_Format(PyExc_ImportError
,
2440 "reload(): module %.200s not in sys.modules",
2444 existing_m
= PyDict_GetItemString(modules_reloading
, name
);
2445 if (existing_m
!= NULL
) {
2446 /* Due to a recursive reload, this module is already
2448 Py_INCREF(existing_m
);
2451 if (PyDict_SetItemString(modules_reloading
, name
, m
) < 0)
2454 subname
= strrchr(name
, '.');
2455 if (subname
== NULL
)
2458 PyObject
*parentname
, *parent
;
2459 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2460 if (parentname
== NULL
) {
2461 imp_modules_reloading_clear();
2464 parent
= PyDict_GetItem(modules
, parentname
);
2465 if (parent
== NULL
) {
2466 PyErr_Format(PyExc_ImportError
,
2467 "reload(): parent %.200s not in sys.modules",
2468 PyString_AS_STRING(parentname
));
2469 Py_DECREF(parentname
);
2470 imp_modules_reloading_clear();
2473 Py_DECREF(parentname
);
2475 path
= PyObject_GetAttrString(parent
, "__path__");
2480 fdp
= find_module(name
, subname
, path
, buf
, MAXPATHLEN
+1, &fp
, &loader
);
2485 imp_modules_reloading_clear();
2489 newm
= load_module(name
, fp
, buf
, fdp
->type
, loader
);
2495 /* load_module probably removed name from modules because of
2496 * the error. Put back the original module object. We're
2497 * going to return NULL in this case regardless of whether
2498 * replacing name succeeds, so the return value is ignored.
2500 PyDict_SetItemString(modules
, name
, m
);
2502 imp_modules_reloading_clear();
2507 /* Higher-level import emulator which emulates the "import" statement
2508 more accurately -- it invokes the __import__() function from the
2509 builtins of the current globals. This means that the import is
2510 done using whatever import hooks are installed in the current
2511 environment, e.g. by "rexec".
2512 A dummy list ["__doc__"] is passed as the 4th argument so that
2513 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2514 will return <module "gencache"> instead of <module "win32com">. */
2517 PyImport_Import(PyObject
*module_name
)
2519 static PyObject
*silly_list
= NULL
;
2520 static PyObject
*builtins_str
= NULL
;
2521 static PyObject
*import_str
= NULL
;
2522 PyObject
*globals
= NULL
;
2523 PyObject
*import
= NULL
;
2524 PyObject
*builtins
= NULL
;
2527 /* Initialize constant string objects */
2528 if (silly_list
== NULL
) {
2529 import_str
= PyString_InternFromString("__import__");
2530 if (import_str
== NULL
)
2532 builtins_str
= PyString_InternFromString("__builtins__");
2533 if (builtins_str
== NULL
)
2535 silly_list
= Py_BuildValue("[s]", "__doc__");
2536 if (silly_list
== NULL
)
2540 /* Get the builtins from current globals */
2541 globals
= PyEval_GetGlobals();
2542 if (globals
!= NULL
) {
2544 builtins
= PyObject_GetItem(globals
, builtins_str
);
2545 if (builtins
== NULL
)
2549 /* No globals -- use standard builtins, and fake globals */
2552 builtins
= PyImport_ImportModuleLevel("__builtin__",
2553 NULL
, NULL
, NULL
, 0);
2554 if (builtins
== NULL
)
2556 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2557 if (globals
== NULL
)
2561 /* Get the __import__ function from the builtins */
2562 if (PyDict_Check(builtins
)) {
2563 import
= PyObject_GetItem(builtins
, import_str
);
2565 PyErr_SetObject(PyExc_KeyError
, import_str
);
2568 import
= PyObject_GetAttr(builtins
, import_str
);
2572 /* Call the __import__ function with the proper argument list */
2573 r
= PyObject_CallFunctionObjArgs(import
, module_name
, globals
,
2574 globals
, silly_list
, NULL
);
2577 Py_XDECREF(globals
);
2578 Py_XDECREF(builtins
);
2585 /* Module 'imp' provides Python access to the primitives used for
2590 imp_get_magic(PyObject
*self
, PyObject
*noargs
)
2594 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2595 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2596 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2597 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2599 return PyString_FromStringAndSize(buf
, 4);
2603 imp_get_suffixes(PyObject
*self
, PyObject
*noargs
)
2606 struct filedescr
*fdp
;
2608 list
= PyList_New(0);
2611 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2612 PyObject
*item
= Py_BuildValue("ssi",
2613 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2618 if (PyList_Append(list
, item
) < 0) {
2629 call_find_module(char *name
, PyObject
*path
)
2631 extern int fclose(FILE *);
2632 PyObject
*fob
, *ret
;
2633 struct filedescr
*fdp
;
2634 char pathname
[MAXPATHLEN
+1];
2638 if (path
== Py_None
)
2640 fdp
= find_module(NULL
, name
, path
, pathname
, MAXPATHLEN
+1, &fp
, NULL
);
2644 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2654 ret
= Py_BuildValue("Os(ssi)",
2655 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2661 imp_find_module(PyObject
*self
, PyObject
*args
)
2664 PyObject
*path
= NULL
;
2665 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2667 return call_find_module(name
, path
);
2671 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2676 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2678 ret
= init_builtin(name
);
2685 m
= PyImport_AddModule(name
);
2691 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2696 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2698 ret
= PyImport_ImportFrozenModule(name
);
2705 m
= PyImport_AddModule(name
);
2711 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2715 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2717 return get_frozen_object(name
);
2721 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2724 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2726 return PyInt_FromLong(is_builtin(name
));
2730 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2734 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2736 p
= find_frozen(name
);
2737 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2741 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2746 mode
= "r" PY_STDIOTEXTMODE
;
2747 fp
= fopen(pathname
, mode
);
2749 PyErr_SetFromErrno(PyExc_IOError
);
2752 fp
= PyFile_AsFile(fob
);
2754 PyErr_SetString(PyExc_ValueError
,
2755 "bad/closed file object");
2761 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2765 PyObject
*fob
= NULL
;
2768 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2769 &PyFile_Type
, &fob
))
2771 fp
= get_file(pathname
, fob
, "rb");
2774 m
= load_compiled_module(name
, pathname
, fp
);
2780 #ifdef HAVE_DYNAMIC_LOADING
2783 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2787 PyObject
*fob
= NULL
;
2790 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2791 &PyFile_Type
, &fob
))
2794 fp
= get_file(pathname
, fob
, "r");
2798 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2802 #endif /* HAVE_DYNAMIC_LOADING */
2805 imp_load_source(PyObject
*self
, PyObject
*args
)
2809 PyObject
*fob
= NULL
;
2812 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2813 &PyFile_Type
, &fob
))
2815 fp
= get_file(pathname
, fob
, "r");
2818 m
= load_source_module(name
, pathname
, fp
);
2825 imp_load_module(PyObject
*self
, PyObject
*args
)
2830 char *suffix
; /* Unused */
2835 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2836 &name
, &fob
, &pathname
,
2837 &suffix
, &mode
, &type
))
2840 /* Mode must start with 'r' or 'U' and must not contain '+'.
2841 Implicit in this test is the assumption that the mode
2842 may contain other modifiers like 'b' or 't'. */
2844 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2845 PyErr_Format(PyExc_ValueError
,
2846 "invalid file open mode %.200s", mode
);
2853 if (!PyFile_Check(fob
)) {
2854 PyErr_SetString(PyExc_ValueError
,
2855 "load_module arg#2 should be a file or None");
2858 fp
= get_file(pathname
, fob
, mode
);
2862 return load_module(name
, fp
, pathname
, type
, NULL
);
2866 imp_load_package(PyObject
*self
, PyObject
*args
)
2870 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2872 return load_package(name
, pathname
);
2876 imp_new_module(PyObject
*self
, PyObject
*args
)
2879 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2881 return PyModule_New(name
);
2886 PyDoc_STRVAR(doc_imp
,
2887 "This module provides the components needed to build your own\n\
2888 __import__ function. Undocumented functions are obsolete.");
2890 PyDoc_STRVAR(doc_find_module
,
2891 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2892 Search for a module. If path is omitted or None, search for a\n\
2893 built-in, frozen or special module and continue search in sys.path.\n\
2894 The module name cannot contain '.'; to search for a submodule of a\n\
2895 package, pass the submodule name and the package's __path__.");
2897 PyDoc_STRVAR(doc_load_module
,
2898 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2899 Load a module, given information returned by find_module().\n\
2900 The module name must include the full package name, if any.");
2902 PyDoc_STRVAR(doc_get_magic
,
2903 "get_magic() -> string\n\
2904 Return the magic number for .pyc or .pyo files.");
2906 PyDoc_STRVAR(doc_get_suffixes
,
2907 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2908 Return a list of (suffix, mode, type) tuples describing the files\n\
2909 that find_module() looks for.");
2911 PyDoc_STRVAR(doc_new_module
,
2912 "new_module(name) -> module\n\
2913 Create a new module. Do not enter it in sys.modules.\n\
2914 The module name must include the full package name, if any.");
2916 PyDoc_STRVAR(doc_lock_held
,
2917 "lock_held() -> boolean\n\
2918 Return True if the import lock is currently held, else False.\n\
2919 On platforms without threads, return False.");
2921 PyDoc_STRVAR(doc_acquire_lock
,
2922 "acquire_lock() -> None\n\
2923 Acquires the interpreter's import lock for the current thread.\n\
2924 This lock should be used by import hooks to ensure thread-safety\n\
2925 when importing modules.\n\
2926 On platforms without threads, this function does nothing.");
2928 PyDoc_STRVAR(doc_release_lock
,
2929 "release_lock() -> None\n\
2930 Release the interpreter's import lock.\n\
2931 On platforms without threads, this function does nothing.");
2933 static PyMethodDef imp_methods
[] = {
2934 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
2935 {"get_magic", imp_get_magic
, METH_NOARGS
, doc_get_magic
},
2936 {"get_suffixes", imp_get_suffixes
, METH_NOARGS
, doc_get_suffixes
},
2937 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
2938 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
2939 {"lock_held", imp_lock_held
, METH_NOARGS
, doc_lock_held
},
2940 {"acquire_lock", imp_acquire_lock
, METH_NOARGS
, doc_acquire_lock
},
2941 {"release_lock", imp_release_lock
, METH_NOARGS
, doc_release_lock
},
2942 /* The rest are obsolete */
2943 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
2944 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
2945 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
2946 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
2947 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
2948 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
2949 #ifdef HAVE_DYNAMIC_LOADING
2950 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
2952 {"load_package", imp_load_package
, METH_VARARGS
},
2953 {"load_source", imp_load_source
, METH_VARARGS
},
2954 {NULL
, NULL
} /* sentinel */
2958 setint(PyObject
*d
, char *name
, int value
)
2963 v
= PyInt_FromLong((long)value
);
2964 err
= PyDict_SetItemString(d
, name
, v
);
2974 NullImporter_init(NullImporter
*self
, PyObject
*args
, PyObject
*kwds
)
2978 if (!_PyArg_NoKeywords("NullImporter()", kwds
))
2981 if (!PyArg_ParseTuple(args
, "s:NullImporter",
2985 if (strlen(path
) == 0) {
2986 PyErr_SetString(PyExc_ImportError
, "empty pathname");
2990 struct stat statbuf
;
2993 rv
= stat(path
, &statbuf
);
2996 if (S_ISDIR(statbuf
.st_mode
)) {
2997 /* it's a directory */
2998 PyErr_SetString(PyExc_ImportError
,
2999 "existing directory");
3004 if (object_exists(path
)) {
3007 /* it's a directory */
3008 PyErr_SetString(PyExc_ImportError
,
3009 "existing directory");
3019 NullImporter_find_module(NullImporter
*self
, PyObject
*args
)
3024 static PyMethodDef NullImporter_methods
[] = {
3025 {"find_module", (PyCFunction
)NullImporter_find_module
, METH_VARARGS
,
3026 "Always return None"
3028 {NULL
} /* Sentinel */
3032 static PyTypeObject NullImporterType
= {
3033 PyObject_HEAD_INIT(NULL
)
3035 "imp.NullImporter", /*tp_name*/
3036 sizeof(NullImporter
), /*tp_basicsize*/
3045 0, /*tp_as_sequence*/
3046 0, /*tp_as_mapping*/
3053 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
3054 "Null importer object", /* tp_doc */
3055 0, /* tp_traverse */
3057 0, /* tp_richcompare */
3058 0, /* tp_weaklistoffset */
3060 0, /* tp_iternext */
3061 NullImporter_methods
, /* tp_methods */
3066 0, /* tp_descr_get */
3067 0, /* tp_descr_set */
3068 0, /* tp_dictoffset */
3069 (initproc
)NullImporter_init
, /* tp_init */
3071 PyType_GenericNew
/* tp_new */
3080 if (PyType_Ready(&NullImporterType
) < 0)
3083 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
3084 NULL
, PYTHON_API_VERSION
);
3087 d
= PyModule_GetDict(m
);
3091 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
3092 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
3093 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
3094 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
3095 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
3096 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
3097 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
3098 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
3099 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
3100 if (setint(d
, "IMP_HOOK", IMP_HOOK
) < 0) goto failure
;
3102 Py_INCREF(&NullImporterType
);
3103 PyModule_AddObject(m
, "NullImporter", (PyObject
*)&NullImporterType
);
3109 /* API for embedding applications that want to add their own entries
3110 to the table of built-in modules. This should normally be called
3111 *before* Py_Initialize(). When the table resize fails, -1 is
3112 returned and the existing table is unchanged.
3114 After a similar function by Just van Rossum. */
3117 PyImport_ExtendInittab(struct _inittab
*newtab
)
3119 static struct _inittab
*our_copy
= NULL
;
3123 /* Count the number of entries in both tables */
3124 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
3127 return 0; /* Nothing to do */
3128 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
3131 /* Allocate new memory for the combined table */
3133 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
3137 /* Copy the tables into the new memory */
3138 if (our_copy
!= PyImport_Inittab
)
3139 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
3140 PyImport_Inittab
= our_copy
= p
;
3141 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
3146 /* Shorthand to add a single entry given a name and a function */
3149 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
3151 struct _inittab newtab
[2];
3153 memset(newtab
, '\0', sizeof newtab
);
3155 newtab
[0].name
= name
;
3156 newtab
[0].initfunc
= initfunc
;
3158 return PyImport_ExtendInittab(newtab
);