2 /* Python interpreter top-level routines, including init/exit */
20 #ifdef HAVE_LANGINFO_H
33 extern char *Py_GetPath(void);
35 extern grammar _PyParser_Grammar
; /* From graminit.c */
38 static void initmain(void);
39 static void initsite(void);
40 static PyObject
*run_err_node(node
*, const char *, PyObject
*, PyObject
*,
42 static PyObject
*run_node(node
*, const char *, PyObject
*, PyObject
*,
44 static PyObject
*run_pyc_file(FILE *, const char *, PyObject
*, PyObject
*,
46 static void err_input(perrdetail
*);
47 static void initsigs(void);
48 static void call_sys_exitfunc(void);
49 static void call_ll_exitfuncs(void);
50 extern void _PyUnicode_Init(void);
51 extern void _PyUnicode_Fini(void);
54 extern void _PyGILState_Init(PyInterpreterState
*, PyThreadState
*);
55 extern void _PyGILState_Fini(void);
56 #endif /* WITH_THREAD */
58 int Py_DebugFlag
; /* Needed by parser.c */
59 int Py_VerboseFlag
; /* Needed by import.c */
60 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
61 int Py_NoSiteFlag
; /* Suppress 'import site' */
62 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c: deprecated */
63 int Py_FrozenFlag
; /* Needed by getpath.c */
64 int Py_UnicodeFlag
= 0; /* Needed by compile.c */
65 int Py_IgnoreEnvironmentFlag
; /* e.g. PYTHONPATH, PYTHONHOME */
66 /* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
67 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
68 true divisions (which they will be in 2.3). */
71 /* Reference to 'warnings' module, to avoid importing it
72 on the fly when the import lock may be held. See 683658
74 PyObject
*PyModule_WarningsModule
= NULL
;
76 static int initialized
= 0;
78 /* API to access the initialized flag -- useful for esoteric use */
81 Py_IsInitialized(void)
86 /* Global initializations. Can be undone by Py_Finalize(). Don't
87 call this twice without an intervening Py_Finalize() call. When
88 initializations fail, a fatal error is issued and the function does
89 not return. On return, the first thread and interpreter state have
92 Locking: you must hold the interpreter lock while calling this.
93 (If the lock has not yet been initialized, that's equivalent to
94 having the lock, but you cannot use multiple threads.)
99 add_flag(int flag
, const char *envs
)
101 int env
= atoi(envs
);
112 PyInterpreterState
*interp
;
113 PyThreadState
*tstate
;
114 PyObject
*bimod
, *sysmod
;
116 extern void _Py_ReadyTypes(void);
122 if ((p
= Py_GETENV("PYTHONDEBUG")) && *p
!= '\0')
123 Py_DebugFlag
= add_flag(Py_DebugFlag
, p
);
124 if ((p
= Py_GETENV("PYTHONVERBOSE")) && *p
!= '\0')
125 Py_VerboseFlag
= add_flag(Py_VerboseFlag
, p
);
126 if ((p
= Py_GETENV("PYTHONOPTIMIZE")) && *p
!= '\0')
127 Py_OptimizeFlag
= add_flag(Py_OptimizeFlag
, p
);
129 interp
= PyInterpreterState_New();
131 Py_FatalError("Py_Initialize: can't make first interpreter");
133 tstate
= PyThreadState_New(interp
);
135 Py_FatalError("Py_Initialize: can't make first thread");
136 (void) PyThreadState_Swap(tstate
);
140 if (!_PyFrame_Init())
141 Py_FatalError("Py_Initialize: can't init frames");
144 Py_FatalError("Py_Initialize: can't init ints");
146 interp
->modules
= PyDict_New();
147 if (interp
->modules
== NULL
)
148 Py_FatalError("Py_Initialize: can't make modules dictionary");
150 #ifdef Py_USING_UNICODE
151 /* Init Unicode implementation; relies on the codec registry */
155 bimod
= _PyBuiltin_Init();
157 Py_FatalError("Py_Initialize: can't initialize __builtin__");
158 interp
->builtins
= PyModule_GetDict(bimod
);
159 Py_INCREF(interp
->builtins
);
161 sysmod
= _PySys_Init();
163 Py_FatalError("Py_Initialize: can't initialize sys");
164 interp
->sysdict
= PyModule_GetDict(sysmod
);
165 Py_INCREF(interp
->sysdict
);
166 _PyImport_FixupExtension("sys", "sys");
167 PySys_SetPath(Py_GetPath());
168 PyDict_SetItemString(interp
->sysdict
, "modules",
173 /* initialize builtin exceptions */
175 _PyImport_FixupExtension("exceptions", "exceptions");
177 /* phase 2 of builtins */
178 _PyImport_FixupExtension("__builtin__", "__builtin__");
180 _PyImportHooks_Init();
182 initsigs(); /* Signal handling stuff, including initintr() */
184 initmain(); /* Module __main__ */
186 initsite(); /* Module site */
188 /* auto-thread-state API, if available */
190 _PyGILState_Init(interp
, tstate
);
191 #endif /* WITH_THREAD */
193 PyModule_WarningsModule
= PyImport_ImportModule("warnings");
195 #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
196 /* On Unix, set the file system encoding according to the
197 user's preference, if the CODESET names a well-known
198 Python codec, and Py_FileSystemDefaultEncoding isn't
199 initialized by other means. */
200 if (!Py_FileSystemDefaultEncoding
) {
201 char *saved_locale
= setlocale(LC_CTYPE
, NULL
);
203 setlocale(LC_CTYPE
, "");
204 codeset
= nl_langinfo(CODESET
);
206 PyObject
*enc
= PyCodec_Encoder(codeset
);
208 Py_FileSystemDefaultEncoding
= strdup(codeset
);
213 setlocale(LC_CTYPE
, saved_locale
);
219 extern void dump_counts(void);
222 /* Undo the effect of Py_Initialize().
224 Beware: if multiple interpreter and/or thread states exist, these
225 are not wiped out; only the current thread and interpreter state
226 are deleted. But since everything else is deleted, those other
227 interpreter and thread states should no longer be used.
229 (XXX We should do better, e.g. wipe out all interpreters and
239 PyInterpreterState
*interp
;
240 PyThreadState
*tstate
;
245 /* The interpreter is still entirely intact at this point, and the
246 * exit funcs may be relying on that. In particular, if some thread
247 * or exit func is still waiting to do an import, the import machinery
248 * expects Py_IsInitialized() to return true. So don't say the
249 * interpreter is uninitialized until after the exit funcs have run.
250 * Note that Threading.py uses an exit func to do a join on all the
251 * threads created thru it, so this also protects pending imports in
252 * the threads created via Threading.
257 /* Get current thread state and interpreter pointer */
258 tstate
= PyThreadState_Get();
259 interp
= tstate
->interp
;
261 /* Disable signal handling */
262 PyOS_FiniInterrupts();
264 /* drop module references we saved */
265 Py_XDECREF(PyModule_WarningsModule
);
266 PyModule_WarningsModule
= NULL
;
268 /* Collect garbage. This may call finalizers; it's nice to call these
269 before all modules are destroyed. */
272 /* Destroy all modules */
275 /* Collect final garbage. This disposes of cycles created by
276 new-style class definitions, for example. */
279 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
282 /* Debugging stuff */
288 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
292 /* Display all objects still alive -- this can invoke arbitrary
293 * __repr__ overrides, so requires a mostly-intact interpreter.
294 * Alas, a lot of stuff may still be alive now that will be cleaned
297 if (Py_GETENV("PYTHONDUMPREFS"))
298 _Py_PrintReferences(stderr
);
299 #endif /* Py_TRACE_REFS */
301 /* Now we decref the exception classes. After this point nothing
302 can raise an exception. That's okay, because each Fini() method
303 below has been checked to make sure no exceptions are ever
308 /* Cleanup auto-thread-state */
311 #endif /* WITH_THREAD */
313 /* Clear interpreter state */
314 PyInterpreterState_Clear(interp
);
316 /* Delete current thread */
317 PyThreadState_Swap(NULL
);
318 PyInterpreterState_Delete(interp
);
320 /* Sundry finalizers */
329 #ifdef Py_USING_UNICODE
330 /* Cleanup Unicode implementation */
334 /* XXX Still allocated:
335 - various static ad-hoc pointers to interned strings
336 - int and float free list blocks
337 - whatever various modules and libraries allocate
340 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
343 /* Display addresses (& refcnts) of all objects still alive.
344 * An address can be used to find the repr of the object, printed
345 * above by _Py_PrintReferences.
347 if (Py_GETENV("PYTHONDUMPREFS"))
348 _Py_PrintReferenceAddresses(stderr
);
349 #endif /* Py_TRACE_REFS */
350 #ifdef PYMALLOC_DEBUG
351 if (Py_GETENV("PYTHONMALLOCSTATS"))
352 _PyObject_DebugMallocStats();
358 /* Create and initialize a new interpreter and thread, and return the
359 new thread. This requires that Py_Initialize() has been called
362 Unsuccessful initialization yields a NULL pointer. Note that *no*
363 exception information is available even in this case -- the
364 exception information is held in the thread, and there is no
372 Py_NewInterpreter(void)
374 PyInterpreterState
*interp
;
375 PyThreadState
*tstate
, *save_tstate
;
376 PyObject
*bimod
, *sysmod
;
379 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
381 interp
= PyInterpreterState_New();
385 tstate
= PyThreadState_New(interp
);
386 if (tstate
== NULL
) {
387 PyInterpreterState_Delete(interp
);
391 save_tstate
= PyThreadState_Swap(tstate
);
393 /* XXX The following is lax in error checking */
395 interp
->modules
= PyDict_New();
397 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
399 interp
->builtins
= PyModule_GetDict(bimod
);
400 Py_INCREF(interp
->builtins
);
402 sysmod
= _PyImport_FindExtension("sys", "sys");
403 if (bimod
!= NULL
&& sysmod
!= NULL
) {
404 interp
->sysdict
= PyModule_GetDict(sysmod
);
405 Py_INCREF(interp
->sysdict
);
406 PySys_SetPath(Py_GetPath());
407 PyDict_SetItemString(interp
->sysdict
, "modules",
409 _PyImportHooks_Init();
415 if (!PyErr_Occurred())
418 /* Oops, it didn't work. Undo it all. */
421 PyThreadState_Clear(tstate
);
422 PyThreadState_Swap(save_tstate
);
423 PyThreadState_Delete(tstate
);
424 PyInterpreterState_Delete(interp
);
429 /* Delete an interpreter and its last thread. This requires that the
430 given thread state is current, that the thread has no remaining
431 frames, and that it is its interpreter's only remaining thread.
432 It is a fatal error to violate these constraints.
434 (Py_Finalize() doesn't have these constraints -- it zaps
435 everything, regardless.)
442 Py_EndInterpreter(PyThreadState
*tstate
)
444 PyInterpreterState
*interp
= tstate
->interp
;
446 if (tstate
!= PyThreadState_Get())
447 Py_FatalError("Py_EndInterpreter: thread is not current");
448 if (tstate
->frame
!= NULL
)
449 Py_FatalError("Py_EndInterpreter: thread still has a frame");
450 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
451 Py_FatalError("Py_EndInterpreter: not the last thread");
454 PyInterpreterState_Clear(interp
);
455 PyThreadState_Swap(NULL
);
456 PyInterpreterState_Delete(interp
);
459 static char *progname
= "python";
462 Py_SetProgramName(char *pn
)
469 Py_GetProgramName(void)
474 static char *default_home
= NULL
;
477 Py_SetPythonHome(char *home
)
483 Py_GetPythonHome(void)
485 char *home
= default_home
;
486 if (home
== NULL
&& !Py_IgnoreEnvironmentFlag
)
487 home
= Py_GETENV("PYTHONHOME");
491 /* Create __main__ module */
497 m
= PyImport_AddModule("__main__");
499 Py_FatalError("can't create __main__ module");
500 d
= PyModule_GetDict(m
);
501 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
502 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
504 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
505 Py_FatalError("can't add __builtins__ to __main__");
510 /* Import the site module (not into __main__ though) */
516 m
= PyImport_ImportModule("site");
518 f
= PySys_GetObject("stderr");
519 if (Py_VerboseFlag
) {
521 "'import site' failed; traceback:\n", f
);
526 "'import site' failed; use -v for traceback\n", f
);
535 /* Parse input from a file and execute it */
538 PyRun_AnyFile(FILE *fp
, const char *filename
)
540 return PyRun_AnyFileExFlags(fp
, filename
, 0, NULL
);
544 PyRun_AnyFileFlags(FILE *fp
, const char *filename
, PyCompilerFlags
*flags
)
546 return PyRun_AnyFileExFlags(fp
, filename
, 0, flags
);
550 PyRun_AnyFileEx(FILE *fp
, const char *filename
, int closeit
)
552 return PyRun_AnyFileExFlags(fp
, filename
, closeit
, NULL
);
556 PyRun_AnyFileExFlags(FILE *fp
, const char *filename
, int closeit
,
557 PyCompilerFlags
*flags
)
559 if (filename
== NULL
)
561 if (Py_FdIsInteractive(fp
, filename
)) {
562 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
568 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
572 PyRun_InteractiveLoop(FILE *fp
, const char *filename
)
574 return PyRun_InteractiveLoopFlags(fp
, filename
, NULL
);
578 PyRun_InteractiveLoopFlags(FILE *fp
, const char *filename
, PyCompilerFlags
*flags
)
582 PyCompilerFlags local_flags
;
585 flags
= &local_flags
;
586 local_flags
.cf_flags
= 0;
588 v
= PySys_GetObject("ps1");
590 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
593 v
= PySys_GetObject("ps2");
595 PySys_SetObject("ps2", v
= PyString_FromString("... "));
599 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
601 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
613 PyRun_InteractiveOne(FILE *fp
, const char *filename
)
615 return PyRun_InteractiveOneFlags(fp
, filename
, NULL
);
618 /* compute parser flags based on compiler flags */
619 #define PARSER_FLAGS(flags) \
620 (((flags) && (flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
621 PyPARSE_DONT_IMPLY_DEDENT : 0)
624 PyRun_InteractiveOneFlags(FILE *fp
, const char *filename
, PyCompilerFlags
*flags
)
626 PyObject
*m
, *d
, *v
, *w
;
629 char *ps1
= "", *ps2
= "";
631 v
= PySys_GetObject("ps1");
636 else if (PyString_Check(v
))
637 ps1
= PyString_AsString(v
);
639 w
= PySys_GetObject("ps2");
644 else if (PyString_Check(w
))
645 ps2
= PyString_AsString(w
);
647 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
,
648 Py_single_input
, ps1
, ps2
, &err
,
649 PARSER_FLAGS(flags
));
653 if (err
.error
== E_EOF
) {
662 m
= PyImport_AddModule("__main__");
665 d
= PyModule_GetDict(m
);
666 v
= run_node(n
, filename
, d
, d
, flags
);
678 PyRun_SimpleFile(FILE *fp
, const char *filename
)
680 return PyRun_SimpleFileEx(fp
, filename
, 0);
683 /* Check whether a file maybe a pyc file: Look at the extension,
684 the file type, and, if we may close it, at the first few bytes. */
687 maybe_pyc_file(FILE *fp
, const char* filename
, const char* ext
, int closeit
)
689 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
693 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
694 if (PyMac_getfiletype((char *)filename
) == 'PYC '
695 || PyMac_getfiletype((char *)filename
) == 'APPL')
697 #endif /* macintosh */
699 /* Only look into the file if we are allowed to close it, since
700 it then should also be seekable. */
702 /* Read only two bytes of the magic. If the file was opened in
703 text mode, the bytes 3 and 4 of the magic (\r\n) might not
704 be read as they are on disk. */
705 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
706 unsigned char buf
[2];
707 /* Mess: In case of -x, the stream is NOT at its start now,
708 and ungetc() was used to push back the first newline,
709 which makes the current stream position formally undefined,
710 and a x-platform nightmare.
711 Unfortunately, we have no direct way to know whether -x
712 was specified. So we use a terrible hack: if the current
713 stream position is not 0, we assume -x was specified, and
714 give up. Bug 132850 on SourceForge spells out the
715 hopelessness of trying anything else (fseek and ftell
716 don't work predictably x-platform for text-mode files).
719 if (ftell(fp
) == 0) {
720 if (fread(buf
, 1, 2, fp
) == 2 &&
721 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
731 PyRun_SimpleFileEx(FILE *fp
, const char *filename
, int closeit
)
733 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, NULL
);
737 PyRun_SimpleFileExFlags(FILE *fp
, const char *filename
, int closeit
,
738 PyCompilerFlags
*flags
)
743 m
= PyImport_AddModule("__main__");
746 d
= PyModule_GetDict(m
);
747 if (PyDict_GetItemString(d
, "__file__") == NULL
) {
748 PyObject
*f
= PyString_FromString(filename
);
751 if (PyDict_SetItemString(d
, "__file__", f
) < 0) {
757 ext
= filename
+ strlen(filename
) - 4;
758 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
759 /* Try to run a pyc file. First, re-open in binary */
762 if ((fp
= fopen(filename
, "rb")) == NULL
) {
763 fprintf(stderr
, "python: Can't reopen .pyc file\n");
766 /* Turn on optimization if a .pyo file is given */
767 if (strcmp(ext
, ".pyo") == 0)
769 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
771 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
785 PyRun_SimpleString(const char *command
)
787 return PyRun_SimpleStringFlags(command
, NULL
);
791 PyRun_SimpleStringFlags(const char *command
, PyCompilerFlags
*flags
)
794 m
= PyImport_AddModule("__main__");
797 d
= PyModule_GetDict(m
);
798 v
= PyRun_StringFlags(command
, Py_file_input
, d
, d
, flags
);
810 parse_syntax_error(PyObject
*err
, PyObject
**message
, const char **filename
,
811 int *lineno
, int *offset
, const char **text
)
816 /* old style errors */
817 if (PyTuple_Check(err
))
818 return PyArg_ParseTuple(err
, "O(ziiz)", message
, filename
,
819 lineno
, offset
, text
);
821 /* new style errors. `err' is an instance */
823 if (! (v
= PyObject_GetAttrString(err
, "msg")))
827 if (!(v
= PyObject_GetAttrString(err
, "filename")))
831 else if (! (*filename
= PyString_AsString(v
)))
835 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
837 hold
= PyInt_AsLong(v
);
840 if (hold
< 0 && PyErr_Occurred())
844 if (!(v
= PyObject_GetAttrString(err
, "offset")))
851 hold
= PyInt_AsLong(v
);
854 if (hold
< 0 && PyErr_Occurred())
859 if (!(v
= PyObject_GetAttrString(err
, "text")))
863 else if (! (*text
= PyString_AsString(v
)))
880 print_error_text(PyObject
*f
, int offset
, const char *text
)
884 if (offset
> 0 && offset
== (int)strlen(text
))
887 nl
= strchr(text
, '\n');
888 if (nl
== NULL
|| nl
-text
>= offset
)
890 offset
-= (nl
+1-text
);
893 while (*text
== ' ' || *text
== '\t') {
898 PyFile_WriteString(" ", f
);
899 PyFile_WriteString(text
, f
);
900 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
901 PyFile_WriteString("\n", f
);
904 PyFile_WriteString(" ", f
);
907 PyFile_WriteString(" ", f
);
910 PyFile_WriteString("^\n", f
);
914 handle_system_exit(void)
916 PyObject
*exception
, *value
, *tb
;
919 PyErr_Fetch(&exception
, &value
, &tb
);
923 if (value
== NULL
|| value
== Py_None
)
925 if (PyInstance_Check(value
)) {
926 /* The error code should be in the `code' attribute. */
927 PyObject
*code
= PyObject_GetAttrString(value
, "code");
931 if (value
== Py_None
)
934 /* If we failed to dig out the 'code' attribute,
935 just let the else clause below print the error. */
937 if (PyInt_Check(value
))
938 exitcode
= (int)PyInt_AsLong(value
);
940 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
941 PySys_WriteStderr("\n");
945 /* Restore and clear the exception info, in order to properly decref
946 * the exception, value, and traceback. If we just exit instead,
947 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
948 * some finalizers from running.
950 PyErr_Restore(exception
, value
, tb
);
957 PyErr_PrintEx(int set_sys_last_vars
)
959 PyObject
*exception
, *v
, *tb
, *hook
;
961 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
962 handle_system_exit();
964 PyErr_Fetch(&exception
, &v
, &tb
);
965 PyErr_NormalizeException(&exception
, &v
, &tb
);
966 if (exception
== NULL
)
968 if (set_sys_last_vars
) {
969 PySys_SetObject("last_type", exception
);
970 PySys_SetObject("last_value", v
);
971 PySys_SetObject("last_traceback", tb
);
973 hook
= PySys_GetObject("excepthook");
975 PyObject
*args
= Py_BuildValue("(OOO)",
976 exception
, v
? v
: Py_None
, tb
? tb
: Py_None
);
977 PyObject
*result
= PyEval_CallObject(hook
, args
);
978 if (result
== NULL
) {
979 PyObject
*exception2
, *v2
, *tb2
;
980 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
981 handle_system_exit();
983 PyErr_Fetch(&exception2
, &v2
, &tb2
);
984 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
988 PySys_WriteStderr("Error in sys.excepthook:\n");
989 PyErr_Display(exception2
, v2
, tb2
);
990 PySys_WriteStderr("\nOriginal exception was:\n");
991 PyErr_Display(exception
, v
, tb
);
992 Py_XDECREF(exception2
);
999 PySys_WriteStderr("sys.excepthook is missing\n");
1000 PyErr_Display(exception
, v
, tb
);
1002 Py_XDECREF(exception
);
1007 void PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
1010 PyObject
*v
= value
;
1011 PyObject
*f
= PySys_GetObject("stderr");
1013 fprintf(stderr
, "lost sys.stderr\n");
1018 if (tb
&& tb
!= Py_None
)
1019 err
= PyTraceBack_Print(tb
, f
);
1021 PyObject_HasAttrString(v
, "print_file_and_line"))
1024 const char *filename
, *text
;
1026 if (!parse_syntax_error(v
, &message
, &filename
,
1027 &lineno
, &offset
, &text
))
1031 PyFile_WriteString(" File \"", f
);
1032 if (filename
== NULL
)
1033 PyFile_WriteString("<string>", f
);
1035 PyFile_WriteString(filename
, f
);
1036 PyFile_WriteString("\", line ", f
);
1037 PyOS_snprintf(buf
, sizeof(buf
), "%d", lineno
);
1038 PyFile_WriteString(buf
, f
);
1039 PyFile_WriteString("\n", f
);
1041 print_error_text(f
, offset
, text
);
1043 /* Can't be bothered to check all those
1044 PyFile_WriteString() calls */
1045 if (PyErr_Occurred())
1050 /* Don't do anything else */
1052 else if (PyClass_Check(exception
)) {
1053 PyClassObject
* exc
= (PyClassObject
*)exception
;
1054 PyObject
* className
= exc
->cl_name
;
1055 PyObject
* moduleName
=
1056 PyDict_GetItemString(exc
->cl_dict
, "__module__");
1058 if (moduleName
== NULL
)
1059 err
= PyFile_WriteString("<unknown>", f
);
1061 char* modstr
= PyString_AsString(moduleName
);
1062 if (modstr
&& strcmp(modstr
, "exceptions"))
1064 err
= PyFile_WriteString(modstr
, f
);
1065 err
+= PyFile_WriteString(".", f
);
1069 if (className
== NULL
)
1070 err
= PyFile_WriteString("<unknown>", f
);
1072 err
= PyFile_WriteObject(className
, f
,
1077 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
1079 if (v
!= NULL
&& v
!= Py_None
) {
1080 PyObject
*s
= PyObject_Str(v
);
1081 /* only print colon if the str() of the
1082 object is not the empty string
1086 else if (!PyString_Check(s
) ||
1087 PyString_GET_SIZE(s
) != 0)
1088 err
= PyFile_WriteString(": ", f
);
1090 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
1095 err
= PyFile_WriteString("\n", f
);
1097 /* If an error happened here, don't show it.
1098 XXX This is wrong, but too many callers rely on this behavior. */
1104 PyRun_String(const char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
1106 return run_err_node(PyParser_SimpleParseString(str
, start
),
1107 "<string>", globals
, locals
, NULL
);
1111 PyRun_File(FILE *fp
, const char *filename
, int start
, PyObject
*globals
,
1114 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
1118 PyRun_FileEx(FILE *fp
, const char *filename
, int start
, PyObject
*globals
,
1119 PyObject
*locals
, int closeit
)
1121 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1124 return run_err_node(n
, filename
, globals
, locals
, NULL
);
1128 PyRun_StringFlags(const char *str
, int start
, PyObject
*globals
, PyObject
*locals
,
1129 PyCompilerFlags
*flags
)
1131 return run_err_node(PyParser_SimpleParseStringFlags(
1132 str
, start
, PARSER_FLAGS(flags
)),
1133 "<string>", globals
, locals
, flags
);
1137 PyRun_FileFlags(FILE *fp
, const char *filename
, int start
, PyObject
*globals
,
1138 PyObject
*locals
, PyCompilerFlags
*flags
)
1140 return PyRun_FileExFlags(fp
, filename
, start
, globals
, locals
, 0,
1145 PyRun_FileExFlags(FILE *fp
, const char *filename
, int start
, PyObject
*globals
,
1146 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1148 node
*n
= PyParser_SimpleParseFileFlags(fp
, filename
, start
,
1149 PARSER_FLAGS(flags
));
1152 return run_err_node(n
, filename
, globals
, locals
, flags
);
1156 run_err_node(node
*n
, const char *filename
, PyObject
*globals
, PyObject
*locals
,
1157 PyCompilerFlags
*flags
)
1161 return run_node(n
, filename
, globals
, locals
, flags
);
1165 run_node(node
*n
, const char *filename
, PyObject
*globals
, PyObject
*locals
,
1166 PyCompilerFlags
*flags
)
1170 co
= PyNode_CompileFlags(n
, filename
, flags
);
1174 v
= PyEval_EvalCode(co
, globals
, locals
);
1180 run_pyc_file(FILE *fp
, const char *filename
, PyObject
*globals
, PyObject
*locals
,
1181 PyCompilerFlags
*flags
)
1186 long PyImport_GetMagicNumber(void);
1188 magic
= PyMarshal_ReadLongFromFile(fp
);
1189 if (magic
!= PyImport_GetMagicNumber()) {
1190 PyErr_SetString(PyExc_RuntimeError
,
1191 "Bad magic number in .pyc file");
1194 (void) PyMarshal_ReadLongFromFile(fp
);
1195 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1197 if (v
== NULL
|| !PyCode_Check(v
)) {
1199 PyErr_SetString(PyExc_RuntimeError
,
1200 "Bad code object in .pyc file");
1203 co
= (PyCodeObject
*)v
;
1204 v
= PyEval_EvalCode(co
, globals
, locals
);
1206 flags
->cf_flags
|= (co
->co_flags
& PyCF_MASK
);
1212 Py_CompileString(const char *str
, const char *filename
, int start
)
1214 return Py_CompileStringFlags(str
, filename
, start
, NULL
);
1218 Py_CompileStringFlags(const char *str
, const char *filename
, int start
,
1219 PyCompilerFlags
*flags
)
1224 n
= PyParser_SimpleParseStringFlagsFilename(str
, filename
, start
,
1225 PARSER_FLAGS(flags
));
1228 co
= PyNode_CompileFlags(n
, filename
, flags
);
1230 return (PyObject
*)co
;
1234 Py_SymtableString(const char *str
, const char *filename
, int start
)
1237 struct symtable
*st
;
1238 n
= PyParser_SimpleParseStringFlagsFilename(str
, filename
,
1242 st
= PyNode_CompileSymtable(n
, filename
);
1247 /* Simplified interface to parsefile -- return node or set exception */
1250 PyParser_SimpleParseFileFlags(FILE *fp
, const char *filename
, int start
, int flags
)
1254 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
, start
,
1255 (char *)0, (char *)0, &err
, flags
);
1262 PyParser_SimpleParseFile(FILE *fp
, const char *filename
, int start
)
1264 return PyParser_SimpleParseFileFlags(fp
, filename
, start
, 0);
1267 /* Simplified interface to parsestring -- return node or set exception */
1270 PyParser_SimpleParseStringFlags(const char *str
, int start
, int flags
)
1274 n
= PyParser_ParseStringFlags(str
, &_PyParser_Grammar
, start
, &err
,
1282 PyParser_SimpleParseString(const char *str
, int start
)
1284 return PyParser_SimpleParseStringFlags(str
, start
, 0);
1288 PyParser_SimpleParseStringFlagsFilename(const char *str
, const char *filename
,
1289 int start
, int flags
)
1294 n
= PyParser_ParseStringFlagsFilename(str
, filename
,
1296 start
, &err
, flags
);
1303 PyParser_SimpleParseStringFilename(const char *str
, const char *filename
, int start
)
1305 return PyParser_SimpleParseStringFlagsFilename(str
, filename
,
1309 /* May want to move a more generalized form of this to parsetok.c or
1310 even parser modules. */
1313 PyParser_SetError(perrdetail
*err
)
1318 /* Set the error appropriate to the given input error code (see errcode.h) */
1321 err_input(perrdetail
*err
)
1323 PyObject
*v
, *w
, *errtype
;
1326 errtype
= PyExc_SyntaxError
;
1327 v
= Py_BuildValue("(ziiz)", err
->filename
,
1328 err
->lineno
, err
->offset
, err
->text
);
1329 if (err
->text
!= NULL
) {
1330 PyMem_DEL(err
->text
);
1333 switch (err
->error
) {
1335 errtype
= PyExc_IndentationError
;
1336 if (err
->expected
== INDENT
)
1337 msg
= "expected an indented block";
1338 else if (err
->token
== INDENT
)
1339 msg
= "unexpected indent";
1340 else if (err
->token
== DEDENT
)
1341 msg
= "unexpected unindent";
1343 errtype
= PyExc_SyntaxError
;
1344 msg
= "invalid syntax";
1348 msg
= "invalid token";
1351 msg
= "EOF while scanning triple-quoted string";
1354 msg
= "EOL while scanning single-quoted string";
1357 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1365 msg
= "unexpected EOF while parsing";
1368 errtype
= PyExc_TabError
;
1369 msg
= "inconsistent use of tabs and spaces in indentation";
1372 msg
= "expression too long";
1375 errtype
= PyExc_IndentationError
;
1376 msg
= "unindent does not match any outer indentation level";
1379 errtype
= PyExc_IndentationError
;
1380 msg
= "too many levels of indentation";
1382 case E_DECODE
: { /* XXX */
1383 PyThreadState
* tstate
= PyThreadState_Get();
1384 PyObject
* value
= tstate
->curexc_value
;
1385 if (value
!= NULL
) {
1386 u
= PyObject_Repr(value
);
1388 msg
= PyString_AsString(u
);
1394 fprintf(stderr
, "error=%d\n", err
->error
);
1395 msg
= "unknown parsing error";
1398 w
= Py_BuildValue("(sO)", msg
, v
);
1401 PyErr_SetObject(errtype
, w
);
1405 /* Print fatal error message and abort */
1408 Py_FatalError(const char *msg
)
1410 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1412 OutputDebugString("Fatal Python error: ");
1413 OutputDebugString(msg
);
1414 OutputDebugString("\n");
1418 #endif /* MS_WINDOWS */
1422 /* Clean up and exit */
1425 #include "pythread.h"
1426 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1429 #define NEXITFUNCS 32
1430 static void (*exitfuncs
[NEXITFUNCS
])(void);
1431 static int nexitfuncs
= 0;
1433 int Py_AtExit(void (*func
)(void))
1435 if (nexitfuncs
>= NEXITFUNCS
)
1437 exitfuncs
[nexitfuncs
++] = func
;
1442 call_sys_exitfunc(void)
1444 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1448 Py_INCREF(exitfunc
);
1449 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1450 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1452 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1453 PySys_WriteStderr("Error in sys.exitfunc:\n");
1457 Py_DECREF(exitfunc
);
1465 call_ll_exitfuncs(void)
1467 while (nexitfuncs
> 0)
1468 (*exitfuncs
[--nexitfuncs
])();
1489 #ifdef HAVE_SIGNAL_H
1491 signal(SIGPIPE
, SIG_IGN
);
1494 signal(SIGXFZ
, SIG_IGN
);
1497 signal(SIGXFSZ
, SIG_IGN
);
1499 #endif /* HAVE_SIGNAL_H */
1500 PyOS_InitInterrupts(); /* May imply initsignal() */
1505 /* Check for file descriptor connected to interactive device.
1506 Pretend that stdin is always interactive, other files never. */
1511 return fd
== fileno(stdin
);
1517 * The file descriptor fd is considered ``interactive'' if either
1518 * a) isatty(fd) is TRUE, or
1519 * b) the -i flag was given, and the filename associated with
1520 * the descriptor is NULL or "<stdin>" or "???".
1523 Py_FdIsInteractive(FILE *fp
, const char *filename
)
1525 if (isatty((int)fileno(fp
)))
1527 if (!Py_InteractiveFlag
)
1529 return (filename
== NULL
) ||
1530 (strcmp(filename
, "<stdin>") == 0) ||
1531 (strcmp(filename
, "???") == 0);
1535 #if defined(USE_STACKCHECK)
1536 #if defined(WIN32) && defined(_MSC_VER)
1538 /* Stack checking for Microsoft C */
1544 * Return non-zero when we run out of memory on the stack; zero otherwise.
1547 PyOS_CheckStack(void)
1550 /* alloca throws a stack overflow exception if there's
1551 not enough space left on the stack */
1552 alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1554 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1555 /* just ignore all errors */
1560 #endif /* WIN32 && _MSC_VER */
1562 /* Alternate implementations can be added here... */
1564 #endif /* USE_STACKCHECK */
1567 /* Wrappers around sigaction() or signal(). */
1570 PyOS_getsig(int sig
)
1572 #ifdef HAVE_SIGACTION
1573 struct sigaction context
;
1574 /* Initialize context.sa_handler to SIG_ERR which makes about as
1575 * much sense as anything else. It should get overwritten if
1576 * sigaction actually succeeds and otherwise we avoid an
1577 * uninitialized memory read.
1579 context
.sa_handler
= SIG_ERR
;
1580 sigaction(sig
, NULL
, &context
);
1581 return context
.sa_handler
;
1583 PyOS_sighandler_t handler
;
1584 handler
= signal(sig
, SIG_IGN
);
1585 signal(sig
, handler
);
1591 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1593 #ifdef HAVE_SIGACTION
1594 struct sigaction context
;
1595 PyOS_sighandler_t oldhandler
;
1596 /* Initialize context.sa_handler to SIG_ERR which makes about as
1597 * much sense as anything else. It should get overwritten if
1598 * sigaction actually succeeds and otherwise we avoid an
1599 * uninitialized memory read.
1601 context
.sa_handler
= SIG_ERR
;
1602 sigaction(sig
, NULL
, &context
);
1603 oldhandler
= context
.sa_handler
;
1604 context
.sa_handler
= handler
;
1605 sigaction(sig
, &context
, NULL
);
1608 return signal(sig
, handler
);