2 /* Python interpreter top-level routines, including init/exit */
28 extern char *Py_GetPath(void);
30 extern grammar _PyParser_Grammar
; /* From graminit.c */
33 static void initmain(void);
34 static void initsite(void);
35 static PyObject
*run_err_node(node
*, char *, PyObject
*, PyObject
*,
37 static PyObject
*run_node(node
*, char *, PyObject
*, PyObject
*,
39 static PyObject
*run_pyc_file(FILE *, char *, PyObject
*, PyObject
*,
41 static void err_input(perrdetail
*);
42 static void initsigs(void);
43 static void call_sys_exitfunc(void);
44 static void call_ll_exitfuncs(void);
45 extern void _PyUnicode_Init(void);
46 extern void _PyUnicode_Fini(void);
47 extern void _PyCodecRegistry_Init(void);
48 extern void _PyCodecRegistry_Fini(void);
50 int Py_DebugFlag
; /* Needed by parser.c */
51 int Py_VerboseFlag
; /* Needed by import.c */
52 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
53 int Py_NoSiteFlag
; /* Suppress 'import site' */
54 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c: deprecated */
55 int Py_FrozenFlag
; /* Needed by getpath.c */
56 int Py_UnicodeFlag
= 0; /* Needed by compile.c */
57 int Py_IgnoreEnvironmentFlag
; /* e.g. PYTHONPATH, PYTHONHOME */
58 /* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
59 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
60 true divisions (which they will be in 2.3). */
63 static int initialized
= 0;
65 /* API to access the initialized flag -- useful for esoteric use */
68 Py_IsInitialized(void)
73 /* Global initializations. Can be undone by Py_Finalize(). Don't
74 call this twice without an intervening Py_Finalize() call. When
75 initializations fail, a fatal error is issued and the function does
76 not return. On return, the first thread and interpreter state have
79 Locking: you must hold the interpreter lock while calling this.
80 (If the lock has not yet been initialized, that's equivalent to
81 having the lock, but you cannot use multiple threads.)
86 add_flag(int flag
, const char *envs
)
99 PyInterpreterState
*interp
;
100 PyThreadState
*tstate
;
101 PyObject
*bimod
, *sysmod
;
103 extern void _Py_ReadyTypes(void);
109 if ((p
= Py_GETENV("PYTHONDEBUG")) && *p
!= '\0')
110 Py_DebugFlag
= add_flag(Py_DebugFlag
, p
);
111 if ((p
= Py_GETENV("PYTHONVERBOSE")) && *p
!= '\0')
112 Py_VerboseFlag
= add_flag(Py_VerboseFlag
, p
);
113 if ((p
= Py_GETENV("PYTHONOPTIMIZE")) && *p
!= '\0')
114 Py_OptimizeFlag
= add_flag(Py_OptimizeFlag
, p
);
116 interp
= PyInterpreterState_New();
118 Py_FatalError("Py_Initialize: can't make first interpreter");
120 tstate
= PyThreadState_New(interp
);
122 Py_FatalError("Py_Initialize: can't make first thread");
123 (void) PyThreadState_Swap(tstate
);
127 interp
->modules
= PyDict_New();
128 if (interp
->modules
== NULL
)
129 Py_FatalError("Py_Initialize: can't make modules dictionary");
131 /* Init codec registry */
132 _PyCodecRegistry_Init();
134 #ifdef Py_USING_UNICODE
135 /* Init Unicode implementation; relies on the codec registry */
139 bimod
= _PyBuiltin_Init();
141 Py_FatalError("Py_Initialize: can't initialize __builtin__");
142 interp
->builtins
= PyModule_GetDict(bimod
);
143 Py_INCREF(interp
->builtins
);
145 sysmod
= _PySys_Init();
147 Py_FatalError("Py_Initialize: can't initialize sys");
148 interp
->sysdict
= PyModule_GetDict(sysmod
);
149 Py_INCREF(interp
->sysdict
);
150 _PyImport_FixupExtension("sys", "sys");
151 PySys_SetPath(Py_GetPath());
152 PyDict_SetItemString(interp
->sysdict
, "modules",
157 /* initialize builtin exceptions */
159 _PyImport_FixupExtension("exceptions", "exceptions");
161 /* phase 2 of builtins */
162 _PyImport_FixupExtension("__builtin__", "__builtin__");
164 initsigs(); /* Signal handling stuff, including initintr() */
166 initmain(); /* Module __main__ */
168 initsite(); /* Module site */
172 extern void dump_counts(void);
175 /* Undo the effect of Py_Initialize().
177 Beware: if multiple interpreter and/or thread states exist, these
178 are not wiped out; only the current thread and interpreter state
179 are deleted. But since everything else is deleted, those other
180 interpreter and thread states should no longer be used.
182 (XXX We should do better, e.g. wipe out all interpreters and
192 PyInterpreterState
*interp
;
193 PyThreadState
*tstate
;
198 /* The interpreter is still entirely intact at this point, and the
199 * exit funcs may be relying on that. In particular, if some thread
200 * or exit func is still waiting to do an import, the import machinery
201 * expects Py_IsInitialized() to return true. So don't say the
202 * interpreter is uninitialized until after the exit funcs have run.
203 * Note that Threading.py uses an exit func to do a join on all the
204 * threads created thru it, so this also protects pending imports in
205 * the threads created via Threading.
210 /* Get current thread state and interpreter pointer */
211 tstate
= PyThreadState_Get();
212 interp
= tstate
->interp
;
214 /* Disable signal handling */
215 PyOS_FiniInterrupts();
217 /* Cleanup Codec registry */
218 _PyCodecRegistry_Fini();
220 /* Destroy all modules */
223 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
226 /* Debugging stuff */
232 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
236 if (Py_GETENV("PYTHONDUMPREFS")) {
237 _Py_PrintReferences(stderr
);
239 #endif /* Py_TRACE_REFS */
241 /* Now we decref the exception classes. After this point nothing
242 can raise an exception. That's okay, because each Fini() method
243 below has been checked to make sure no exceptions are ever
248 /* Delete current thread */
249 PyInterpreterState_Clear(interp
);
250 PyThreadState_Swap(NULL
);
251 PyInterpreterState_Delete(interp
);
261 #ifdef Py_USING_UNICODE
262 /* Cleanup Unicode implementation */
266 /* XXX Still allocated:
267 - various static ad-hoc pointers to interned strings
268 - int and float free list blocks
269 - whatever various modules and libraries allocate
272 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
274 #ifdef PYMALLOC_DEBUG
275 if (Py_GETENV("PYTHONMALLOCSTATS"))
276 _PyObject_DebugMallocStats();
282 _Py_ResetReferences();
283 #endif /* Py_TRACE_REFS */
286 /* Create and initialize a new interpreter and thread, and return the
287 new thread. This requires that Py_Initialize() has been called
290 Unsuccessful initialization yields a NULL pointer. Note that *no*
291 exception information is available even in this case -- the
292 exception information is held in the thread, and there is no
300 Py_NewInterpreter(void)
302 PyInterpreterState
*interp
;
303 PyThreadState
*tstate
, *save_tstate
;
304 PyObject
*bimod
, *sysmod
;
307 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
309 interp
= PyInterpreterState_New();
313 tstate
= PyThreadState_New(interp
);
314 if (tstate
== NULL
) {
315 PyInterpreterState_Delete(interp
);
319 save_tstate
= PyThreadState_Swap(tstate
);
321 /* XXX The following is lax in error checking */
323 interp
->modules
= PyDict_New();
325 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
327 interp
->builtins
= PyModule_GetDict(bimod
);
328 Py_INCREF(interp
->builtins
);
330 sysmod
= _PyImport_FindExtension("sys", "sys");
331 if (bimod
!= NULL
&& sysmod
!= NULL
) {
332 interp
->sysdict
= PyModule_GetDict(sysmod
);
333 Py_INCREF(interp
->sysdict
);
334 PySys_SetPath(Py_GetPath());
335 PyDict_SetItemString(interp
->sysdict
, "modules",
342 if (!PyErr_Occurred())
345 /* Oops, it didn't work. Undo it all. */
348 PyThreadState_Clear(tstate
);
349 PyThreadState_Swap(save_tstate
);
350 PyThreadState_Delete(tstate
);
351 PyInterpreterState_Delete(interp
);
356 /* Delete an interpreter and its last thread. This requires that the
357 given thread state is current, that the thread has no remaining
358 frames, and that it is its interpreter's only remaining thread.
359 It is a fatal error to violate these constraints.
361 (Py_Finalize() doesn't have these constraints -- it zaps
362 everything, regardless.)
369 Py_EndInterpreter(PyThreadState
*tstate
)
371 PyInterpreterState
*interp
= tstate
->interp
;
373 if (tstate
!= PyThreadState_Get())
374 Py_FatalError("Py_EndInterpreter: thread is not current");
375 if (tstate
->frame
!= NULL
)
376 Py_FatalError("Py_EndInterpreter: thread still has a frame");
377 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
378 Py_FatalError("Py_EndInterpreter: not the last thread");
381 PyInterpreterState_Clear(interp
);
382 PyThreadState_Swap(NULL
);
383 PyInterpreterState_Delete(interp
);
386 static char *progname
= "python";
389 Py_SetProgramName(char *pn
)
396 Py_GetProgramName(void)
401 static char *default_home
= NULL
;
404 Py_SetPythonHome(char *home
)
410 Py_GetPythonHome(void)
412 char *home
= default_home
;
413 if (home
== NULL
&& !Py_IgnoreEnvironmentFlag
)
414 home
= Py_GETENV("PYTHONHOME");
418 /* Create __main__ module */
424 m
= PyImport_AddModule("__main__");
426 Py_FatalError("can't create __main__ module");
427 d
= PyModule_GetDict(m
);
428 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
429 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
431 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
432 Py_FatalError("can't add __builtins__ to __main__");
437 /* Import the site module (not into __main__ though) */
443 m
= PyImport_ImportModule("site");
445 f
= PySys_GetObject("stderr");
446 if (Py_VerboseFlag
) {
448 "'import site' failed; traceback:\n", f
);
453 "'import site' failed; use -v for traceback\n", f
);
462 /* Parse input from a file and execute it */
465 PyRun_AnyFile(FILE *fp
, char *filename
)
467 return PyRun_AnyFileExFlags(fp
, filename
, 0, NULL
);
471 PyRun_AnyFileFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
473 return PyRun_AnyFileExFlags(fp
, filename
, 0, flags
);
477 PyRun_AnyFileEx(FILE *fp
, char *filename
, int closeit
)
479 return PyRun_AnyFileExFlags(fp
, filename
, closeit
, NULL
);
483 PyRun_AnyFileExFlags(FILE *fp
, char *filename
, int closeit
,
484 PyCompilerFlags
*flags
)
486 if (filename
== NULL
)
488 if (Py_FdIsInteractive(fp
, filename
)) {
489 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
495 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
499 PyRun_InteractiveLoop(FILE *fp
, char *filename
)
501 return PyRun_InteractiveLoopFlags(fp
, filename
, NULL
);
505 PyRun_InteractiveLoopFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
509 PyCompilerFlags local_flags
;
512 flags
= &local_flags
;
513 local_flags
.cf_flags
= 0;
515 v
= PySys_GetObject("ps1");
517 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
520 v
= PySys_GetObject("ps2");
522 PySys_SetObject("ps2", v
= PyString_FromString("... "));
526 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
528 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
540 PyRun_InteractiveOne(FILE *fp
, char *filename
)
542 return PyRun_InteractiveOneFlags(fp
, filename
, NULL
);
545 /* compute parser flags based on compiler flags */
546 #if 0 /* future keyword */
547 #define PARSER_FLAGS(flags) \
548 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
549 PyPARSE_YIELD_IS_KEYWORD : 0)
551 #define PARSER_FLAGS(flags) 0
555 PyRun_InteractiveOneFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
557 PyObject
*m
, *d
, *v
, *w
;
560 char *ps1
= "", *ps2
= "";
562 v
= PySys_GetObject("ps1");
567 else if (PyString_Check(v
))
568 ps1
= PyString_AsString(v
);
570 w
= PySys_GetObject("ps2");
575 else if (PyString_Check(w
))
576 ps2
= PyString_AsString(w
);
578 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
,
579 Py_single_input
, ps1
, ps2
, &err
,
580 PARSER_FLAGS(flags
));
584 if (err
.error
== E_EOF
) {
593 m
= PyImport_AddModule("__main__");
596 d
= PyModule_GetDict(m
);
597 v
= run_node(n
, filename
, d
, d
, flags
);
609 PyRun_SimpleFile(FILE *fp
, char *filename
)
611 return PyRun_SimpleFileEx(fp
, filename
, 0);
614 /* Check whether a file maybe a pyc file: Look at the extension,
615 the file type, and, if we may close it, at the first few bytes. */
618 maybe_pyc_file(FILE *fp
, char* filename
, char* ext
, int closeit
)
620 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
624 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
625 if (PyMac_getfiletype(filename
) == 'PYC '
626 || PyMac_getfiletype(filename
) == 'APPL')
628 #endif /* macintosh */
630 /* Only look into the file if we are allowed to close it, since
631 it then should also be seekable. */
633 /* Read only two bytes of the magic. If the file was opened in
634 text mode, the bytes 3 and 4 of the magic (\r\n) might not
635 be read as they are on disk. */
636 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
637 unsigned char buf
[2];
638 /* Mess: In case of -x, the stream is NOT at its start now,
639 and ungetc() was used to push back the first newline,
640 which makes the current stream position formally undefined,
641 and a x-platform nightmare.
642 Unfortunately, we have no direct way to know whether -x
643 was specified. So we use a terrible hack: if the current
644 stream position is not 0, we assume -x was specified, and
645 give up. Bug 132850 on SourceForge spells out the
646 hopelessness of trying anything else (fseek and ftell
647 don't work predictably x-platform for text-mode files).
650 if (ftell(fp
) == 0) {
651 if (fread(buf
, 1, 2, fp
) == 2 &&
652 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
662 PyRun_SimpleFileEx(FILE *fp
, char *filename
, int closeit
)
664 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, NULL
);
668 PyRun_SimpleFileExFlags(FILE *fp
, char *filename
, int closeit
,
669 PyCompilerFlags
*flags
)
674 m
= PyImport_AddModule("__main__");
677 d
= PyModule_GetDict(m
);
678 ext
= filename
+ strlen(filename
) - 4;
679 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
680 /* Try to run a pyc file. First, re-open in binary */
683 if( (fp
= fopen(filename
, "rb")) == NULL
) {
684 fprintf(stderr
, "python: Can't reopen .pyc file\n");
687 /* Turn on optimization if a .pyo file is given */
688 if (strcmp(ext
, ".pyo") == 0)
690 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
692 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
706 PyRun_SimpleString(char *command
)
708 return PyRun_SimpleStringFlags(command
, NULL
);
712 PyRun_SimpleStringFlags(char *command
, PyCompilerFlags
*flags
)
715 m
= PyImport_AddModule("__main__");
718 d
= PyModule_GetDict(m
);
719 v
= PyRun_StringFlags(command
, Py_file_input
, d
, d
, flags
);
731 parse_syntax_error(PyObject
*err
, PyObject
**message
, char **filename
,
732 int *lineno
, int *offset
, char **text
)
737 /* old style errors */
738 if (PyTuple_Check(err
))
739 return PyArg_ParseTuple(err
, "O(ziiz)", message
, filename
,
740 lineno
, offset
, text
);
742 /* new style errors. `err' is an instance */
744 if (! (v
= PyObject_GetAttrString(err
, "msg")))
748 if (!(v
= PyObject_GetAttrString(err
, "filename")))
752 else if (! (*filename
= PyString_AsString(v
)))
756 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
758 hold
= PyInt_AsLong(v
);
761 if (hold
< 0 && PyErr_Occurred())
765 if (!(v
= PyObject_GetAttrString(err
, "offset")))
772 hold
= PyInt_AsLong(v
);
775 if (hold
< 0 && PyErr_Occurred())
780 if (!(v
= PyObject_GetAttrString(err
, "text")))
784 else if (! (*text
= PyString_AsString(v
)))
801 print_error_text(PyObject
*f
, int offset
, char *text
)
805 if (offset
> 0 && offset
== (int)strlen(text
))
808 nl
= strchr(text
, '\n');
809 if (nl
== NULL
|| nl
-text
>= offset
)
811 offset
-= (nl
+1-text
);
814 while (*text
== ' ' || *text
== '\t') {
819 PyFile_WriteString(" ", f
);
820 PyFile_WriteString(text
, f
);
821 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
822 PyFile_WriteString("\n", f
);
825 PyFile_WriteString(" ", f
);
828 PyFile_WriteString(" ", f
);
831 PyFile_WriteString("^\n", f
);
835 handle_system_exit(void)
837 PyObject
*exception
, *value
, *tb
;
838 PyErr_Fetch(&exception
, &value
, &tb
);
842 if (value
== NULL
|| value
== Py_None
)
844 if (PyInstance_Check(value
)) {
845 /* The error code should be in the `code' attribute. */
846 PyObject
*code
= PyObject_GetAttrString(value
, "code");
850 if (value
== Py_None
)
853 /* If we failed to dig out the 'code' attribute,
854 just let the else clause below print the error. */
856 if (PyInt_Check(value
))
857 Py_Exit((int)PyInt_AsLong(value
));
859 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
860 PySys_WriteStderr("\n");
866 PyErr_PrintEx(int set_sys_last_vars
)
868 PyObject
*exception
, *v
, *tb
, *hook
;
870 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
871 handle_system_exit();
873 PyErr_Fetch(&exception
, &v
, &tb
);
874 PyErr_NormalizeException(&exception
, &v
, &tb
);
875 if (exception
== NULL
)
877 if (set_sys_last_vars
) {
878 PySys_SetObject("last_type", exception
);
879 PySys_SetObject("last_value", v
);
880 PySys_SetObject("last_traceback", tb
);
882 hook
= PySys_GetObject("excepthook");
884 PyObject
*args
= Py_BuildValue("(OOO)",
885 exception
, v
? v
: Py_None
, tb
? tb
: Py_None
);
886 PyObject
*result
= PyEval_CallObject(hook
, args
);
887 if (result
== NULL
) {
888 PyObject
*exception2
, *v2
, *tb2
;
889 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
890 handle_system_exit();
892 PyErr_Fetch(&exception2
, &v2
, &tb2
);
893 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
897 PySys_WriteStderr("Error in sys.excepthook:\n");
898 PyErr_Display(exception2
, v2
, tb2
);
899 PySys_WriteStderr("\nOriginal exception was:\n");
900 PyErr_Display(exception
, v
, tb
);
901 Py_XDECREF(exception2
);
908 PySys_WriteStderr("sys.excepthook is missing\n");
909 PyErr_Display(exception
, v
, tb
);
911 Py_XDECREF(exception
);
916 void PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
920 PyObject
*f
= PySys_GetObject("stderr");
922 fprintf(stderr
, "lost sys.stderr\n");
927 if (tb
&& tb
!= Py_None
)
928 err
= PyTraceBack_Print(tb
, f
);
930 PyObject_HasAttrString(v
, "print_file_and_line"))
933 char *filename
, *text
;
935 if (!parse_syntax_error(v
, &message
, &filename
,
936 &lineno
, &offset
, &text
))
940 PyFile_WriteString(" File \"", f
);
941 if (filename
== NULL
)
942 PyFile_WriteString("<string>", f
);
944 PyFile_WriteString(filename
, f
);
945 PyFile_WriteString("\", line ", f
);
946 PyOS_snprintf(buf
, sizeof(buf
), "%d", lineno
);
947 PyFile_WriteString(buf
, f
);
948 PyFile_WriteString("\n", f
);
950 print_error_text(f
, offset
, text
);
952 /* Can't be bothered to check all those
953 PyFile_WriteString() calls */
954 if (PyErr_Occurred())
959 /* Don't do anything else */
961 else if (PyClass_Check(exception
)) {
962 PyClassObject
* exc
= (PyClassObject
*)exception
;
963 PyObject
* className
= exc
->cl_name
;
964 PyObject
* moduleName
=
965 PyDict_GetItemString(exc
->cl_dict
, "__module__");
967 if (moduleName
== NULL
)
968 err
= PyFile_WriteString("<unknown>", f
);
970 char* modstr
= PyString_AsString(moduleName
);
971 if (modstr
&& strcmp(modstr
, "exceptions"))
973 err
= PyFile_WriteString(modstr
, f
);
974 err
+= PyFile_WriteString(".", f
);
978 if (className
== NULL
)
979 err
= PyFile_WriteString("<unknown>", f
);
981 err
= PyFile_WriteObject(className
, f
,
986 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
988 if (v
!= NULL
&& v
!= Py_None
) {
989 PyObject
*s
= PyObject_Str(v
);
990 /* only print colon if the str() of the
991 object is not the empty string
995 else if (!PyString_Check(s
) ||
996 PyString_GET_SIZE(s
) != 0)
997 err
= PyFile_WriteString(": ", f
);
999 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
1004 err
= PyFile_WriteString("\n", f
);
1006 /* If an error happened here, don't show it.
1007 XXX This is wrong, but too many callers rely on this behavior. */
1013 PyRun_String(char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
1015 return run_err_node(PyParser_SimpleParseString(str
, start
),
1016 "<string>", globals
, locals
, NULL
);
1020 PyRun_File(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1023 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
1027 PyRun_FileEx(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1028 PyObject
*locals
, int closeit
)
1030 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1033 return run_err_node(n
, filename
, globals
, locals
, NULL
);
1037 PyRun_StringFlags(char *str
, int start
, PyObject
*globals
, PyObject
*locals
,
1038 PyCompilerFlags
*flags
)
1040 return run_err_node(PyParser_SimpleParseStringFlags(
1041 str
, start
, PARSER_FLAGS(flags
)),
1042 "<string>", globals
, locals
, flags
);
1046 PyRun_FileFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1047 PyObject
*locals
, PyCompilerFlags
*flags
)
1049 return PyRun_FileExFlags(fp
, filename
, start
, globals
, locals
, 0,
1054 PyRun_FileExFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1055 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1057 node
*n
= PyParser_SimpleParseFileFlags(fp
, filename
, start
,
1058 PARSER_FLAGS(flags
));
1061 return run_err_node(n
, filename
, globals
, locals
, flags
);
1065 run_err_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1066 PyCompilerFlags
*flags
)
1070 return run_node(n
, filename
, globals
, locals
, flags
);
1074 run_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1075 PyCompilerFlags
*flags
)
1079 co
= PyNode_CompileFlags(n
, filename
, flags
);
1083 v
= PyEval_EvalCode(co
, globals
, locals
);
1089 run_pyc_file(FILE *fp
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1090 PyCompilerFlags
*flags
)
1095 long PyImport_GetMagicNumber(void);
1097 magic
= PyMarshal_ReadLongFromFile(fp
);
1098 if (magic
!= PyImport_GetMagicNumber()) {
1099 PyErr_SetString(PyExc_RuntimeError
,
1100 "Bad magic number in .pyc file");
1103 (void) PyMarshal_ReadLongFromFile(fp
);
1104 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1106 if (v
== NULL
|| !PyCode_Check(v
)) {
1108 PyErr_SetString(PyExc_RuntimeError
,
1109 "Bad code object in .pyc file");
1112 co
= (PyCodeObject
*)v
;
1113 v
= PyEval_EvalCode(co
, globals
, locals
);
1115 flags
->cf_flags
|= (co
->co_flags
& PyCF_MASK
);
1121 Py_CompileString(char *str
, char *filename
, int start
)
1123 return Py_CompileStringFlags(str
, filename
, start
, NULL
);
1127 Py_CompileStringFlags(char *str
, char *filename
, int start
,
1128 PyCompilerFlags
*flags
)
1133 n
= PyParser_SimpleParseStringFlagsFilename(str
, filename
, start
,
1134 PARSER_FLAGS(flags
));
1137 co
= PyNode_CompileFlags(n
, filename
, flags
);
1139 return (PyObject
*)co
;
1143 Py_SymtableString(char *str
, char *filename
, int start
)
1146 struct symtable
*st
;
1147 n
= PyParser_SimpleParseStringFlagsFilename(str
, filename
,
1151 st
= PyNode_CompileSymtable(n
, filename
);
1156 /* Simplified interface to parsefile -- return node or set exception */
1159 PyParser_SimpleParseFileFlags(FILE *fp
, char *filename
, int start
, int flags
)
1163 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
, start
,
1164 (char *)0, (char *)0, &err
, flags
);
1171 PyParser_SimpleParseFile(FILE *fp
, char *filename
, int start
)
1173 return PyParser_SimpleParseFileFlags(fp
, filename
, start
, 0);
1176 /* Simplified interface to parsestring -- return node or set exception */
1179 PyParser_SimpleParseStringFlags(char *str
, int start
, int flags
)
1183 n
= PyParser_ParseStringFlags(str
, &_PyParser_Grammar
, start
, &err
,
1191 PyParser_SimpleParseString(char *str
, int start
)
1193 return PyParser_SimpleParseStringFlags(str
, start
, 0);
1197 PyParser_SimpleParseStringFlagsFilename(char *str
, char *filename
,
1198 int start
, int flags
)
1203 n
= PyParser_ParseStringFlagsFilename(str
, filename
,
1205 start
, &err
, flags
);
1212 PyParser_SimpleParseStringFilename(char *str
, char *filename
, int start
)
1214 return PyParser_SimpleParseStringFlagsFilename(str
, filename
,
1218 /* Set the error appropriate to the given input error code (see errcode.h) */
1221 err_input(perrdetail
*err
)
1223 PyObject
*v
, *w
, *errtype
;
1225 errtype
= PyExc_SyntaxError
;
1226 v
= Py_BuildValue("(ziiz)", err
->filename
,
1227 err
->lineno
, err
->offset
, err
->text
);
1228 if (err
->text
!= NULL
) {
1229 PyMem_DEL(err
->text
);
1232 switch (err
->error
) {
1234 errtype
= PyExc_IndentationError
;
1235 if (err
->expected
== INDENT
)
1236 msg
= "expected an indented block";
1237 else if (err
->token
== INDENT
)
1238 msg
= "unexpected indent";
1239 else if (err
->token
== DEDENT
)
1240 msg
= "unexpected unindent";
1242 errtype
= PyExc_SyntaxError
;
1243 msg
= "invalid syntax";
1247 msg
= "invalid token";
1250 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1258 msg
= "unexpected EOF while parsing";
1261 errtype
= PyExc_TabError
;
1262 msg
= "inconsistent use of tabs and spaces in indentation";
1265 msg
= "expression too long";
1268 errtype
= PyExc_IndentationError
;
1269 msg
= "unindent does not match any outer indentation level";
1272 errtype
= PyExc_IndentationError
;
1273 msg
= "too many levels of indentation";
1276 fprintf(stderr
, "error=%d\n", err
->error
);
1277 msg
= "unknown parsing error";
1280 w
= Py_BuildValue("(sO)", msg
, v
);
1282 PyErr_SetObject(errtype
, w
);
1286 /* Print fatal error message and abort */
1289 Py_FatalError(const char *msg
)
1291 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1296 OutputDebugString("Fatal Python error: ");
1297 OutputDebugString(msg
);
1298 OutputDebugString("\n");
1302 #endif /* MS_WINDOWS */
1306 /* Clean up and exit */
1309 #include "pythread.h"
1310 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1313 #define NEXITFUNCS 32
1314 static void (*exitfuncs
[NEXITFUNCS
])(void);
1315 static int nexitfuncs
= 0;
1317 int Py_AtExit(void (*func
)(void))
1319 if (nexitfuncs
>= NEXITFUNCS
)
1321 exitfuncs
[nexitfuncs
++] = func
;
1326 call_sys_exitfunc(void)
1328 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1332 Py_INCREF(exitfunc
);
1333 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1334 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1336 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1337 PySys_WriteStderr("Error in sys.exitfunc:\n");
1341 Py_DECREF(exitfunc
);
1349 call_ll_exitfuncs(void)
1351 while (nexitfuncs
> 0)
1352 (*exitfuncs
[--nexitfuncs
])();
1373 #ifdef HAVE_SIGNAL_H
1375 signal(SIGPIPE
, SIG_IGN
);
1378 signal(SIGXFZ
, SIG_IGN
);
1381 signal(SIGXFSZ
, SIG_IGN
);
1383 #endif /* HAVE_SIGNAL_H */
1384 PyOS_InitInterrupts(); /* May imply initsignal() */
1389 /* Check for file descriptor connected to interactive device.
1390 Pretend that stdin is always interactive, other files never. */
1395 return fd
== fileno(stdin
);
1401 * The file descriptor fd is considered ``interactive'' if either
1402 * a) isatty(fd) is TRUE, or
1403 * b) the -i flag was given, and the filename associated with
1404 * the descriptor is NULL or "<stdin>" or "???".
1407 Py_FdIsInteractive(FILE *fp
, char *filename
)
1409 if (isatty((int)fileno(fp
)))
1411 if (!Py_InteractiveFlag
)
1413 return (filename
== NULL
) ||
1414 (strcmp(filename
, "<stdin>") == 0) ||
1415 (strcmp(filename
, "???") == 0);
1419 #if defined(USE_STACKCHECK)
1420 #if defined(WIN32) && defined(_MSC_VER)
1422 /* Stack checking for Microsoft C */
1428 * Return non-zero when we run out of memory on the stack; zero otherwise.
1431 PyOS_CheckStack(void)
1434 /* _alloca throws a stack overflow exception if there's
1435 not enough space left on the stack */
1436 _alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1438 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1439 /* just ignore all errors */
1444 #endif /* WIN32 && _MSC_VER */
1446 /* Alternate implementations can be added here... */
1448 #endif /* USE_STACKCHECK */
1451 /* Wrappers around sigaction() or signal(). */
1454 PyOS_getsig(int sig
)
1456 #ifdef HAVE_SIGACTION
1457 struct sigaction context
;
1458 /* Initialize context.sa_handler to SIG_ERR which makes about as
1459 * much sense as anything else. It should get overwritten if
1460 * sigaction actually succeeds and otherwise we avoid an
1461 * uninitialized memory read.
1463 context
.sa_handler
= SIG_ERR
;
1464 sigaction(sig
, NULL
, &context
);
1465 return context
.sa_handler
;
1467 PyOS_sighandler_t handler
;
1468 handler
= signal(sig
, SIG_IGN
);
1469 signal(sig
, handler
);
1475 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1477 #ifdef HAVE_SIGACTION
1478 struct sigaction context
;
1479 PyOS_sighandler_t oldhandler
;
1480 /* Initialize context.sa_handler to SIG_ERR which makes about as
1481 * much sense as anything else. It should get overwritten if
1482 * sigaction actually succeeds and otherwise we avoid an
1483 * uninitialized memory read.
1485 context
.sa_handler
= SIG_ERR
;
1486 sigaction(sig
, NULL
, &context
);
1487 oldhandler
= context
.sa_handler
;
1488 context
.sa_handler
= handler
;
1489 sigaction(sig
, &context
, NULL
);
1492 return signal(sig
, handler
);