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 */
148 /* phase 2 of builtins */
149 _PyImport_FixupExtension("__builtin__", "__builtin__");
151 initsigs(); /* Signal handling stuff, including initintr() */
153 initmain(); /* Module __main__ */
155 initsite(); /* Module site */
159 extern void dump_counts(void);
162 /* Undo the effect of Py_Initialize().
164 Beware: if multiple interpreter and/or thread states exist, these
165 are not wiped out; only the current thread and interpreter state
166 are deleted. But since everything else is deleted, those other
167 interpreter and thread states should no longer be used.
169 (XXX We should do better, e.g. wipe out all interpreters and
179 PyInterpreterState
*interp
;
180 PyThreadState
*tstate
;
185 /* The interpreter is still entirely intact at this point, and the
186 * exit funcs may be relying on that. In particular, if some thread
187 * or exit func is still waiting to do an import, the import machinery
188 * expects Py_IsInitialized() to return true. So don't say the
189 * interpreter is uninitialized until after the exit funcs have run.
190 * Note that Threading.py uses an exit func to do a join on all the
191 * threads created thru it, so this also protects pending imports in
192 * the threads created via Threading.
197 /* Get current thread state and interpreter pointer */
198 tstate
= PyThreadState_Get();
199 interp
= tstate
->interp
;
201 /* Disable signal handling */
202 PyOS_FiniInterrupts();
204 /* Cleanup Unicode implementation */
207 /* Cleanup Codec registry */
208 _PyCodecRegistry_Fini();
210 /* Destroy all modules */
213 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
216 /* Debugging stuff */
222 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
227 #ifdef MS_WINDOWS /* Only ask on Windows if env var set */
228 getenv("PYTHONDUMPREFS") &&
229 #endif /* MS_WINDOWS */
230 _Py_AskYesNo("Print left references?")) {
231 _Py_PrintReferences(stderr
);
233 #endif /* Py_TRACE_REFS */
235 /* Now we decref the exception classes. After this point nothing
236 can raise an exception. That's okay, because each Fini() method
237 below has been checked to make sure no exceptions are ever
242 /* Delete current thread */
243 PyInterpreterState_Clear(interp
);
244 PyThreadState_Swap(NULL
);
245 PyInterpreterState_Delete(interp
);
255 /* XXX Still allocated:
256 - various static ad-hoc pointers to interned strings
257 - int and float free list blocks
258 - whatever various modules and libraries allocate
261 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
266 _Py_ResetReferences();
267 #endif /* Py_TRACE_REFS */
270 /* Create and initialize a new interpreter and thread, and return the
271 new thread. This requires that Py_Initialize() has been called
274 Unsuccessful initialization yields a NULL pointer. Note that *no*
275 exception information is available even in this case -- the
276 exception information is held in the thread, and there is no
284 Py_NewInterpreter(void)
286 PyInterpreterState
*interp
;
287 PyThreadState
*tstate
, *save_tstate
;
288 PyObject
*bimod
, *sysmod
;
291 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
293 interp
= PyInterpreterState_New();
297 tstate
= PyThreadState_New(interp
);
298 if (tstate
== NULL
) {
299 PyInterpreterState_Delete(interp
);
303 save_tstate
= PyThreadState_Swap(tstate
);
305 /* XXX The following is lax in error checking */
307 interp
->modules
= PyDict_New();
309 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
311 interp
->builtins
= PyModule_GetDict(bimod
);
312 Py_INCREF(interp
->builtins
);
314 sysmod
= _PyImport_FindExtension("sys", "sys");
315 if (bimod
!= NULL
&& sysmod
!= NULL
) {
316 interp
->sysdict
= PyModule_GetDict(sysmod
);
317 Py_INCREF(interp
->sysdict
);
318 PySys_SetPath(Py_GetPath());
319 PyDict_SetItemString(interp
->sysdict
, "modules",
326 if (!PyErr_Occurred())
329 /* Oops, it didn't work. Undo it all. */
332 PyThreadState_Clear(tstate
);
333 PyThreadState_Swap(save_tstate
);
334 PyThreadState_Delete(tstate
);
335 PyInterpreterState_Delete(interp
);
340 /* Delete an interpreter and its last thread. This requires that the
341 given thread state is current, that the thread has no remaining
342 frames, and that it is its interpreter's only remaining thread.
343 It is a fatal error to violate these constraints.
345 (Py_Finalize() doesn't have these constraints -- it zaps
346 everything, regardless.)
353 Py_EndInterpreter(PyThreadState
*tstate
)
355 PyInterpreterState
*interp
= tstate
->interp
;
357 if (tstate
!= PyThreadState_Get())
358 Py_FatalError("Py_EndInterpreter: thread is not current");
359 if (tstate
->frame
!= NULL
)
360 Py_FatalError("Py_EndInterpreter: thread still has a frame");
361 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
362 Py_FatalError("Py_EndInterpreter: not the last thread");
365 PyInterpreterState_Clear(interp
);
366 PyThreadState_Swap(NULL
);
367 PyInterpreterState_Delete(interp
);
370 static char *progname
= "python";
373 Py_SetProgramName(char *pn
)
380 Py_GetProgramName(void)
385 static char *default_home
= NULL
;
388 Py_SetPythonHome(char *home
)
394 Py_GetPythonHome(void)
396 char *home
= default_home
;
398 home
= getenv("PYTHONHOME");
402 /* Create __main__ module */
408 m
= PyImport_AddModule("__main__");
410 Py_FatalError("can't create __main__ module");
411 d
= PyModule_GetDict(m
);
412 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
413 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
415 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
416 Py_FatalError("can't add __builtins__ to __main__");
421 /* Import the site module (not into __main__ though) */
427 m
= PyImport_ImportModule("site");
429 f
= PySys_GetObject("stderr");
430 if (Py_VerboseFlag
) {
432 "'import site' failed; traceback:\n", f
);
437 "'import site' failed; use -v for traceback\n", f
);
446 /* Parse input from a file and execute it */
449 PyRun_AnyFile(FILE *fp
, char *filename
)
451 return PyRun_AnyFileExFlags(fp
, filename
, 0, NULL
);
455 PyRun_AnyFileFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
457 return PyRun_AnyFileExFlags(fp
, filename
, 0, flags
);
461 PyRun_AnyFileEx(FILE *fp
, char *filename
, int closeit
)
463 return PyRun_AnyFileExFlags(fp
, filename
, closeit
, NULL
);
467 PyRun_AnyFileExFlags(FILE *fp
, char *filename
, int closeit
,
468 PyCompilerFlags
*flags
)
470 if (filename
== NULL
)
472 if (Py_FdIsInteractive(fp
, filename
)) {
473 int err
= PyRun_InteractiveLoopFlags(fp
, filename
, flags
);
479 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, flags
);
483 PyRun_InteractiveLoop(FILE *fp
, char *filename
)
485 return PyRun_InteractiveLoopFlags(fp
, filename
, NULL
);
489 PyRun_InteractiveLoopFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
493 PyCompilerFlags local_flags
;
496 flags
= &local_flags
;
497 local_flags
.cf_nested_scopes
= 0;
499 v
= PySys_GetObject("ps1");
501 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
504 v
= PySys_GetObject("ps2");
506 PySys_SetObject("ps2", v
= PyString_FromString("... "));
510 ret
= PyRun_InteractiveOneFlags(fp
, filename
, flags
);
512 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
524 PyRun_InteractiveOne(FILE *fp
, char *filename
)
526 return PyRun_InteractiveOneFlags(fp
, filename
, NULL
);
530 PyRun_InteractiveOneFlags(FILE *fp
, char *filename
, PyCompilerFlags
*flags
)
532 PyObject
*m
, *d
, *v
, *w
;
535 char *ps1
= "", *ps2
= "";
536 v
= PySys_GetObject("ps1");
541 else if (PyString_Check(v
))
542 ps1
= PyString_AsString(v
);
544 w
= PySys_GetObject("ps2");
549 else if (PyString_Check(w
))
550 ps2
= PyString_AsString(w
);
552 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
,
553 Py_single_input
, ps1
, ps2
, &err
);
557 if (err
.error
== E_EOF
) {
566 m
= PyImport_AddModule("__main__");
569 d
= PyModule_GetDict(m
);
570 v
= run_node(n
, filename
, d
, d
, flags
);
582 PyRun_SimpleFile(FILE *fp
, char *filename
)
584 return PyRun_SimpleFileEx(fp
, filename
, 0);
587 /* Check whether a file maybe a pyc file: Look at the extension,
588 the file type, and, if we may close it, at the first few bytes. */
591 maybe_pyc_file(FILE *fp
, char* filename
, char* ext
, int closeit
)
593 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0)
597 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
598 if (PyMac_getfiletype(filename
) == 'PYC '
599 || PyMac_getfiletype(filename
) == 'APPL')
601 #endif /* macintosh */
603 /* Only look into the file if we are allowed to close it, since
604 it then should also be seekable. */
606 /* Read only two bytes of the magic. If the file was opened in
607 text mode, the bytes 3 and 4 of the magic (\r\n) might not
608 be read as they are on disk. */
609 unsigned int halfmagic
= PyImport_GetMagicNumber() & 0xFFFF;
610 unsigned char buf
[2];
611 /* Mess: In case of -x, the stream is NOT at its start now,
612 and ungetc() was used to push back the first newline,
613 which makes the current stream position formally undefined,
614 and a x-platform nightmare.
615 Unfortunately, we have no direct way to know whether -x
616 was specified. So we use a terrible hack: if the current
617 stream position is not 0, we assume -x was specified, and
618 give up. Bug 132850 on SourceForge spells out the
619 hopelessness of trying anything else (fseek and ftell
620 don't work predictably x-platform for text-mode files).
623 if (ftell(fp
) == 0) {
624 if (fread(buf
, 1, 2, fp
) == 2 &&
625 ((unsigned int)buf
[1]<<8 | buf
[0]) == halfmagic
)
635 PyRun_SimpleFileEx(FILE *fp
, char *filename
, int closeit
)
637 return PyRun_SimpleFileExFlags(fp
, filename
, closeit
, NULL
);
641 PyRun_SimpleFileExFlags(FILE *fp
, char *filename
, int closeit
,
642 PyCompilerFlags
*flags
)
647 m
= PyImport_AddModule("__main__");
650 d
= PyModule_GetDict(m
);
651 ext
= filename
+ strlen(filename
) - 4;
652 if (maybe_pyc_file(fp
, filename
, ext
, closeit
)) {
653 /* Try to run a pyc file. First, re-open in binary */
656 if( (fp
= fopen(filename
, "rb")) == NULL
) {
657 fprintf(stderr
, "python: Can't reopen .pyc file\n");
660 /* Turn on optimization if a .pyo file is given */
661 if (strcmp(ext
, ".pyo") == 0)
663 v
= run_pyc_file(fp
, filename
, d
, d
, flags
);
665 v
= PyRun_FileExFlags(fp
, filename
, Py_file_input
, d
, d
,
679 PyRun_SimpleString(char *command
)
682 m
= PyImport_AddModule("__main__");
685 d
= PyModule_GetDict(m
);
686 v
= PyRun_String(command
, Py_file_input
, d
, d
);
698 parse_syntax_error(PyObject
*err
, PyObject
**message
, char **filename
,
699 int *lineno
, int *offset
, char **text
)
704 /* old style errors */
705 if (PyTuple_Check(err
))
706 return PyArg_Parse(err
, "(O(ziiz))", message
, filename
,
707 lineno
, offset
, text
);
709 /* new style errors. `err' is an instance */
711 if (! (v
= PyObject_GetAttrString(err
, "msg")))
715 if (!(v
= PyObject_GetAttrString(err
, "filename")))
719 else if (! (*filename
= PyString_AsString(v
)))
723 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
725 hold
= PyInt_AsLong(v
);
728 if (hold
< 0 && PyErr_Occurred())
732 if (!(v
= PyObject_GetAttrString(err
, "offset")))
739 hold
= PyInt_AsLong(v
);
742 if (hold
< 0 && PyErr_Occurred())
747 if (!(v
= PyObject_GetAttrString(err
, "text")))
751 else if (! (*text
= PyString_AsString(v
)))
768 print_error_text(PyObject
*f
, int offset
, char *text
)
772 if (offset
> 0 && offset
== (int)strlen(text
))
775 nl
= strchr(text
, '\n');
776 if (nl
== NULL
|| nl
-text
>= offset
)
778 offset
-= (nl
+1-text
);
781 while (*text
== ' ' || *text
== '\t') {
786 PyFile_WriteString(" ", f
);
787 PyFile_WriteString(text
, f
);
788 if (*text
== '\0' || text
[strlen(text
)-1] != '\n')
789 PyFile_WriteString("\n", f
);
792 PyFile_WriteString(" ", f
);
795 PyFile_WriteString(" ", f
);
798 PyFile_WriteString("^\n", f
);
802 handle_system_exit(void)
804 PyObject
*exception
, *value
, *tb
;
805 PyErr_Fetch(&exception
, &value
, &tb
);
809 if (value
== NULL
|| value
== Py_None
)
811 if (PyInstance_Check(value
)) {
812 /* The error code should be in the `code' attribute. */
813 PyObject
*code
= PyObject_GetAttrString(value
, "code");
817 if (value
== Py_None
)
820 /* If we failed to dig out the 'code' attribute,
821 just let the else clause below print the error. */
823 if (PyInt_Check(value
))
824 Py_Exit((int)PyInt_AsLong(value
));
826 PyObject_Print(value
, stderr
, Py_PRINT_RAW
);
827 PySys_WriteStderr("\n");
833 PyErr_PrintEx(int set_sys_last_vars
)
835 PyObject
*exception
, *v
, *tb
, *hook
;
837 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
838 handle_system_exit();
840 PyErr_Fetch(&exception
, &v
, &tb
);
841 PyErr_NormalizeException(&exception
, &v
, &tb
);
842 if (exception
== NULL
)
844 if (set_sys_last_vars
) {
845 PySys_SetObject("last_type", exception
);
846 PySys_SetObject("last_value", v
);
847 PySys_SetObject("last_traceback", tb
);
849 hook
= PySys_GetObject("excepthook");
851 PyObject
*args
= Py_BuildValue("(OOO)",
852 exception
, v
? v
: Py_None
, tb
? tb
: Py_None
);
853 PyObject
*result
= PyEval_CallObject(hook
, args
);
854 if (result
== NULL
) {
855 PyObject
*exception2
, *v2
, *tb2
;
856 if (PyErr_ExceptionMatches(PyExc_SystemExit
)) {
857 handle_system_exit();
859 PyErr_Fetch(&exception2
, &v2
, &tb2
);
860 PyErr_NormalizeException(&exception2
, &v2
, &tb2
);
864 PySys_WriteStderr("Error in sys.excepthook:\n");
865 PyErr_Display(exception2
, v2
, tb2
);
866 PySys_WriteStderr("\nOriginal exception was:\n");
867 PyErr_Display(exception
, v
, tb
);
872 PySys_WriteStderr("sys.excepthook is missing\n");
873 PyErr_Display(exception
, v
, tb
);
875 Py_XDECREF(exception
);
880 void PyErr_Display(PyObject
*exception
, PyObject
*value
, PyObject
*tb
)
884 PyObject
*f
= PySys_GetObject("stderr");
886 fprintf(stderr
, "lost sys.stderr\n");
891 if (tb
&& tb
!= Py_None
)
892 err
= PyTraceBack_Print(tb
, f
);
894 PyErr_GivenExceptionMatches(exception
, PyExc_SyntaxError
))
897 char *filename
, *text
;
899 if (!parse_syntax_error(v
, &message
, &filename
,
900 &lineno
, &offset
, &text
))
904 PyFile_WriteString(" File \"", f
);
905 if (filename
== NULL
)
906 PyFile_WriteString("<string>", f
);
908 PyFile_WriteString(filename
, f
);
909 PyFile_WriteString("\", line ", f
);
910 sprintf(buf
, "%d", lineno
);
911 PyFile_WriteString(buf
, f
);
912 PyFile_WriteString("\n", f
);
914 print_error_text(f
, offset
, text
);
916 /* Can't be bothered to check all those
917 PyFile_WriteString() calls */
918 if (PyErr_Occurred())
923 /* Don't do anything else */
925 else if (PyClass_Check(exception
)) {
926 PyClassObject
* exc
= (PyClassObject
*)exception
;
927 PyObject
* className
= exc
->cl_name
;
928 PyObject
* moduleName
=
929 PyDict_GetItemString(exc
->cl_dict
, "__module__");
931 if (moduleName
== NULL
)
932 err
= PyFile_WriteString("<unknown>", f
);
934 char* modstr
= PyString_AsString(moduleName
);
935 if (modstr
&& strcmp(modstr
, "exceptions"))
937 err
= PyFile_WriteString(modstr
, f
);
938 err
+= PyFile_WriteString(".", f
);
942 if (className
== NULL
)
943 err
= PyFile_WriteString("<unknown>", f
);
945 err
= PyFile_WriteObject(className
, f
,
950 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
952 if (v
!= NULL
&& v
!= Py_None
) {
953 PyObject
*s
= PyObject_Str(v
);
954 /* only print colon if the str() of the
955 object is not the empty string
959 else if (!PyString_Check(s
) ||
960 PyString_GET_SIZE(s
) != 0)
961 err
= PyFile_WriteString(": ", f
);
963 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
968 err
= PyFile_WriteString("\n", f
);
970 /* If an error happened here, don't show it.
971 XXX This is wrong, but too many callers rely on this behavior. */
977 PyRun_String(char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
979 return run_err_node(PyParser_SimpleParseString(str
, start
),
980 "<string>", globals
, locals
, NULL
);
984 PyRun_File(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
987 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
991 PyRun_FileEx(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
992 PyObject
*locals
, int closeit
)
994 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
997 return run_err_node(n
, filename
, globals
, locals
, NULL
);
1001 PyRun_StringFlags(char *str
, int start
, PyObject
*globals
, PyObject
*locals
,
1002 PyCompilerFlags
*flags
)
1004 return run_err_node(PyParser_SimpleParseString(str
, start
),
1005 "<string>", globals
, locals
, flags
);
1009 PyRun_FileFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1010 PyObject
*locals
, PyCompilerFlags
*flags
)
1012 return PyRun_FileExFlags(fp
, filename
, start
, globals
, locals
, 0,
1017 PyRun_FileExFlags(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
1018 PyObject
*locals
, int closeit
, PyCompilerFlags
*flags
)
1020 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
1023 return run_err_node(n
, filename
, globals
, locals
, flags
);
1027 run_err_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1028 PyCompilerFlags
*flags
)
1032 return run_node(n
, filename
, globals
, locals
, flags
);
1036 run_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1037 PyCompilerFlags
*flags
)
1041 co
= PyNode_CompileFlags(n
, filename
, flags
);
1045 v
= PyEval_EvalCode(co
, globals
, locals
);
1051 run_pyc_file(FILE *fp
, char *filename
, PyObject
*globals
, PyObject
*locals
,
1052 PyCompilerFlags
*flags
)
1057 long PyImport_GetMagicNumber(void);
1059 magic
= PyMarshal_ReadLongFromFile(fp
);
1060 if (magic
!= PyImport_GetMagicNumber()) {
1061 PyErr_SetString(PyExc_RuntimeError
,
1062 "Bad magic number in .pyc file");
1065 (void) PyMarshal_ReadLongFromFile(fp
);
1066 v
= PyMarshal_ReadLastObjectFromFile(fp
);
1068 if (v
== NULL
|| !PyCode_Check(v
)) {
1070 PyErr_SetString(PyExc_RuntimeError
,
1071 "Bad code object in .pyc file");
1074 co
= (PyCodeObject
*)v
;
1075 v
= PyEval_EvalCode(co
, globals
, locals
);
1077 if (co
->co_flags
& CO_NESTED
)
1078 flags
->cf_nested_scopes
= 1;
1079 fprintf(stderr
, "run_pyc_file: nested_scopes: %d\n",
1080 flags
->cf_nested_scopes
);
1087 Py_CompileString(char *str
, char *filename
, int start
)
1089 return Py_CompileStringFlags(str
, filename
, start
, NULL
);
1093 Py_CompileStringFlags(char *str
, char *filename
, int start
,
1094 PyCompilerFlags
*flags
)
1098 n
= PyParser_SimpleParseString(str
, start
);
1101 co
= PyNode_CompileFlags(n
, filename
, flags
);
1103 return (PyObject
*)co
;
1107 Py_SymtableString(char *str
, char *filename
, int start
)
1110 struct symtable
*st
;
1111 n
= PyParser_SimpleParseString(str
, start
);
1114 st
= PyNode_CompileSymtable(n
, filename
);
1119 /* Simplified interface to parsefile -- return node or set exception */
1122 PyParser_SimpleParseFile(FILE *fp
, char *filename
, int start
)
1126 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
, start
,
1127 (char *)0, (char *)0, &err
);
1133 /* Simplified interface to parsestring -- return node or set exception */
1136 PyParser_SimpleParseString(char *str
, int start
)
1140 n
= PyParser_ParseString(str
, &_PyParser_Grammar
, start
, &err
);
1146 /* Set the error appropriate to the given input error code (see errcode.h) */
1149 err_input(perrdetail
*err
)
1151 PyObject
*v
, *w
, *errtype
;
1153 errtype
= PyExc_SyntaxError
;
1154 v
= Py_BuildValue("(ziiz)", err
->filename
,
1155 err
->lineno
, err
->offset
, err
->text
);
1156 if (err
->text
!= NULL
) {
1157 PyMem_DEL(err
->text
);
1160 switch (err
->error
) {
1162 errtype
= PyExc_IndentationError
;
1163 if (err
->expected
== INDENT
)
1164 msg
= "expected an indented block";
1165 else if (err
->token
== INDENT
)
1166 msg
= "unexpected indent";
1167 else if (err
->token
== DEDENT
)
1168 msg
= "unexpected unindent";
1170 errtype
= PyExc_SyntaxError
;
1171 msg
= "invalid syntax";
1175 msg
= "invalid token";
1178 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1186 msg
= "unexpected EOF while parsing";
1189 errtype
= PyExc_TabError
;
1190 msg
= "inconsistent use of tabs and spaces in indentation";
1193 msg
= "expression too long";
1196 errtype
= PyExc_IndentationError
;
1197 msg
= "unindent does not match any outer indentation level";
1200 errtype
= PyExc_IndentationError
;
1201 msg
= "too many levels of indentation";
1204 fprintf(stderr
, "error=%d\n", err
->error
);
1205 msg
= "unknown parsing error";
1208 w
= Py_BuildValue("(sO)", msg
, v
);
1210 PyErr_SetObject(errtype
, w
);
1214 /* Print fatal error message and abort */
1217 Py_FatalError(char *msg
)
1219 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1224 OutputDebugString("Fatal Python error: ");
1225 OutputDebugString(msg
);
1226 OutputDebugString("\n");
1230 #endif /* MS_WIN32 */
1234 /* Clean up and exit */
1237 #include "pythread.h"
1238 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1241 #define NEXITFUNCS 32
1242 static void (*exitfuncs
[NEXITFUNCS
])(void);
1243 static int nexitfuncs
= 0;
1245 int Py_AtExit(void (*func
)(void))
1247 if (nexitfuncs
>= NEXITFUNCS
)
1249 exitfuncs
[nexitfuncs
++] = func
;
1254 call_sys_exitfunc(void)
1256 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1260 Py_INCREF(exitfunc
);
1261 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1262 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1264 if (!PyErr_ExceptionMatches(PyExc_SystemExit
)) {
1265 PySys_WriteStderr("Error in sys.exitfunc:\n");
1269 Py_DECREF(exitfunc
);
1277 call_ll_exitfuncs(void)
1279 while (nexitfuncs
> 0)
1280 (*exitfuncs
[--nexitfuncs
])();
1301 #ifdef HAVE_SIGNAL_H
1303 signal(SIGPIPE
, SIG_IGN
);
1305 #endif /* HAVE_SIGNAL_H */
1306 PyOS_InitInterrupts(); /* May imply initsignal() */
1309 #ifdef Py_TRACE_REFS
1310 /* Ask a yes/no question */
1313 _Py_AskYesNo(char *prompt
)
1317 printf("%s [ny] ", prompt
);
1318 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1320 return buf
[0] == 'y' || buf
[0] == 'Y';
1326 /* Check for file descriptor connected to interactive device.
1327 Pretend that stdin is always interactive, other files never. */
1332 return fd
== fileno(stdin
);
1338 * The file descriptor fd is considered ``interactive'' if either
1339 * a) isatty(fd) is TRUE, or
1340 * b) the -i flag was given, and the filename associated with
1341 * the descriptor is NULL or "<stdin>" or "???".
1344 Py_FdIsInteractive(FILE *fp
, char *filename
)
1346 if (isatty((int)fileno(fp
)))
1348 if (!Py_InteractiveFlag
)
1350 return (filename
== NULL
) ||
1351 (strcmp(filename
, "<stdin>") == 0) ||
1352 (strcmp(filename
, "???") == 0);
1356 #if defined(USE_STACKCHECK)
1357 #if defined(WIN32) && defined(_MSC_VER)
1359 /* Stack checking for Microsoft C */
1365 * Return non-zero when we run out of memory on the stack; zero otherwise.
1368 PyOS_CheckStack(void)
1371 /* _alloca throws a stack overflow exception if there's
1372 not enough space left on the stack */
1373 _alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1375 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1376 /* just ignore all errors */
1381 #endif /* WIN32 && _MSC_VER */
1383 /* Alternate implementations can be added here... */
1385 #endif /* USE_STACKCHECK */
1388 /* Wrappers around sigaction() or signal(). */
1391 PyOS_getsig(int sig
)
1393 #ifdef HAVE_SIGACTION
1394 struct sigaction context
;
1395 sigaction(sig
, NULL
, &context
);
1396 return context
.sa_handler
;
1398 PyOS_sighandler_t handler
;
1399 handler
= signal(sig
, SIG_IGN
);
1400 signal(sig
, handler
);
1406 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1408 #ifdef HAVE_SIGACTION
1409 struct sigaction context
;
1410 PyOS_sighandler_t oldhandler
;
1411 sigaction(sig
, NULL
, &context
);
1412 oldhandler
= context
.sa_handler
;
1413 context
.sa_handler
= handler
;
1414 sigaction(sig
, &context
, NULL
);
1417 return signal(sig
, handler
);