2 /* Python interpreter top-level routines, including init/exit */
32 extern char *Py_GetPath(void);
34 extern grammar _PyParser_Grammar
; /* From graminit.c */
37 static void initmain(void);
38 static void initsite(void);
39 static PyObject
*run_err_node(node
*, char *, PyObject
*, PyObject
*,
41 static PyObject
*run_node(node
*, char *, PyObject
*, PyObject
*,
43 static PyObject
*run_pyc_file(FILE *, char *, PyObject
*, PyObject
*,
45 static void err_input(perrdetail
*);
46 static void initsigs(void);
47 static void call_sys_exitfunc(void);
48 static void call_ll_exitfuncs(void);
51 int _Py_AskYesNo(char *prompt
);
54 extern void _PyUnicode_Init(void);
55 extern void _PyUnicode_Fini(void);
56 extern void _PyCodecRegistry_Init(void);
57 extern void _PyCodecRegistry_Fini(void);
59 int Py_DebugFlag
; /* Needed by parser.c */
60 int Py_VerboseFlag
; /* Needed by import.c */
61 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
62 int Py_NoSiteFlag
; /* Suppress 'import site' */
63 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c: deprecated */
64 int Py_FrozenFlag
; /* Needed by getpath.c */
65 int Py_UnicodeFlag
= 0; /* Needed by compile.c */
66 int Py_IgnoreEnvironmentFlag
; /* e.g. PYTHONPATH, PYTHONHOME */
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.)
93 PyInterpreterState
*interp
;
94 PyThreadState
*tstate
;
95 PyObject
*bimod
, *sysmod
;
97 extern void _Py_ReadyTypes(void);
103 if ((p
= Py_GETENV("PYTHONDEBUG")) && *p
!= '\0')
104 Py_DebugFlag
= Py_DebugFlag
? Py_DebugFlag
: 1;
105 if ((p
= Py_GETENV("PYTHONVERBOSE")) && *p
!= '\0')
106 Py_VerboseFlag
= Py_VerboseFlag
? Py_VerboseFlag
: 1;
107 if ((p
= Py_GETENV("PYTHONOPTIMIZE")) && *p
!= '\0')
108 Py_OptimizeFlag
= Py_OptimizeFlag
? Py_OptimizeFlag
: 1;
110 interp
= PyInterpreterState_New();
112 Py_FatalError("Py_Initialize: can't make first interpreter");
114 tstate
= PyThreadState_New(interp
);
116 Py_FatalError("Py_Initialize: can't make first thread");
117 (void) PyThreadState_Swap(tstate
);
121 interp
->modules
= PyDict_New();
122 if (interp
->modules
== NULL
)
123 Py_FatalError("Py_Initialize: can't make modules dictionary");
125 /* Init codec registry */
126 _PyCodecRegistry_Init();
128 #ifdef Py_USING_UNICODE
129 /* Init Unicode implementation; relies on the codec registry */
133 bimod
= _PyBuiltin_Init();
135 Py_FatalError("Py_Initialize: can't initialize __builtin__");
136 interp
->builtins
= PyModule_GetDict(bimod
);
137 Py_INCREF(interp
->builtins
);
139 sysmod
= _PySys_Init();
141 Py_FatalError("Py_Initialize: can't initialize sys");
142 interp
->sysdict
= PyModule_GetDict(sysmod
);
143 Py_INCREF(interp
->sysdict
);
144 _PyImport_FixupExtension("sys", "sys");
145 PySys_SetPath(Py_GetPath());
146 PyDict_SetItemString(interp
->sysdict
, "modules",
151 /* initialize builtin exceptions */
153 _PyImport_FixupExtension("exceptions", "exceptions");
155 /* phase 2 of builtins */
156 _PyImport_FixupExtension("__builtin__", "__builtin__");
158 initsigs(); /* Signal handling stuff, including initintr() */
160 initmain(); /* Module __main__ */
162 initsite(); /* Module site */
166 extern void dump_counts(void);
169 /* Undo the effect of Py_Initialize().
171 Beware: if multiple interpreter and/or thread states exist, these
172 are not wiped out; only the current thread and interpreter state
173 are deleted. But since everything else is deleted, those other
174 interpreter and thread states should no longer be used.
176 (XXX We should do better, e.g. wipe out all interpreters and
186 PyInterpreterState
*interp
;
187 PyThreadState
*tstate
;
192 /* The interpreter is still entirely intact at this point, and the
193 * exit funcs may be relying on that. In particular, if some thread
194 * or exit func is still waiting to do an import, the import machinery
195 * expects Py_IsInitialized() to return true. So don't say the
196 * interpreter is uninitialized until after the exit funcs have run.
197 * Note that Threading.py uses an exit func to do a join on all the
198 * threads created thru it, so this also protects pending imports in
199 * the threads created via Threading.
204 /* Get current thread state and interpreter pointer */
205 tstate
= PyThreadState_Get();
206 interp
= tstate
->interp
;
208 /* Disable signal handling */
209 PyOS_FiniInterrupts();
211 #ifdef Py_USING_UNICODE
212 /* Cleanup Unicode implementation */
216 /* Cleanup Codec registry */
217 _PyCodecRegistry_Fini();
219 /* Destroy all modules */
222 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
225 /* Debugging stuff */
231 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
235 if (Py_GETENV("PYTHONDUMPREFS")) {
236 _Py_PrintReferences(stderr
);
238 #endif /* Py_TRACE_REFS */
240 /* Now we decref the exception classes. After this point nothing
241 can raise an exception. That's okay, because each Fini() method
242 below has been checked to make sure no exceptions are ever
247 /* Delete current thread */
248 PyInterpreterState_Clear(interp
);
249 PyThreadState_Swap(NULL
);
250 PyInterpreterState_Delete(interp
);
260 /* XXX Still allocated:
261 - various static ad-hoc pointers to interned strings
262 - int and float free list blocks
263 - whatever various modules and libraries allocate
266 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
271 _Py_ResetReferences();
272 #endif /* Py_TRACE_REFS */
275 /* Create and initialize a new interpreter and thread, and return the
276 new thread. This requires that Py_Initialize() has been called
279 Unsuccessful initialization yields a NULL pointer. Note that *no*
280 exception information is available even in this case -- the
281 exception information is held in the thread, and there is no
289 Py_NewInterpreter(void)
291 PyInterpreterState
*interp
;
292 PyThreadState
*tstate
, *save_tstate
;
293 PyObject
*bimod
, *sysmod
;
296 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
298 interp
= PyInterpreterState_New();
302 tstate
= PyThreadState_New(interp
);
303 if (tstate
== NULL
) {
304 PyInterpreterState_Delete(interp
);
308 save_tstate
= PyThreadState_Swap(tstate
);
310 /* XXX The following is lax in error checking */
312 interp
->modules
= PyDict_New();
314 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
316 interp
->builtins
= PyModule_GetDict(bimod
);
317 Py_INCREF(interp
->builtins
);
319 sysmod
= _PyImport_FindExtension("sys", "sys");
320 if (bimod
!= NULL
&& sysmod
!= NULL
) {
321 interp
->sysdict
= PyModule_GetDict(sysmod
);
322 Py_INCREF(interp
->sysdict
);
323 PySys_SetPath(Py_GetPath());
324 PyDict_SetItemString(interp
->sysdict
, "modules",
331 if (!PyErr_Occurred())
334 /* Oops, it didn't work. Undo it all. */
337 PyThreadState_Clear(tstate
);
338 PyThreadState_Swap(save_tstate
);
339 PyThreadState_Delete(tstate
);
340 PyInterpreterState_Delete(interp
);
345 /* Delete an interpreter and its last thread. This requires that the
346 given thread state is current, that the thread has no remaining
347 frames, and that it is its interpreter's only remaining thread.
348 It is a fatal error to violate these constraints.
350 (Py_Finalize() doesn't have these constraints -- it zaps
351 everything, regardless.)
358 Py_EndInterpreter(PyThreadState
*tstate
)
360 PyInterpreterState
*interp
= tstate
->interp
;
362 if (tstate
!= PyThreadState_Get())
363 Py_FatalError("Py_EndInterpreter: thread is not current");
364 if (tstate
->frame
!= NULL
)
365 Py_FatalError("Py_EndInterpreter: thread still has a frame");
366 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
367 Py_FatalError("Py_EndInterpreter: not the last thread");
370 PyInterpreterState_Clear(interp
);
371 PyThreadState_Swap(NULL
);
372 PyInterpreterState_Delete(interp
);
375 static char *progname
= "python";
378 Py_SetProgramName(char *pn
)
385 Py_GetProgramName(void)
390 static char *default_home
= NULL
;
393 Py_SetPythonHome(char *home
)
399 Py_GetPythonHome(void)
401 char *home
= default_home
;
402 if (home
== NULL
&& !Py_IgnoreEnvironmentFlag
)
403 home
= Py_GETENV("PYTHONHOME");
407 /* Create __main__ module */
413 m
= PyImport_AddModule("__main__");
415 Py_FatalError("can't create __main__ module");
416 d
= PyModule_GetDict(m
);
417 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
418 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
420 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
421 Py_FatalError("can't add __builtins__ to __main__");
426 /* Import the site module (not into __main__ though) */
432 m
= PyImport_ImportModule("site");
434 f
= PySys_GetObject("stderr");
435 if (Py_VerboseFlag
) {
437 "'import site' failed; traceback:\n", f
);
442 "'import site' failed; use -v for traceback\n", f
);
451 /* Parse input from a file and execute it */
454 PyRun_AnyFile(FILE *fp
, char *filename
)
456 return PyRun_AnyFileExFlags(fp
, filename
, 0, NULL
);
460 PyRun_AnyFileFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
462 return PyRun_AnyFileExFlags(fp
, filename
, 0, flags
);
466 PyRun_AnyFileEx(FILE *fp
, char *filename
, int closeit
)
468 return PyRun_AnyFileExFlags(fp
, filename
, closeit
, NULL
);
472 PyRun_AnyFileExFlags(FILE *fp
, char *filename
, int closeit
,
473 PyCompilerFlags
*flags
)
475 if (filename
== NULL
)
477 if (Py_FdIsInteractive(fp
, filename
)) {
478 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
484 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
488 PyRun_InteractiveLoop(FILE *fp
, char *filename
)
490 return PyRun_InteractiveLoopFlags(fp
, filename
, NULL
);
494 PyRun_InteractiveLoopFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
498 PyCompilerFlags local_flags
;
501 flags
= &local_flags
;
502 local_flags
.cf_flags
= 0;
504 v
= PySys_GetObject("ps1");
506 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
509 v
= PySys_GetObject("ps2");
511 PySys_SetObject("ps2", v
= PyString_FromString("... "));
515 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
517 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
529 PyRun_InteractiveOne(FILE *fp
, char *filename
)
531 return PyRun_InteractiveOneFlags(fp
, filename
, NULL
);
535 PyRun_InteractiveOneFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
537 PyObject
*m
, *d
, *v
, *w
;
540 char *ps1
= "", *ps2
= "";
542 v
= PySys_GetObject("ps1");
547 else if (PyString_Check(v
))
548 ps1
= PyString_AsString(v
);
550 w
= PySys_GetObject("ps2");
555 else if (PyString_Check(w
))
556 ps2
= PyString_AsString(w
);
558 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
,
559 Py_single_input
, ps1
, ps2
, &err
,
561 flags
->cf_flags
& CO_GENERATOR_ALLOWED
) ?
562 PyPARSE_YIELD_IS_KEYWORD
: 0);
566 if (err
.error
== E_EOF
) {
575 m
= PyImport_AddModule("__main__");
578 d
= PyModule_GetDict(m
);
579 v
= run_node(n
, filename
, d
, d
, flags
);
591 PyRun_SimpleFile(FILE *fp
, char *filename
)
593 return PyRun_SimpleFileEx(fp
, filename
, 0);
596 /* Check whether a file maybe a pyc file: Look at the extension,
597 the file type, and, if we may close it, at the first few bytes. */
600 maybe_pyc_file(FILE *fp
, char* filename
, char* ext
, int closeit
)
602 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
606 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
607 if (PyMac_getfiletype(filename
) == 'PYC '
608 || PyMac_getfiletype(filename
) == 'APPL')
610 #endif /* macintosh */
612 /* Only look into the file if we are allowed to close it, since
613 it then should also be seekable. */
615 /* Read only two bytes of the magic. If the file was opened in
616 text mode, the bytes 3 and 4 of the magic (\r\n) might not
617 be read as they are on disk. */
618 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
619 unsigned char buf
[2];
620 /* Mess: In case of -x, the stream is NOT at its start now,
621 and ungetc() was used to push back the first newline,
622 which makes the current stream position formally undefined,
623 and a x-platform nightmare.
624 Unfortunately, we have no direct way to know whether -x
625 was specified. So we use a terrible hack: if the current
626 stream position is not 0, we assume -x was specified, and
627 give up. Bug 132850 on SourceForge spells out the
628 hopelessness of trying anything else (fseek and ftell
629 don't work predictably x-platform for text-mode files).
632 if (ftell(fp
) == 0) {
633 if (fread(buf
, 1, 2, fp
) == 2 &&
634 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
644 PyRun_SimpleFileEx(FILE *fp
, char *filename
, int closeit
)
646 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, NULL
);
650 PyRun_SimpleFileExFlags(FILE *fp
, char *filename
, int closeit
,
651 PyCompilerFlags
*flags
)
656 m
= PyImport_AddModule("__main__");
659 d
= PyModule_GetDict(m
);
660 ext
= filename
+ strlen(filename
) - 4;
661 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
662 /* Try to run a pyc file. First, re-open in binary */
665 if( (fp
= fopen(filename
, "rb")) == NULL
) {
666 fprintf(stderr
, "python: Can't reopen .pyc file\n");
669 /* Turn on optimization if a .pyo file is given */
670 if (strcmp(ext
, ".pyo") == 0)
672 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
674 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
688 PyRun_SimpleString(char *command
)
690 return PyRun_SimpleStringFlags(command
, NULL
);
694 PyRun_SimpleStringFlags(char *command
, PyCompilerFlags
*flags
)
697 m
= PyImport_AddModule("__main__");
700 d
= PyModule_GetDict(m
);
701 v
= PyRun_StringFlags(command
, Py_file_input
, d
, d
, flags
);
713 parse_syntax_error(PyObject
*err
, PyObject
**message
, char **filename
,
714 int *lineno
, int *offset
, char **text
)
719 /* old style errors */
720 if (PyTuple_Check(err
))
721 return PyArg_Parse(err
, "(O(ziiz))", message
, filename
,
722 lineno
, offset
, text
);
724 /* new style errors. `err' is an instance */
726 if (! (v
= PyObject_GetAttrString(err
, "msg")))
730 if (!(v
= PyObject_GetAttrString(err
, "filename")))
734 else if (! (*filename
= PyString_AsString(v
)))
738 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
740 hold
= PyInt_AsLong(v
);
743 if (hold
< 0 && PyErr_Occurred())
747 if (!(v
= PyObject_GetAttrString(err
, "offset")))
754 hold
= PyInt_AsLong(v
);
757 if (hold
< 0 && PyErr_Occurred())
762 if (!(v
= PyObject_GetAttrString(err
, "text")))
766 else if (! (*text
= PyString_AsString(v
)))
783 print_error_text(PyObject
*f
, int offset
, char *text
)
787 if (offset
> 0 && offset
== (int)strlen(text
))
790 nl
= strchr(text
, '\n');
791 if (nl
== NULL
|| nl
-text
>= offset
)
793 offset
-= (nl
+1-text
);
796 while (*text
== ' ' || *text
== '\t') {
801 PyFile_WriteString(" ", f
);
802 PyFile_WriteString(text
, f
);
803 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
804 PyFile_WriteString("\n", f
);
807 PyFile_WriteString(" ", f
);
810 PyFile_WriteString(" ", f
);
813 PyFile_WriteString("^\n", f
);
817 handle_system_exit(void)
819 PyObject
*exception
, *value
, *tb
;
820 PyErr_Fetch(&exception
, &value
, &tb
);
824 if (value
== NULL
|| value
== Py_None
)
826 if (PyInstance_Check(value
)) {
827 /* The error code should be in the `code' attribute. */
828 PyObject
*code
= PyObject_GetAttrString(value
, "code");
832 if (value
== Py_None
)
835 /* If we failed to dig out the 'code' attribute,
836 just let the else clause below print the error. */
838 if (PyInt_Check(value
))
839 Py_Exit((int)PyInt_AsLong(value
));
841 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
842 PySys_WriteStderr("\n");
848 PyErr_PrintEx(int set_sys_last_vars
)
850 PyObject
*exception
, *v
, *tb
, *hook
;
852 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
853 handle_system_exit();
855 PyErr_Fetch(&exception
, &v
, &tb
);
856 PyErr_NormalizeException(&exception
, &v
, &tb
);
857 if (exception
== NULL
)
859 if (set_sys_last_vars
) {
860 PySys_SetObject("last_type", exception
);
861 PySys_SetObject("last_value", v
);
862 PySys_SetObject("last_traceback", tb
);
864 hook
= PySys_GetObject("excepthook");
866 PyObject
*args
= Py_BuildValue("(OOO)",
867 exception
, v
? v
: Py_None
, tb
? tb
: Py_None
);
868 PyObject
*result
= PyEval_CallObject(hook
, args
);
869 if (result
== NULL
) {
870 PyObject
*exception2
, *v2
, *tb2
;
871 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
872 handle_system_exit();
874 PyErr_Fetch(&exception2
, &v2
, &tb2
);
875 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
879 PySys_WriteStderr("Error in sys.excepthook:\n");
880 PyErr_Display(exception2
, v2
, tb2
);
881 PySys_WriteStderr("\nOriginal exception was:\n");
882 PyErr_Display(exception
, v
, tb
);
887 PySys_WriteStderr("sys.excepthook is missing\n");
888 PyErr_Display(exception
, v
, tb
);
890 Py_XDECREF(exception
);
895 void PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
899 PyObject
*f
= PySys_GetObject("stderr");
901 fprintf(stderr
, "lost sys.stderr\n");
906 if (tb
&& tb
!= Py_None
)
907 err
= PyTraceBack_Print(tb
, f
);
909 PyErr_GivenExceptionMatches(exception
, PyExc_SyntaxError
))
912 char *filename
, *text
;
914 if (!parse_syntax_error(v
, &message
, &filename
,
915 &lineno
, &offset
, &text
))
919 PyFile_WriteString(" File \"", f
);
920 if (filename
== NULL
)
921 PyFile_WriteString("<string>", f
);
923 PyFile_WriteString(filename
, f
);
924 PyFile_WriteString("\", line ", f
);
925 sprintf(buf
, "%d", lineno
);
926 PyFile_WriteString(buf
, f
);
927 PyFile_WriteString("\n", f
);
929 print_error_text(f
, offset
, text
);
931 /* Can't be bothered to check all those
932 PyFile_WriteString() calls */
933 if (PyErr_Occurred())
938 /* Don't do anything else */
940 else if (PyClass_Check(exception
)) {
941 PyClassObject
* exc
= (PyClassObject
*)exception
;
942 PyObject
* className
= exc
->cl_name
;
943 PyObject
* moduleName
=
944 PyDict_GetItemString(exc
->cl_dict
, "__module__");
946 if (moduleName
== NULL
)
947 err
= PyFile_WriteString("<unknown>", f
);
949 char* modstr
= PyString_AsString(moduleName
);
950 if (modstr
&& strcmp(modstr
, "exceptions"))
952 err
= PyFile_WriteString(modstr
, f
);
953 err
+= PyFile_WriteString(".", f
);
957 if (className
== NULL
)
958 err
= PyFile_WriteString("<unknown>", f
);
960 err
= PyFile_WriteObject(className
, f
,
965 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
967 if (v
!= NULL
&& v
!= Py_None
) {
968 PyObject
*s
= PyObject_Str(v
);
969 /* only print colon if the str() of the
970 object is not the empty string
974 else if (!PyString_Check(s
) ||
975 PyString_GET_SIZE(s
) != 0)
976 err
= PyFile_WriteString(": ", f
);
978 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
983 err
= PyFile_WriteString("\n", f
);
985 /* If an error happened here, don't show it.
986 XXX This is wrong, but too many callers rely on this behavior. */
992 PyRun_String(char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
994 return run_err_node(PyParser_SimpleParseString(str
, start
),
995 "<string>", globals
, locals
, NULL
);
999 PyRun_File(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1002 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
1006 PyRun_FileEx(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1007 PyObject
*locals
, int closeit
)
1009 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1012 return run_err_node(n
, filename
, globals
, locals
, NULL
);
1016 PyRun_StringFlags(char *str
, int start
, PyObject
*globals
, PyObject
*locals
,
1017 PyCompilerFlags
*flags
)
1019 return run_err_node(PyParser_SimpleParseStringFlags(
1021 (flags
&& flags
->cf_flags
& CO_GENERATOR_ALLOWED
) ?
1022 PyPARSE_YIELD_IS_KEYWORD
: 0),
1023 "<string>", globals
, locals
, flags
);
1027 PyRun_FileFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1028 PyObject
*locals
, PyCompilerFlags
*flags
)
1030 return PyRun_FileExFlags(fp
, filename
, start
, globals
, locals
, 0,
1035 PyRun_FileExFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1036 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1038 node
*n
= PyParser_SimpleParseFileFlags(fp
, filename
, start
,
1039 (flags
&& flags
->cf_flags
& CO_GENERATOR_ALLOWED
) ?
1040 PyPARSE_YIELD_IS_KEYWORD
: 0);
1043 return run_err_node(n
, filename
, globals
, locals
, flags
);
1047 run_err_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1048 PyCompilerFlags
*flags
)
1052 return run_node(n
, filename
, globals
, locals
, flags
);
1056 run_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1057 PyCompilerFlags
*flags
)
1061 co
= PyNode_CompileFlags(n
, filename
, flags
);
1065 v
= PyEval_EvalCode(co
, globals
, locals
);
1071 run_pyc_file(FILE *fp
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1072 PyCompilerFlags
*flags
)
1077 long PyImport_GetMagicNumber(void);
1079 magic
= PyMarshal_ReadLongFromFile(fp
);
1080 if (magic
!= PyImport_GetMagicNumber()) {
1081 PyErr_SetString(PyExc_RuntimeError
,
1082 "Bad magic number in .pyc file");
1085 (void) PyMarshal_ReadLongFromFile(fp
);
1086 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1088 if (v
== NULL
|| !PyCode_Check(v
)) {
1090 PyErr_SetString(PyExc_RuntimeError
,
1091 "Bad code object in .pyc file");
1094 co
= (PyCodeObject
*)v
;
1095 v
= PyEval_EvalCode(co
, globals
, locals
);
1097 flags
->cf_flags
|= (co
->co_flags
& PyCF_MASK
);
1103 Py_CompileString(char *str
, char *filename
, int start
)
1105 return Py_CompileStringFlags(str
, filename
, start
, NULL
);
1109 Py_CompileStringFlags(char *str
, char *filename
, int start
,
1110 PyCompilerFlags
*flags
)
1114 n
= PyParser_SimpleParseStringFlags(str
, start
,
1115 (flags
&& flags
->cf_flags
& CO_GENERATOR_ALLOWED
) ?
1116 PyPARSE_YIELD_IS_KEYWORD
: 0);
1119 co
= PyNode_CompileFlags(n
, filename
, flags
);
1121 return (PyObject
*)co
;
1125 Py_SymtableString(char *str
, char *filename
, int start
)
1128 struct symtable
*st
;
1129 n
= PyParser_SimpleParseString(str
, start
);
1132 st
= PyNode_CompileSymtable(n
, filename
);
1137 /* Simplified interface to parsefile -- return node or set exception */
1140 PyParser_SimpleParseFileFlags(FILE *fp
, char *filename
, int start
, int flags
)
1144 n
= PyParser_ParseFileFlags(fp
, filename
, &_PyParser_Grammar
, start
,
1145 (char *)0, (char *)0, &err
, flags
);
1152 PyParser_SimpleParseFile(FILE *fp
, char *filename
, int start
)
1154 return PyParser_SimpleParseFileFlags(fp
, filename
, start
, 0);
1157 /* Simplified interface to parsestring -- return node or set exception */
1160 PyParser_SimpleParseStringFlags(char *str
, int start
, int flags
)
1164 n
= PyParser_ParseStringFlags(str
, &_PyParser_Grammar
, start
, &err
,
1172 PyParser_SimpleParseString(char *str
, int start
)
1174 return PyParser_SimpleParseStringFlags(str
, start
, 0);
1177 /* Set the error appropriate to the given input error code (see errcode.h) */
1180 err_input(perrdetail
*err
)
1182 PyObject
*v
, *w
, *errtype
;
1184 errtype
= PyExc_SyntaxError
;
1185 v
= Py_BuildValue("(ziiz)", err
->filename
,
1186 err
->lineno
, err
->offset
, err
->text
);
1187 if (err
->text
!= NULL
) {
1188 PyMem_DEL(err
->text
);
1191 switch (err
->error
) {
1193 errtype
= PyExc_IndentationError
;
1194 if (err
->expected
== INDENT
)
1195 msg
= "expected an indented block";
1196 else if (err
->token
== INDENT
)
1197 msg
= "unexpected indent";
1198 else if (err
->token
== DEDENT
)
1199 msg
= "unexpected unindent";
1201 errtype
= PyExc_SyntaxError
;
1202 msg
= "invalid syntax";
1206 msg
= "invalid token";
1209 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1217 msg
= "unexpected EOF while parsing";
1220 errtype
= PyExc_TabError
;
1221 msg
= "inconsistent use of tabs and spaces in indentation";
1224 msg
= "expression too long";
1227 errtype
= PyExc_IndentationError
;
1228 msg
= "unindent does not match any outer indentation level";
1231 errtype
= PyExc_IndentationError
;
1232 msg
= "too many levels of indentation";
1235 fprintf(stderr
, "error=%d\n", err
->error
);
1236 msg
= "unknown parsing error";
1239 w
= Py_BuildValue("(sO)", msg
, v
);
1241 PyErr_SetObject(errtype
, w
);
1245 /* Print fatal error message and abort */
1248 Py_FatalError(char *msg
)
1250 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1255 OutputDebugString("Fatal Python error: ");
1256 OutputDebugString(msg
);
1257 OutputDebugString("\n");
1261 #endif /* MS_WIN32 */
1265 /* Clean up and exit */
1268 #include "pythread.h"
1269 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1272 #define NEXITFUNCS 32
1273 static void (*exitfuncs
[NEXITFUNCS
])(void);
1274 static int nexitfuncs
= 0;
1276 int Py_AtExit(void (*func
)(void))
1278 if (nexitfuncs
>= NEXITFUNCS
)
1280 exitfuncs
[nexitfuncs
++] = func
;
1285 call_sys_exitfunc(void)
1287 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1291 Py_INCREF(exitfunc
);
1292 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1293 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1295 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1296 PySys_WriteStderr("Error in sys.exitfunc:\n");
1300 Py_DECREF(exitfunc
);
1308 call_ll_exitfuncs(void)
1310 while (nexitfuncs
> 0)
1311 (*exitfuncs
[--nexitfuncs
])();
1332 #ifdef HAVE_SIGNAL_H
1334 signal(SIGPIPE
, SIG_IGN
);
1337 signal(SIGXFZ
, SIG_IGN
);
1339 #endif /* HAVE_SIGNAL_H */
1340 PyOS_InitInterrupts(); /* May imply initsignal() */
1343 #ifdef Py_TRACE_REFS
1344 /* Ask a yes/no question */
1347 _Py_AskYesNo(char *prompt
)
1351 fprintf(stderr
, "%s [ny] ", prompt
);
1352 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1354 return buf
[0] == 'y' || buf
[0] == 'Y';
1360 /* Check for file descriptor connected to interactive device.
1361 Pretend that stdin is always interactive, other files never. */
1366 return fd
== fileno(stdin
);
1372 * The file descriptor fd is considered ``interactive'' if either
1373 * a) isatty(fd) is TRUE, or
1374 * b) the -i flag was given, and the filename associated with
1375 * the descriptor is NULL or "<stdin>" or "???".
1378 Py_FdIsInteractive(FILE *fp
, char *filename
)
1380 if (isatty((int)fileno(fp
)))
1382 if (!Py_InteractiveFlag
)
1384 return (filename
== NULL
) ||
1385 (strcmp(filename
, "<stdin>") == 0) ||
1386 (strcmp(filename
, "???") == 0);
1390 #if defined(USE_STACKCHECK)
1391 #if defined(WIN32) && defined(_MSC_VER)
1393 /* Stack checking for Microsoft C */
1399 * Return non-zero when we run out of memory on the stack; zero otherwise.
1402 PyOS_CheckStack(void)
1405 /* _alloca throws a stack overflow exception if there's
1406 not enough space left on the stack */
1407 _alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1409 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1410 /* just ignore all errors */
1415 #endif /* WIN32 && _MSC_VER */
1417 /* Alternate implementations can be added here... */
1419 #endif /* USE_STACKCHECK */
1422 /* Wrappers around sigaction() or signal(). */
1425 PyOS_getsig(int sig
)
1427 #ifdef HAVE_SIGACTION
1428 struct sigaction context
;
1429 sigaction(sig
, NULL
, &context
);
1430 return context
.sa_handler
;
1432 PyOS_sighandler_t handler
;
1433 handler
= signal(sig
, SIG_IGN
);
1434 signal(sig
, handler
);
1440 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1442 #ifdef HAVE_SIGACTION
1443 struct sigaction context
;
1444 PyOS_sighandler_t oldhandler
;
1445 sigaction(sig
, NULL
, &context
);
1446 oldhandler
= context
.sa_handler
;
1447 context
.sa_handler
= handler
;
1448 sigaction(sig
, &context
, NULL
);
1451 return signal(sig
, handler
);