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 */
67 static int initialized
= 0;
69 /* API to access the initialized flag -- useful for esoteric use */
72 Py_IsInitialized(void)
77 /* Global initializations. Can be undone by Py_Finalize(). Don't
78 call this twice without an intervening Py_Finalize() call. When
79 initializations fail, a fatal error is issued and the function does
80 not return. On return, the first thread and interpreter state have
83 Locking: you must hold the interpreter lock while calling this.
84 (If the lock has not yet been initialized, that's equivalent to
85 having the lock, but you cannot use multiple threads.)
92 PyInterpreterState
*interp
;
93 PyThreadState
*tstate
;
94 PyObject
*bimod
, *sysmod
;
101 if ((p
= getenv("PYTHONDEBUG")) && *p
!= '\0')
102 Py_DebugFlag
= Py_DebugFlag
? Py_DebugFlag
: 1;
103 if ((p
= getenv("PYTHONVERBOSE")) && *p
!= '\0')
104 Py_VerboseFlag
= Py_VerboseFlag
? Py_VerboseFlag
: 1;
105 if ((p
= getenv("PYTHONOPTIMIZE")) && *p
!= '\0')
106 Py_OptimizeFlag
= Py_OptimizeFlag
? Py_OptimizeFlag
: 1;
108 interp
= PyInterpreterState_New();
110 Py_FatalError("Py_Initialize: can't make first interpreter");
112 tstate
= PyThreadState_New(interp
);
114 Py_FatalError("Py_Initialize: can't make first thread");
115 (void) PyThreadState_Swap(tstate
);
117 interp
->modules
= PyDict_New();
118 if (interp
->modules
== NULL
)
119 Py_FatalError("Py_Initialize: can't make modules dictionary");
121 /* Init codec registry */
122 _PyCodecRegistry_Init();
124 /* Init Unicode implementation; relies on the codec registry */
127 bimod
= _PyBuiltin_Init();
129 Py_FatalError("Py_Initialize: can't initialize __builtin__");
130 interp
->builtins
= PyModule_GetDict(bimod
);
131 Py_INCREF(interp
->builtins
);
133 sysmod
= _PySys_Init();
135 Py_FatalError("Py_Initialize: can't initialize sys");
136 interp
->sysdict
= PyModule_GetDict(sysmod
);
137 Py_INCREF(interp
->sysdict
);
138 _PyImport_FixupExtension("sys", "sys");
139 PySys_SetPath(Py_GetPath());
140 PyDict_SetItemString(interp
->sysdict
, "modules",
145 /* initialize builtin exceptions */
147 _PyImport_FixupExtension("exceptions", "exceptions");
149 /* phase 2 of builtins */
150 _PyImport_FixupExtension("__builtin__", "__builtin__");
152 initsigs(); /* Signal handling stuff, including initintr() */
154 initmain(); /* Module __main__ */
156 initsite(); /* Module site */
160 extern void dump_counts(void);
163 /* Undo the effect of Py_Initialize().
165 Beware: if multiple interpreter and/or thread states exist, these
166 are not wiped out; only the current thread and interpreter state
167 are deleted. But since everything else is deleted, those other
168 interpreter and thread states should no longer be used.
170 (XXX We should do better, e.g. wipe out all interpreters and
180 PyInterpreterState
*interp
;
181 PyThreadState
*tstate
;
186 /* The interpreter is still entirely intact at this point, and the
187 * exit funcs may be relying on that. In particular, if some thread
188 * or exit func is still waiting to do an import, the import machinery
189 * expects Py_IsInitialized() to return true. So don't say the
190 * interpreter is uninitialized until after the exit funcs have run.
191 * Note that Threading.py uses an exit func to do a join on all the
192 * threads created thru it, so this also protects pending imports in
193 * the threads created via Threading.
198 /* Get current thread state and interpreter pointer */
199 tstate
= PyThreadState_Get();
200 interp
= tstate
->interp
;
202 /* Disable signal handling */
203 PyOS_FiniInterrupts();
205 /* Cleanup Unicode implementation */
208 /* Cleanup Codec registry */
209 _PyCodecRegistry_Fini();
211 /* Destroy all modules */
214 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
217 /* Debugging stuff */
223 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
228 #ifdef MS_WINDOWS /* Only ask on Windows if env var set */
229 getenv("PYTHONDUMPREFS") &&
230 #endif /* MS_WINDOWS */
231 _Py_AskYesNo("Print left references?")) {
232 _Py_PrintReferences(stderr
);
234 #endif /* Py_TRACE_REFS */
236 /* Now we decref the exception classes. After this point nothing
237 can raise an exception. That's okay, because each Fini() method
238 below has been checked to make sure no exceptions are ever
243 /* Delete current thread */
244 PyInterpreterState_Clear(interp
);
245 PyThreadState_Swap(NULL
);
246 PyInterpreterState_Delete(interp
);
256 /* XXX Still allocated:
257 - various static ad-hoc pointers to interned strings
258 - int and float free list blocks
259 - whatever various modules and libraries allocate
262 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
267 _Py_ResetReferences();
268 #endif /* Py_TRACE_REFS */
271 /* Create and initialize a new interpreter and thread, and return the
272 new thread. This requires that Py_Initialize() has been called
275 Unsuccessful initialization yields a NULL pointer. Note that *no*
276 exception information is available even in this case -- the
277 exception information is held in the thread, and there is no
285 Py_NewInterpreter(void)
287 PyInterpreterState
*interp
;
288 PyThreadState
*tstate
, *save_tstate
;
289 PyObject
*bimod
, *sysmod
;
292 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
294 interp
= PyInterpreterState_New();
298 tstate
= PyThreadState_New(interp
);
299 if (tstate
== NULL
) {
300 PyInterpreterState_Delete(interp
);
304 save_tstate
= PyThreadState_Swap(tstate
);
306 /* XXX The following is lax in error checking */
308 interp
->modules
= PyDict_New();
310 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
312 interp
->builtins
= PyModule_GetDict(bimod
);
313 Py_INCREF(interp
->builtins
);
315 sysmod
= _PyImport_FindExtension("sys", "sys");
316 if (bimod
!= NULL
&& sysmod
!= NULL
) {
317 interp
->sysdict
= PyModule_GetDict(sysmod
);
318 Py_INCREF(interp
->sysdict
);
319 PySys_SetPath(Py_GetPath());
320 PyDict_SetItemString(interp
->sysdict
, "modules",
327 if (!PyErr_Occurred())
330 /* Oops, it didn't work. Undo it all. */
333 PyThreadState_Clear(tstate
);
334 PyThreadState_Swap(save_tstate
);
335 PyThreadState_Delete(tstate
);
336 PyInterpreterState_Delete(interp
);
341 /* Delete an interpreter and its last thread. This requires that the
342 given thread state is current, that the thread has no remaining
343 frames, and that it is its interpreter's only remaining thread.
344 It is a fatal error to violate these constraints.
346 (Py_Finalize() doesn't have these constraints -- it zaps
347 everything, regardless.)
354 Py_EndInterpreter(PyThreadState
*tstate
)
356 PyInterpreterState
*interp
= tstate
->interp
;
358 if (tstate
!= PyThreadState_Get())
359 Py_FatalError("Py_EndInterpreter: thread is not current");
360 if (tstate
->frame
!= NULL
)
361 Py_FatalError("Py_EndInterpreter: thread still has a frame");
362 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
363 Py_FatalError("Py_EndInterpreter: not the last thread");
366 PyInterpreterState_Clear(interp
);
367 PyThreadState_Swap(NULL
);
368 PyInterpreterState_Delete(interp
);
371 static char *progname
= "python";
374 Py_SetProgramName(char *pn
)
381 Py_GetProgramName(void)
386 static char *default_home
= NULL
;
389 Py_SetPythonHome(char *home
)
395 Py_GetPythonHome(void)
397 char *home
= default_home
;
399 home
= getenv("PYTHONHOME");
403 /* Create __main__ module */
409 m
= PyImport_AddModule("__main__");
411 Py_FatalError("can't create __main__ module");
412 d
= PyModule_GetDict(m
);
413 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
414 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
416 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
417 Py_FatalError("can't add __builtins__ to __main__");
422 /* Import the site module (not into __main__ though) */
428 m
= PyImport_ImportModule("site");
430 f
= PySys_GetObject("stderr");
431 if (Py_VerboseFlag
) {
433 "'import site' failed; traceback:\n", f
);
438 "'import site' failed; use -v for traceback\n", f
);
447 /* Parse input from a file and execute it */
450 PyRun_AnyFile(FILE *fp
, char *filename
)
452 return PyRun_AnyFileExFlags(fp
, filename
, 0, NULL
);
456 PyRun_AnyFileFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
458 return PyRun_AnyFileExFlags(fp
, filename
, 0, flags
);
462 PyRun_AnyFileEx(FILE *fp
, char *filename
, int closeit
)
464 return PyRun_AnyFileExFlags(fp
, filename
, closeit
, NULL
);
468 PyRun_AnyFileExFlags(FILE *fp
, char *filename
, int closeit
,
469 PyCompilerFlags
*flags
)
471 if (filename
== NULL
)
473 if (Py_FdIsInteractive(fp
, filename
)) {
474 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
480 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
484 PyRun_InteractiveLoop(FILE *fp
, char *filename
)
486 return PyRun_InteractiveLoopFlags(fp
, filename
, NULL
);
490 PyRun_InteractiveLoopFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
494 PyCompilerFlags local_flags
;
497 flags
= &local_flags
;
498 local_flags
.cf_nested_scopes
= 0;
500 v
= PySys_GetObject("ps1");
502 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
505 v
= PySys_GetObject("ps2");
507 PySys_SetObject("ps2", v
= PyString_FromString("... "));
511 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
513 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
525 PyRun_InteractiveOne(FILE *fp
, char *filename
)
527 return PyRun_InteractiveOneFlags(fp
, filename
, NULL
);
531 PyRun_InteractiveOneFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
533 PyObject
*m
, *d
, *v
, *w
;
536 char *ps1
= "", *ps2
= "";
537 v
= PySys_GetObject("ps1");
542 else if (PyString_Check(v
))
543 ps1
= PyString_AsString(v
);
545 w
= PySys_GetObject("ps2");
550 else if (PyString_Check(w
))
551 ps2
= PyString_AsString(w
);
553 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
,
554 Py_single_input
, ps1
, ps2
, &err
);
558 if (err
.error
== E_EOF
) {
567 m
= PyImport_AddModule("__main__");
570 d
= PyModule_GetDict(m
);
571 v
= run_node(n
, filename
, d
, d
, flags
);
583 PyRun_SimpleFile(FILE *fp
, char *filename
)
585 return PyRun_SimpleFileEx(fp
, filename
, 0);
588 /* Check whether a file maybe a pyc file: Look at the extension,
589 the file type, and, if we may close it, at the first few bytes. */
592 maybe_pyc_file(FILE *fp
, char* filename
, char* ext
, int closeit
)
594 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
598 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
599 if (PyMac_getfiletype(filename
) == 'PYC '
600 || PyMac_getfiletype(filename
) == 'APPL')
602 #endif /* macintosh */
604 /* Only look into the file if we are allowed to close it, since
605 it then should also be seekable. */
607 /* Read only two bytes of the magic. If the file was opened in
608 text mode, the bytes 3 and 4 of the magic (\r\n) might not
609 be read as they are on disk. */
610 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
611 unsigned char buf
[2];
612 /* Mess: In case of -x, the stream is NOT at its start now,
613 and ungetc() was used to push back the first newline,
614 which makes the current stream position formally undefined,
615 and a x-platform nightmare.
616 Unfortunately, we have no direct way to know whether -x
617 was specified. So we use a terrible hack: if the current
618 stream position is not 0, we assume -x was specified, and
619 give up. Bug 132850 on SourceForge spells out the
620 hopelessness of trying anything else (fseek and ftell
621 don't work predictably x-platform for text-mode files).
624 if (ftell(fp
) == 0) {
625 if (fread(buf
, 1, 2, fp
) == 2 &&
626 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
636 PyRun_SimpleFileEx(FILE *fp
, char *filename
, int closeit
)
638 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, NULL
);
642 PyRun_SimpleFileExFlags(FILE *fp
, char *filename
, int closeit
,
643 PyCompilerFlags
*flags
)
648 m
= PyImport_AddModule("__main__");
651 d
= PyModule_GetDict(m
);
652 ext
= filename
+ strlen(filename
) - 4;
653 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
654 /* Try to run a pyc file. First, re-open in binary */
657 if( (fp
= fopen(filename
, "rb")) == NULL
) {
658 fprintf(stderr
, "python: Can't reopen .pyc file\n");
661 /* Turn on optimization if a .pyo file is given */
662 if (strcmp(ext
, ".pyo") == 0)
664 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
666 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
680 PyRun_SimpleString(char *command
)
683 m
= PyImport_AddModule("__main__");
686 d
= PyModule_GetDict(m
);
687 v
= PyRun_String(command
, Py_file_input
, d
, d
);
699 parse_syntax_error(PyObject
*err
, PyObject
**message
, char **filename
,
700 int *lineno
, int *offset
, char **text
)
705 /* old style errors */
706 if (PyTuple_Check(err
))
707 return PyArg_Parse(err
, "(O(ziiz))", message
, filename
,
708 lineno
, offset
, text
);
710 /* new style errors. `err' is an instance */
712 if (! (v
= PyObject_GetAttrString(err
, "msg")))
716 if (!(v
= PyObject_GetAttrString(err
, "filename")))
720 else if (! (*filename
= PyString_AsString(v
)))
724 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
726 hold
= PyInt_AsLong(v
);
729 if (hold
< 0 && PyErr_Occurred())
733 if (!(v
= PyObject_GetAttrString(err
, "offset")))
740 hold
= PyInt_AsLong(v
);
743 if (hold
< 0 && PyErr_Occurred())
748 if (!(v
= PyObject_GetAttrString(err
, "text")))
752 else if (! (*text
= PyString_AsString(v
)))
769 print_error_text(PyObject
*f
, int offset
, char *text
)
773 if (offset
> 0 && offset
== (int)strlen(text
))
776 nl
= strchr(text
, '\n');
777 if (nl
== NULL
|| nl
-text
>= offset
)
779 offset
-= (nl
+1-text
);
782 while (*text
== ' ' || *text
== '\t') {
787 PyFile_WriteString(" ", f
);
788 PyFile_WriteString(text
, f
);
789 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
790 PyFile_WriteString("\n", f
);
793 PyFile_WriteString(" ", f
);
796 PyFile_WriteString(" ", f
);
799 PyFile_WriteString("^\n", f
);
803 handle_system_exit(void)
805 PyObject
*exception
, *value
, *tb
;
806 PyErr_Fetch(&exception
, &value
, &tb
);
810 if (value
== NULL
|| value
== Py_None
)
812 if (PyInstance_Check(value
)) {
813 /* The error code should be in the `code' attribute. */
814 PyObject
*code
= PyObject_GetAttrString(value
, "code");
818 if (value
== Py_None
)
821 /* If we failed to dig out the 'code' attribute,
822 just let the else clause below print the error. */
824 if (PyInt_Check(value
))
825 Py_Exit((int)PyInt_AsLong(value
));
827 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
828 PySys_WriteStderr("\n");
834 PyErr_PrintEx(int set_sys_last_vars
)
836 PyObject
*exception
, *v
, *tb
, *hook
;
838 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
839 handle_system_exit();
841 PyErr_Fetch(&exception
, &v
, &tb
);
842 PyErr_NormalizeException(&exception
, &v
, &tb
);
843 if (exception
== NULL
)
845 if (set_sys_last_vars
) {
846 PySys_SetObject("last_type", exception
);
847 PySys_SetObject("last_value", v
);
848 PySys_SetObject("last_traceback", tb
);
850 hook
= PySys_GetObject("excepthook");
852 PyObject
*args
= Py_BuildValue("(OOO)",
853 exception
, v
? v
: Py_None
, tb
? tb
: Py_None
);
854 PyObject
*result
= PyEval_CallObject(hook
, args
);
855 if (result
== NULL
) {
856 PyObject
*exception2
, *v2
, *tb2
;
857 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
858 handle_system_exit();
860 PyErr_Fetch(&exception2
, &v2
, &tb2
);
861 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
865 PySys_WriteStderr("Error in sys.excepthook:\n");
866 PyErr_Display(exception2
, v2
, tb2
);
867 PySys_WriteStderr("\nOriginal exception was:\n");
868 PyErr_Display(exception
, v
, tb
);
869 Py_XDECREF(exception2
);
876 PySys_WriteStderr("sys.excepthook is missing\n");
877 PyErr_Display(exception
, v
, tb
);
879 Py_XDECREF(exception
);
884 void PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
888 PyObject
*f
= PySys_GetObject("stderr");
890 fprintf(stderr
, "lost sys.stderr\n");
895 if (tb
&& tb
!= Py_None
)
896 err
= PyTraceBack_Print(tb
, f
);
898 PyErr_GivenExceptionMatches(exception
, PyExc_SyntaxError
))
901 char *filename
, *text
;
903 if (!parse_syntax_error(v
, &message
, &filename
,
904 &lineno
, &offset
, &text
))
908 PyFile_WriteString(" File \"", f
);
909 if (filename
== NULL
)
910 PyFile_WriteString("<string>", f
);
912 PyFile_WriteString(filename
, f
);
913 PyFile_WriteString("\", line ", f
);
914 sprintf(buf
, "%d", lineno
);
915 PyFile_WriteString(buf
, f
);
916 PyFile_WriteString("\n", f
);
918 print_error_text(f
, offset
, text
);
920 /* Can't be bothered to check all those
921 PyFile_WriteString() calls */
922 if (PyErr_Occurred())
927 /* Don't do anything else */
929 else if (PyClass_Check(exception
)) {
930 PyClassObject
* exc
= (PyClassObject
*)exception
;
931 PyObject
* className
= exc
->cl_name
;
932 PyObject
* moduleName
=
933 PyDict_GetItemString(exc
->cl_dict
, "__module__");
935 if (moduleName
== NULL
)
936 err
= PyFile_WriteString("<unknown>", f
);
938 char* modstr
= PyString_AsString(moduleName
);
939 if (modstr
&& strcmp(modstr
, "exceptions"))
941 err
= PyFile_WriteString(modstr
, f
);
942 err
+= PyFile_WriteString(".", f
);
946 if (className
== NULL
)
947 err
= PyFile_WriteString("<unknown>", f
);
949 err
= PyFile_WriteObject(className
, f
,
954 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
956 if (v
!= NULL
&& v
!= Py_None
) {
957 PyObject
*s
= PyObject_Str(v
);
958 /* only print colon if the str() of the
959 object is not the empty string
963 else if (!PyString_Check(s
) ||
964 PyString_GET_SIZE(s
) != 0)
965 err
= PyFile_WriteString(": ", f
);
967 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
972 err
= PyFile_WriteString("\n", f
);
974 /* If an error happened here, don't show it.
975 XXX This is wrong, but too many callers rely on this behavior. */
981 PyRun_String(char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
983 return run_err_node(PyParser_SimpleParseString(str
, start
),
984 "<string>", globals
, locals
, NULL
);
988 PyRun_File(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
991 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
995 PyRun_FileEx(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
996 PyObject
*locals
, int closeit
)
998 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1001 return run_err_node(n
, filename
, globals
, locals
, NULL
);
1005 PyRun_StringFlags(char *str
, int start
, PyObject
*globals
, PyObject
*locals
,
1006 PyCompilerFlags
*flags
)
1008 return run_err_node(PyParser_SimpleParseString(str
, start
),
1009 "<string>", globals
, locals
, flags
);
1013 PyRun_FileFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1014 PyObject
*locals
, PyCompilerFlags
*flags
)
1016 return PyRun_FileExFlags(fp
, filename
, start
, globals
, locals
, 0,
1021 PyRun_FileExFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1022 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1024 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1027 return run_err_node(n
, filename
, globals
, locals
, flags
);
1031 run_err_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1032 PyCompilerFlags
*flags
)
1036 return run_node(n
, filename
, globals
, locals
, flags
);
1040 run_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1041 PyCompilerFlags
*flags
)
1045 co
= PyNode_CompileFlags(n
, filename
, flags
);
1049 v
= PyEval_EvalCode(co
, globals
, locals
);
1055 run_pyc_file(FILE *fp
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1056 PyCompilerFlags
*flags
)
1061 long PyImport_GetMagicNumber(void);
1063 magic
= PyMarshal_ReadLongFromFile(fp
);
1064 if (magic
!= PyImport_GetMagicNumber()) {
1065 PyErr_SetString(PyExc_RuntimeError
,
1066 "Bad magic number in .pyc file");
1069 (void) PyMarshal_ReadLongFromFile(fp
);
1070 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1072 if (v
== NULL
|| !PyCode_Check(v
)) {
1074 PyErr_SetString(PyExc_RuntimeError
,
1075 "Bad code object in .pyc file");
1078 co
= (PyCodeObject
*)v
;
1079 v
= PyEval_EvalCode(co
, globals
, locals
);
1081 if (co
->co_flags
& CO_NESTED
)
1082 flags
->cf_nested_scopes
= 1;
1083 fprintf(stderr
, "run_pyc_file: nested_scopes: %d\n",
1084 flags
->cf_nested_scopes
);
1091 Py_CompileString(char *str
, char *filename
, int start
)
1093 return Py_CompileStringFlags(str
, filename
, start
, NULL
);
1097 Py_CompileStringFlags(char *str
, char *filename
, int start
,
1098 PyCompilerFlags
*flags
)
1102 n
= PyParser_SimpleParseString(str
, start
);
1105 co
= PyNode_CompileFlags(n
, filename
, flags
);
1107 return (PyObject
*)co
;
1111 Py_SymtableString(char *str
, char *filename
, int start
)
1114 struct symtable
*st
;
1115 n
= PyParser_SimpleParseString(str
, start
);
1118 st
= PyNode_CompileSymtable(n
, filename
);
1123 /* Simplified interface to parsefile -- return node or set exception */
1126 PyParser_SimpleParseFile(FILE *fp
, char *filename
, int start
)
1130 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
, start
,
1131 (char *)0, (char *)0, &err
);
1137 /* Simplified interface to parsestring -- return node or set exception */
1140 PyParser_SimpleParseString(char *str
, int start
)
1144 n
= PyParser_ParseString(str
, &_PyParser_Grammar
, start
, &err
);
1150 /* Set the error appropriate to the given input error code (see errcode.h) */
1153 err_input(perrdetail
*err
)
1155 PyObject
*v
, *w
, *errtype
;
1157 errtype
= PyExc_SyntaxError
;
1158 v
= Py_BuildValue("(ziiz)", err
->filename
,
1159 err
->lineno
, err
->offset
, err
->text
);
1160 if (err
->text
!= NULL
) {
1161 PyMem_DEL(err
->text
);
1164 switch (err
->error
) {
1166 errtype
= PyExc_IndentationError
;
1167 if (err
->expected
== INDENT
)
1168 msg
= "expected an indented block";
1169 else if (err
->token
== INDENT
)
1170 msg
= "unexpected indent";
1171 else if (err
->token
== DEDENT
)
1172 msg
= "unexpected unindent";
1174 errtype
= PyExc_SyntaxError
;
1175 msg
= "invalid syntax";
1179 msg
= "invalid token";
1182 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1190 msg
= "unexpected EOF while parsing";
1193 errtype
= PyExc_TabError
;
1194 msg
= "inconsistent use of tabs and spaces in indentation";
1197 msg
= "expression too long";
1200 errtype
= PyExc_IndentationError
;
1201 msg
= "unindent does not match any outer indentation level";
1204 errtype
= PyExc_IndentationError
;
1205 msg
= "too many levels of indentation";
1208 fprintf(stderr
, "error=%d\n", err
->error
);
1209 msg
= "unknown parsing error";
1212 w
= Py_BuildValue("(sO)", msg
, v
);
1214 PyErr_SetObject(errtype
, w
);
1218 /* Print fatal error message and abort */
1221 Py_FatalError(char *msg
)
1223 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1228 OutputDebugString("Fatal Python error: ");
1229 OutputDebugString(msg
);
1230 OutputDebugString("\n");
1234 #endif /* MS_WIN32 */
1238 /* Clean up and exit */
1241 #include "pythread.h"
1242 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1245 #define NEXITFUNCS 32
1246 static void (*exitfuncs
[NEXITFUNCS
])(void);
1247 static int nexitfuncs
= 0;
1249 int Py_AtExit(void (*func
)(void))
1251 if (nexitfuncs
>= NEXITFUNCS
)
1253 exitfuncs
[nexitfuncs
++] = func
;
1258 call_sys_exitfunc(void)
1260 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1264 Py_INCREF(exitfunc
);
1265 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1266 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1268 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1269 PySys_WriteStderr("Error in sys.exitfunc:\n");
1273 Py_DECREF(exitfunc
);
1281 call_ll_exitfuncs(void)
1283 while (nexitfuncs
> 0)
1284 (*exitfuncs
[--nexitfuncs
])();
1305 #ifdef HAVE_SIGNAL_H
1307 signal(SIGPIPE
, SIG_IGN
);
1309 #endif /* HAVE_SIGNAL_H */
1310 PyOS_InitInterrupts(); /* May imply initsignal() */
1313 #ifdef Py_TRACE_REFS
1314 /* Ask a yes/no question */
1317 _Py_AskYesNo(char *prompt
)
1321 printf("%s [ny] ", prompt
);
1322 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1324 return buf
[0] == 'y' || buf
[0] == 'Y';
1330 /* Check for file descriptor connected to interactive device.
1331 Pretend that stdin is always interactive, other files never. */
1336 return fd
== fileno(stdin
);
1342 * The file descriptor fd is considered ``interactive'' if either
1343 * a) isatty(fd) is TRUE, or
1344 * b) the -i flag was given, and the filename associated with
1345 * the descriptor is NULL or "<stdin>" or "???".
1348 Py_FdIsInteractive(FILE *fp
, char *filename
)
1350 if (isatty((int)fileno(fp
)))
1352 if (!Py_InteractiveFlag
)
1354 return (filename
== NULL
) ||
1355 (strcmp(filename
, "<stdin>") == 0) ||
1356 (strcmp(filename
, "???") == 0);
1360 #if defined(USE_STACKCHECK)
1361 #if defined(WIN32) && defined(_MSC_VER)
1363 /* Stack checking for Microsoft C */
1369 * Return non-zero when we run out of memory on the stack; zero otherwise.
1372 PyOS_CheckStack(void)
1375 /* _alloca throws a stack overflow exception if there's
1376 not enough space left on the stack */
1377 _alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1379 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1380 /* just ignore all errors */
1385 #endif /* WIN32 && _MSC_VER */
1387 /* Alternate implementations can be added here... */
1389 #endif /* USE_STACKCHECK */
1392 /* Wrappers around sigaction() or signal(). */
1395 PyOS_getsig(int sig
)
1397 #ifdef HAVE_SIGACTION
1398 struct sigaction context
;
1399 sigaction(sig
, NULL
, &context
);
1400 return context
.sa_handler
;
1402 PyOS_sighandler_t handler
;
1403 handler
= signal(sig
, SIG_IGN
);
1404 signal(sig
, handler
);
1410 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1412 #ifdef HAVE_SIGACTION
1413 struct sigaction context
;
1414 PyOS_sighandler_t oldhandler
;
1415 sigaction(sig
, NULL
, &context
);
1416 oldhandler
= context
.sa_handler
;
1417 context
.sa_handler
= handler
;
1418 sigaction(sig
, &context
, NULL
);
1421 return signal(sig
, handler
);