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);
47 int _Py_AskYesNo(char *prompt
);
50 extern void _PyUnicode_Init(void);
51 extern void _PyUnicode_Fini(void);
52 extern void _PyCodecRegistry_Init(void);
53 extern void _PyCodecRegistry_Fini(void);
55 int Py_DebugFlag
; /* Needed by parser.c */
56 int Py_VerboseFlag
; /* Needed by import.c */
57 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
58 int Py_NoSiteFlag
; /* Suppress 'import site' */
59 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c: deprecated */
60 int Py_FrozenFlag
; /* Needed by getpath.c */
61 int Py_UnicodeFlag
= 0; /* Needed by compile.c */
62 int Py_IgnoreEnvironmentFlag
; /* e.g. PYTHONPATH, PYTHONHOME */
63 /* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
64 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
65 true divisions (which they will be in 2.3). */
68 static int initialized
= 0;
70 /* API to access the initialized flag -- useful for esoteric use */
73 Py_IsInitialized(void)
78 /* Global initializations. Can be undone by Py_Finalize(). Don't
79 call this twice without an intervening Py_Finalize() call. When
80 initializations fail, a fatal error is issued and the function does
81 not return. On return, the first thread and interpreter state have
84 Locking: you must hold the interpreter lock while calling this.
85 (If the lock has not yet been initialized, that's equivalent to
86 having the lock, but you cannot use multiple threads.)
91 add_flag(int flag
, const char *envs
)
104 PyInterpreterState
*interp
;
105 PyThreadState
*tstate
;
106 PyObject
*bimod
, *sysmod
;
108 extern void _Py_ReadyTypes(void);
114 if ((p
= Py_GETENV("PYTHONDEBUG")) && *p
!= '\0')
115 Py_DebugFlag
= add_flag(Py_DebugFlag
, p
);
116 if ((p
= Py_GETENV("PYTHONVERBOSE")) && *p
!= '\0')
117 Py_VerboseFlag
= add_flag(Py_VerboseFlag
, p
);
118 if ((p
= Py_GETENV("PYTHONOPTIMIZE")) && *p
!= '\0')
119 Py_OptimizeFlag
= add_flag(Py_OptimizeFlag
, p
);
121 interp
= PyInterpreterState_New();
123 Py_FatalError("Py_Initialize: can't make first interpreter");
125 tstate
= PyThreadState_New(interp
);
127 Py_FatalError("Py_Initialize: can't make first thread");
128 (void) PyThreadState_Swap(tstate
);
132 interp
->modules
= PyDict_New();
133 if (interp
->modules
== NULL
)
134 Py_FatalError("Py_Initialize: can't make modules dictionary");
136 /* Init codec registry */
137 _PyCodecRegistry_Init();
139 #ifdef Py_USING_UNICODE
140 /* Init Unicode implementation; relies on the codec registry */
144 bimod
= _PyBuiltin_Init();
146 Py_FatalError("Py_Initialize: can't initialize __builtin__");
147 interp
->builtins
= PyModule_GetDict(bimod
);
148 Py_INCREF(interp
->builtins
);
150 sysmod
= _PySys_Init();
152 Py_FatalError("Py_Initialize: can't initialize sys");
153 interp
->sysdict
= PyModule_GetDict(sysmod
);
154 Py_INCREF(interp
->sysdict
);
155 _PyImport_FixupExtension("sys", "sys");
156 PySys_SetPath(Py_GetPath());
157 PyDict_SetItemString(interp
->sysdict
, "modules",
162 /* initialize builtin exceptions */
164 _PyImport_FixupExtension("exceptions", "exceptions");
166 /* phase 2 of builtins */
167 _PyImport_FixupExtension("__builtin__", "__builtin__");
169 initsigs(); /* Signal handling stuff, including initintr() */
171 initmain(); /* Module __main__ */
173 initsite(); /* Module site */
177 extern void dump_counts(void);
180 /* Undo the effect of Py_Initialize().
182 Beware: if multiple interpreter and/or thread states exist, these
183 are not wiped out; only the current thread and interpreter state
184 are deleted. But since everything else is deleted, those other
185 interpreter and thread states should no longer be used.
187 (XXX We should do better, e.g. wipe out all interpreters and
197 PyInterpreterState
*interp
;
198 PyThreadState
*tstate
;
203 /* The interpreter is still entirely intact at this point, and the
204 * exit funcs may be relying on that. In particular, if some thread
205 * or exit func is still waiting to do an import, the import machinery
206 * expects Py_IsInitialized() to return true. So don't say the
207 * interpreter is uninitialized until after the exit funcs have run.
208 * Note that Threading.py uses an exit func to do a join on all the
209 * threads created thru it, so this also protects pending imports in
210 * the threads created via Threading.
215 /* Get current thread state and interpreter pointer */
216 tstate
= PyThreadState_Get();
217 interp
= tstate
->interp
;
219 /* Disable signal handling */
220 PyOS_FiniInterrupts();
222 /* Cleanup Codec registry */
223 _PyCodecRegistry_Fini();
225 /* Destroy all modules */
228 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
231 /* Debugging stuff */
237 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
241 if (Py_GETENV("PYTHONDUMPREFS")) {
242 _Py_PrintReferences(stderr
);
244 #endif /* Py_TRACE_REFS */
246 /* Now we decref the exception classes. After this point nothing
247 can raise an exception. That's okay, because each Fini() method
248 below has been checked to make sure no exceptions are ever
253 /* Delete current thread */
254 PyInterpreterState_Clear(interp
);
255 PyThreadState_Swap(NULL
);
256 PyInterpreterState_Delete(interp
);
266 #ifdef Py_USING_UNICODE
267 /* Cleanup Unicode implementation */
271 /* XXX Still allocated:
272 - various static ad-hoc pointers to interned strings
273 - int and float free list blocks
274 - whatever various modules and libraries allocate
277 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
279 #ifdef PYMALLOC_DEBUG
280 if (Py_GETENV("PYTHONMALLOCSTATS"))
281 _PyObject_DebugMallocStats();
287 _Py_ResetReferences();
288 #endif /* Py_TRACE_REFS */
291 /* Create and initialize a new interpreter and thread, and return the
292 new thread. This requires that Py_Initialize() has been called
295 Unsuccessful initialization yields a NULL pointer. Note that *no*
296 exception information is available even in this case -- the
297 exception information is held in the thread, and there is no
305 Py_NewInterpreter(void)
307 PyInterpreterState
*interp
;
308 PyThreadState
*tstate
, *save_tstate
;
309 PyObject
*bimod
, *sysmod
;
312 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
314 interp
= PyInterpreterState_New();
318 tstate
= PyThreadState_New(interp
);
319 if (tstate
== NULL
) {
320 PyInterpreterState_Delete(interp
);
324 save_tstate
= PyThreadState_Swap(tstate
);
326 /* XXX The following is lax in error checking */
328 interp
->modules
= PyDict_New();
330 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
332 interp
->builtins
= PyModule_GetDict(bimod
);
333 Py_INCREF(interp
->builtins
);
335 sysmod
= _PyImport_FindExtension("sys", "sys");
336 if (bimod
!= NULL
&& sysmod
!= NULL
) {
337 interp
->sysdict
= PyModule_GetDict(sysmod
);
338 Py_INCREF(interp
->sysdict
);
339 PySys_SetPath(Py_GetPath());
340 PyDict_SetItemString(interp
->sysdict
, "modules",
347 if (!PyErr_Occurred())
350 /* Oops, it didn't work. Undo it all. */
353 PyThreadState_Clear(tstate
);
354 PyThreadState_Swap(save_tstate
);
355 PyThreadState_Delete(tstate
);
356 PyInterpreterState_Delete(interp
);
361 /* Delete an interpreter and its last thread. This requires that the
362 given thread state is current, that the thread has no remaining
363 frames, and that it is its interpreter's only remaining thread.
364 It is a fatal error to violate these constraints.
366 (Py_Finalize() doesn't have these constraints -- it zaps
367 everything, regardless.)
374 Py_EndInterpreter(PyThreadState
*tstate
)
376 PyInterpreterState
*interp
= tstate
->interp
;
378 if (tstate
!= PyThreadState_Get())
379 Py_FatalError("Py_EndInterpreter: thread is not current");
380 if (tstate
->frame
!= NULL
)
381 Py_FatalError("Py_EndInterpreter: thread still has a frame");
382 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
383 Py_FatalError("Py_EndInterpreter: not the last thread");
386 PyInterpreterState_Clear(interp
);
387 PyThreadState_Swap(NULL
);
388 PyInterpreterState_Delete(interp
);
391 static char *progname
= "python";
394 Py_SetProgramName(char *pn
)
401 Py_GetProgramName(void)
406 static char *default_home
= NULL
;
409 Py_SetPythonHome(char *home
)
415 Py_GetPythonHome(void)
417 char *home
= default_home
;
418 if (home
== NULL
&& !Py_IgnoreEnvironmentFlag
)
419 home
= Py_GETENV("PYTHONHOME");
423 /* Create __main__ module */
429 m
= PyImport_AddModule("__main__");
431 Py_FatalError("can't create __main__ module");
432 d
= PyModule_GetDict(m
);
433 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
434 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
436 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
437 Py_FatalError("can't add __builtins__ to __main__");
442 /* Import the site module (not into __main__ though) */
448 m
= PyImport_ImportModule("site");
450 f
= PySys_GetObject("stderr");
451 if (Py_VerboseFlag
) {
453 "'import site' failed; traceback:\n", f
);
458 "'import site' failed; use -v for traceback\n", f
);
467 /* Parse input from a file and execute it */
470 PyRun_AnyFile(FILE *fp
, char *filename
)
472 return PyRun_AnyFileExFlags(fp
, filename
, 0, NULL
);
476 PyRun_AnyFileFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
478 return PyRun_AnyFileExFlags(fp
, filename
, 0, flags
);
482 PyRun_AnyFileEx(FILE *fp
, char *filename
, int closeit
)
484 return PyRun_AnyFileExFlags(fp
, filename
, closeit
, NULL
);
488 PyRun_AnyFileExFlags(FILE *fp
, char *filename
, int closeit
,
489 PyCompilerFlags
*flags
)
491 if (filename
== NULL
)
493 if (Py_FdIsInteractive(fp
, filename
)) {
494 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
500 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
504 PyRun_InteractiveLoop(FILE *fp
, char *filename
)
506 return PyRun_InteractiveLoopFlags(fp
, filename
, NULL
);
510 PyRun_InteractiveLoopFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
514 PyCompilerFlags local_flags
;
517 flags
= &local_flags
;
518 local_flags
.cf_flags
= 0;
520 v
= PySys_GetObject("ps1");
522 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
525 v
= PySys_GetObject("ps2");
527 PySys_SetObject("ps2", v
= PyString_FromString("... "));
531 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
533 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
545 PyRun_InteractiveOne(FILE *fp
, char *filename
)
547 return PyRun_InteractiveOneFlags(fp
, filename
, NULL
);
550 /* compute parser flags based on compiler flags */
551 #if 0 /* future keyword */
552 #define PARSER_FLAGS(flags) \
553 (((flags) && (flags)->cf_flags & CO_GENERATOR_ALLOWED) ? \
554 PyPARSE_YIELD_IS_KEYWORD : 0)
556 #define PARSER_FLAGS(flags) 0
560 PyRun_InteractiveOneFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
562 PyObject
*m
, *d
, *v
, *w
;
565 char *ps1
= "", *ps2
= "";
567 v
= PySys_GetObject("ps1");
572 else if (PyString_Check(v
))
573 ps1
= PyString_AsString(v
);
575 w
= PySys_GetObject("ps2");
580 else if (PyString_Check(w
))
581 ps2
= PyString_AsString(w
);
583 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
,
584 Py_single_input
, ps1
, ps2
, &err
,
585 PARSER_FLAGS(flags
));
589 if (err
.error
== E_EOF
) {
598 m
= PyImport_AddModule("__main__");
601 d
= PyModule_GetDict(m
);
602 v
= run_node(n
, filename
, d
, d
, flags
);
614 PyRun_SimpleFile(FILE *fp
, char *filename
)
616 return PyRun_SimpleFileEx(fp
, filename
, 0);
619 /* Check whether a file maybe a pyc file: Look at the extension,
620 the file type, and, if we may close it, at the first few bytes. */
623 maybe_pyc_file(FILE *fp
, char* filename
, char* ext
, int closeit
)
625 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
629 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
630 if (PyMac_getfiletype(filename
) == 'PYC '
631 || PyMac_getfiletype(filename
) == 'APPL')
633 #endif /* macintosh */
635 /* Only look into the file if we are allowed to close it, since
636 it then should also be seekable. */
638 /* Read only two bytes of the magic. If the file was opened in
639 text mode, the bytes 3 and 4 of the magic (\r\n) might not
640 be read as they are on disk. */
641 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
642 unsigned char buf
[2];
643 /* Mess: In case of -x, the stream is NOT at its start now,
644 and ungetc() was used to push back the first newline,
645 which makes the current stream position formally undefined,
646 and a x-platform nightmare.
647 Unfortunately, we have no direct way to know whether -x
648 was specified. So we use a terrible hack: if the current
649 stream position is not 0, we assume -x was specified, and
650 give up. Bug 132850 on SourceForge spells out the
651 hopelessness of trying anything else (fseek and ftell
652 don't work predictably x-platform for text-mode files).
655 if (ftell(fp
) == 0) {
656 if (fread(buf
, 1, 2, fp
) == 2 &&
657 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
667 PyRun_SimpleFileEx(FILE *fp
, char *filename
, int closeit
)
669 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, NULL
);
673 PyRun_SimpleFileExFlags(FILE *fp
, char *filename
, int closeit
,
674 PyCompilerFlags
*flags
)
679 m
= PyImport_AddModule("__main__");
682 d
= PyModule_GetDict(m
);
683 ext
= filename
+ strlen(filename
) - 4;
684 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
685 /* Try to run a pyc file. First, re-open in binary */
688 if( (fp
= fopen(filename
, "rb")) == NULL
) {
689 fprintf(stderr
, "python: Can't reopen .pyc file\n");
692 /* Turn on optimization if a .pyo file is given */
693 if (strcmp(ext
, ".pyo") == 0)
695 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
697 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
711 PyRun_SimpleString(char *command
)
713 return PyRun_SimpleStringFlags(command
, NULL
);
717 PyRun_SimpleStringFlags(char *command
, PyCompilerFlags
*flags
)
720 m
= PyImport_AddModule("__main__");
723 d
= PyModule_GetDict(m
);
724 v
= PyRun_StringFlags(command
, Py_file_input
, d
, d
, flags
);
736 parse_syntax_error(PyObject
*err
, PyObject
**message
, char **filename
,
737 int *lineno
, int *offset
, char **text
)
742 /* old style errors */
743 if (PyTuple_Check(err
))
744 return PyArg_ParseTuple(err
, "O(ziiz)", message
, filename
,
745 lineno
, offset
, text
);
747 /* new style errors. `err' is an instance */
749 if (! (v
= PyObject_GetAttrString(err
, "msg")))
753 if (!(v
= PyObject_GetAttrString(err
, "filename")))
757 else if (! (*filename
= PyString_AsString(v
)))
761 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
763 hold
= PyInt_AsLong(v
);
766 if (hold
< 0 && PyErr_Occurred())
770 if (!(v
= PyObject_GetAttrString(err
, "offset")))
777 hold
= PyInt_AsLong(v
);
780 if (hold
< 0 && PyErr_Occurred())
785 if (!(v
= PyObject_GetAttrString(err
, "text")))
789 else if (! (*text
= PyString_AsString(v
)))
806 print_error_text(PyObject
*f
, int offset
, char *text
)
810 if (offset
> 0 && offset
== (int)strlen(text
))
813 nl
= strchr(text
, '\n');
814 if (nl
== NULL
|| nl
-text
>= offset
)
816 offset
-= (nl
+1-text
);
819 while (*text
== ' ' || *text
== '\t') {
824 PyFile_WriteString(" ", f
);
825 PyFile_WriteString(text
, f
);
826 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
827 PyFile_WriteString("\n", f
);
830 PyFile_WriteString(" ", f
);
833 PyFile_WriteString(" ", f
);
836 PyFile_WriteString("^\n", f
);
840 handle_system_exit(void)
842 PyObject
*exception
, *value
, *tb
;
843 PyErr_Fetch(&exception
, &value
, &tb
);
847 if (value
== NULL
|| value
== Py_None
)
849 if (PyInstance_Check(value
)) {
850 /* The error code should be in the `code' attribute. */
851 PyObject
*code
= PyObject_GetAttrString(value
, "code");
855 if (value
== Py_None
)
858 /* If we failed to dig out the 'code' attribute,
859 just let the else clause below print the error. */
861 if (PyInt_Check(value
))
862 Py_Exit((int)PyInt_AsLong(value
));
864 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
865 PySys_WriteStderr("\n");
871 PyErr_PrintEx(int set_sys_last_vars
)
873 PyObject
*exception
, *v
, *tb
, *hook
;
875 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
876 handle_system_exit();
878 PyErr_Fetch(&exception
, &v
, &tb
);
879 PyErr_NormalizeException(&exception
, &v
, &tb
);
880 if (exception
== NULL
)
882 if (set_sys_last_vars
) {
883 PySys_SetObject("last_type", exception
);
884 PySys_SetObject("last_value", v
);
885 PySys_SetObject("last_traceback", tb
);
887 hook
= PySys_GetObject("excepthook");
889 PyObject
*args
= Py_BuildValue("(OOO)",
890 exception
, v
? v
: Py_None
, tb
? tb
: Py_None
);
891 PyObject
*result
= PyEval_CallObject(hook
, args
);
892 if (result
== NULL
) {
893 PyObject
*exception2
, *v2
, *tb2
;
894 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
895 handle_system_exit();
897 PyErr_Fetch(&exception2
, &v2
, &tb2
);
898 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
902 PySys_WriteStderr("Error in sys.excepthook:\n");
903 PyErr_Display(exception2
, v2
, tb2
);
904 PySys_WriteStderr("\nOriginal exception was:\n");
905 PyErr_Display(exception
, v
, tb
);
906 Py_XDECREF(exception2
);
913 PySys_WriteStderr("sys.excepthook is missing\n");
914 PyErr_Display(exception
, v
, tb
);
916 Py_XDECREF(exception
);
921 void PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
925 PyObject
*f
= PySys_GetObject("stderr");
927 fprintf(stderr
, "lost sys.stderr\n");
932 if (tb
&& tb
!= Py_None
)
933 err
= PyTraceBack_Print(tb
, f
);
935 PyObject_HasAttrString(v
, "print_file_and_line"))
938 char *filename
, *text
;
940 if (!parse_syntax_error(v
, &message
, &filename
,
941 &lineno
, &offset
, &text
))
945 PyFile_WriteString(" File \"", f
);
946 if (filename
== NULL
)
947 PyFile_WriteString("<string>", f
);
949 PyFile_WriteString(filename
, f
);
950 PyFile_WriteString("\", line ", f
);
951 PyOS_snprintf(buf
, sizeof(buf
), "%d", lineno
);
952 PyFile_WriteString(buf
, f
);
953 PyFile_WriteString("\n", f
);
955 print_error_text(f
, offset
, text
);
957 /* Can't be bothered to check all those
958 PyFile_WriteString() calls */
959 if (PyErr_Occurred())
964 /* Don't do anything else */
966 else if (PyClass_Check(exception
)) {
967 PyClassObject
* exc
= (PyClassObject
*)exception
;
968 PyObject
* className
= exc
->cl_name
;
969 PyObject
* moduleName
=
970 PyDict_GetItemString(exc
->cl_dict
, "__module__");
972 if (moduleName
== NULL
)
973 err
= PyFile_WriteString("<unknown>", f
);
975 char* modstr
= PyString_AsString(moduleName
);
976 if (modstr
&& strcmp(modstr
, "exceptions"))
978 err
= PyFile_WriteString(modstr
, f
);
979 err
+= PyFile_WriteString(".", f
);
983 if (className
== NULL
)
984 err
= PyFile_WriteString("<unknown>", f
);
986 err
= PyFile_WriteObject(className
, f
,
991 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
993 if (v
!= NULL
&& v
!= Py_None
) {
994 PyObject
*s
= PyObject_Str(v
);
995 /* only print colon if the str() of the
996 object is not the empty string
1000 else if (!PyString_Check(s
) ||
1001 PyString_GET_SIZE(s
) != 0)
1002 err
= PyFile_WriteString(": ", f
);
1004 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
1009 err
= PyFile_WriteString("\n", f
);
1011 /* If an error happened here, don't show it.
1012 XXX This is wrong, but too many callers rely on this behavior. */
1018 PyRun_String(char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
1020 return run_err_node(PyParser_SimpleParseString(str
, start
),
1021 "<string>", globals
, locals
, NULL
);
1025 PyRun_File(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1028 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
1032 PyRun_FileEx(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1033 PyObject
*locals
, int closeit
)
1035 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1038 return run_err_node(n
, filename
, globals
, locals
, NULL
);
1042 PyRun_StringFlags(char *str
, int start
, PyObject
*globals
, PyObject
*locals
,
1043 PyCompilerFlags
*flags
)
1045 return run_err_node(PyParser_SimpleParseStringFlags(
1046 str
, start
, PARSER_FLAGS(flags
)),
1047 "<string>", globals
, locals
, flags
);
1051 PyRun_FileFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1052 PyObject
*locals
, PyCompilerFlags
*flags
)
1054 return PyRun_FileExFlags(fp
, filename
, start
, globals
, locals
, 0,
1059 PyRun_FileExFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1060 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1062 node
*n
= PyParser_SimpleParseFileFlags(fp
, filename
, start
,
1063 PARSER_FLAGS(flags
));
1066 return run_err_node(n
, filename
, globals
, locals
, flags
);
1070 run_err_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1071 PyCompilerFlags
*flags
)
1075 return run_node(n
, filename
, globals
, locals
, flags
);
1079 run_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1080 PyCompilerFlags
*flags
)
1084 co
= PyNode_CompileFlags(n
, filename
, flags
);
1088 v
= PyEval_EvalCode(co
, globals
, locals
);
1094 run_pyc_file(FILE *fp
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1095 PyCompilerFlags
*flags
)
1100 long PyImport_GetMagicNumber(void);
1102 magic
= PyMarshal_ReadLongFromFile(fp
);
1103 if (magic
!= PyImport_GetMagicNumber()) {
1104 PyErr_SetString(PyExc_RuntimeError
,
1105 "Bad magic number in .pyc file");
1108 (void) PyMarshal_ReadLongFromFile(fp
);
1109 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1111 if (v
== NULL
|| !PyCode_Check(v
)) {
1113 PyErr_SetString(PyExc_RuntimeError
,
1114 "Bad code object in .pyc file");
1117 co
= (PyCodeObject
*)v
;
1118 v
= PyEval_EvalCode(co
, globals
, locals
);
1120 flags
->cf_flags
|= (co
->co_flags
& PyCF_MASK
);
1126 Py_CompileString(char *str
, char *filename
, int start
)
1128 return Py_CompileStringFlags(str
, filename
, start
, NULL
);
1132 Py_CompileStringFlags(char *str
, char *filename
, int start
,
1133 PyCompilerFlags
*flags
)
1137 n
= PyParser_SimpleParseStringFlags(str
, start
, PARSER_FLAGS(flags
));
1140 co
= PyNode_CompileFlags(n
, filename
, flags
);
1142 return (PyObject
*)co
;
1146 Py_SymtableString(char *str
, char *filename
, int start
)
1149 struct symtable
*st
;
1150 n
= PyParser_SimpleParseString(str
, start
);
1153 st
= PyNode_CompileSymtable(n
, filename
);
1158 /* Simplified interface to parsefile -- return node or set exception */
1161 PyParser_SimpleParseFileFlags(FILE *fp
, char *filename
, int start
, int flags
)
1165 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
, start
,
1166 (char *)0, (char *)0, &err
, flags
);
1173 PyParser_SimpleParseFile(FILE *fp
, char *filename
, int start
)
1175 return PyParser_SimpleParseFileFlags(fp
, filename
, start
, 0);
1178 /* Simplified interface to parsestring -- return node or set exception */
1181 PyParser_SimpleParseStringFlags(char *str
, int start
, int flags
)
1185 n
= PyParser_ParseStringFlags(str
, &_PyParser_Grammar
, start
, &err
,
1193 PyParser_SimpleParseString(char *str
, int start
)
1195 return PyParser_SimpleParseStringFlags(str
, start
, 0);
1198 /* Set the error appropriate to the given input error code (see errcode.h) */
1201 err_input(perrdetail
*err
)
1203 PyObject
*v
, *w
, *errtype
;
1205 errtype
= PyExc_SyntaxError
;
1206 v
= Py_BuildValue("(ziiz)", err
->filename
,
1207 err
->lineno
, err
->offset
, err
->text
);
1208 if (err
->text
!= NULL
) {
1209 PyMem_DEL(err
->text
);
1212 switch (err
->error
) {
1214 errtype
= PyExc_IndentationError
;
1215 if (err
->expected
== INDENT
)
1216 msg
= "expected an indented block";
1217 else if (err
->token
== INDENT
)
1218 msg
= "unexpected indent";
1219 else if (err
->token
== DEDENT
)
1220 msg
= "unexpected unindent";
1222 errtype
= PyExc_SyntaxError
;
1223 msg
= "invalid syntax";
1227 msg
= "invalid token";
1230 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1238 msg
= "unexpected EOF while parsing";
1241 errtype
= PyExc_TabError
;
1242 msg
= "inconsistent use of tabs and spaces in indentation";
1245 msg
= "expression too long";
1248 errtype
= PyExc_IndentationError
;
1249 msg
= "unindent does not match any outer indentation level";
1252 errtype
= PyExc_IndentationError
;
1253 msg
= "too many levels of indentation";
1256 fprintf(stderr
, "error=%d\n", err
->error
);
1257 msg
= "unknown parsing error";
1260 w
= Py_BuildValue("(sO)", msg
, v
);
1262 PyErr_SetObject(errtype
, w
);
1266 /* Print fatal error message and abort */
1269 Py_FatalError(char *msg
)
1271 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1276 OutputDebugString("Fatal Python error: ");
1277 OutputDebugString(msg
);
1278 OutputDebugString("\n");
1282 #endif /* MS_WIN32 */
1286 /* Clean up and exit */
1289 #include "pythread.h"
1290 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1293 #define NEXITFUNCS 32
1294 static void (*exitfuncs
[NEXITFUNCS
])(void);
1295 static int nexitfuncs
= 0;
1297 int Py_AtExit(void (*func
)(void))
1299 if (nexitfuncs
>= NEXITFUNCS
)
1301 exitfuncs
[nexitfuncs
++] = func
;
1306 call_sys_exitfunc(void)
1308 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1312 Py_INCREF(exitfunc
);
1313 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1314 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1316 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1317 PySys_WriteStderr("Error in sys.exitfunc:\n");
1321 Py_DECREF(exitfunc
);
1329 call_ll_exitfuncs(void)
1331 while (nexitfuncs
> 0)
1332 (*exitfuncs
[--nexitfuncs
])();
1353 #ifdef HAVE_SIGNAL_H
1355 signal(SIGPIPE
, SIG_IGN
);
1358 signal(SIGXFZ
, SIG_IGN
);
1361 signal(SIGXFSZ
, SIG_IGN
);
1363 #endif /* HAVE_SIGNAL_H */
1364 PyOS_InitInterrupts(); /* May imply initsignal() */
1367 #ifdef Py_TRACE_REFS
1368 /* Ask a yes/no question */
1371 _Py_AskYesNo(char *prompt
)
1375 fprintf(stderr
, "%s [ny] ", prompt
);
1376 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1378 return buf
[0] == 'y' || buf
[0] == 'Y';
1384 /* Check for file descriptor connected to interactive device.
1385 Pretend that stdin is always interactive, other files never. */
1390 return fd
== fileno(stdin
);
1396 * The file descriptor fd is considered ``interactive'' if either
1397 * a) isatty(fd) is TRUE, or
1398 * b) the -i flag was given, and the filename associated with
1399 * the descriptor is NULL or "<stdin>" or "???".
1402 Py_FdIsInteractive(FILE *fp
, char *filename
)
1404 if (isatty((int)fileno(fp
)))
1406 if (!Py_InteractiveFlag
)
1408 return (filename
== NULL
) ||
1409 (strcmp(filename
, "<stdin>") == 0) ||
1410 (strcmp(filename
, "???") == 0);
1414 #if defined(USE_STACKCHECK)
1415 #if defined(WIN32) && defined(_MSC_VER)
1417 /* Stack checking for Microsoft C */
1423 * Return non-zero when we run out of memory on the stack; zero otherwise.
1426 PyOS_CheckStack(void)
1429 /* _alloca throws a stack overflow exception if there's
1430 not enough space left on the stack */
1431 _alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1433 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1434 /* just ignore all errors */
1439 #endif /* WIN32 && _MSC_VER */
1441 /* Alternate implementations can be added here... */
1443 #endif /* USE_STACKCHECK */
1446 /* Wrappers around sigaction() or signal(). */
1449 PyOS_getsig(int sig
)
1451 #ifdef HAVE_SIGACTION
1452 struct sigaction context
;
1453 /* Initialize context.sa_handler to SIG_ERR which makes about as
1454 * much sense as anything else. It should get overwritten if
1455 * sigaction actually succeeds and otherwise we avoid an
1456 * uninitialized memory read.
1458 context
.sa_handler
= SIG_ERR
;
1459 sigaction(sig
, NULL
, &context
);
1460 return context
.sa_handler
;
1462 PyOS_sighandler_t handler
;
1463 handler
= signal(sig
, SIG_IGN
);
1464 signal(sig
, handler
);
1470 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1472 #ifdef HAVE_SIGACTION
1473 struct sigaction context
;
1474 PyOS_sighandler_t oldhandler
;
1475 /* Initialize context.sa_handler to SIG_ERR which makes about as
1476 * much sense as anything else. It should get overwritten if
1477 * sigaction actually succeeds and otherwise we avoid an
1478 * uninitialized memory read.
1480 context
.sa_handler
= SIG_ERR
;
1481 sigaction(sig
, NULL
, &context
);
1482 oldhandler
= context
.sa_handler
;
1483 context
.sa_handler
= handler
;
1484 sigaction(sig
, &context
, NULL
);
1487 return signal(sig
, handler
);