2 /* Python interpreter top-level routines, including init/exit */
31 extern char *Py_GetPath(void);
33 extern grammar _PyParser_Grammar
; /* From graminit.c */
36 static void initmain(void);
37 static void initsite(void);
38 static PyObject
*run_err_node(node
*n
, char *filename
,
39 PyObject
*globals
, PyObject
*locals
);
40 static PyObject
*run_node(node
*n
, char *filename
,
41 PyObject
*globals
, PyObject
*locals
);
42 static PyObject
*run_pyc_file(FILE *fp
, char *filename
,
43 PyObject
*globals
, PyObject
*locals
);
44 static void err_input(perrdetail
*);
45 static void initsigs(void);
46 static void call_sys_exitfunc(void);
47 static void call_ll_exitfuncs(void);
50 int _Py_AskYesNo(char *prompt
);
53 extern void _PyUnicode_Init(void);
54 extern void _PyUnicode_Fini(void);
55 extern void _PyCodecRegistry_Init(void);
56 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 _PyCompareState_Key
= PyString_InternFromString("cmp_state");
129 bimod
= _PyBuiltin_Init();
131 Py_FatalError("Py_Initialize: can't initialize __builtin__");
132 interp
->builtins
= PyModule_GetDict(bimod
);
133 Py_INCREF(interp
->builtins
);
135 sysmod
= _PySys_Init();
137 Py_FatalError("Py_Initialize: can't initialize sys");
138 interp
->sysdict
= PyModule_GetDict(sysmod
);
139 Py_INCREF(interp
->sysdict
);
140 _PyImport_FixupExtension("sys", "sys");
141 PySys_SetPath(Py_GetPath());
142 PyDict_SetItemString(interp
->sysdict
, "modules",
147 /* initialize builtin exceptions */
150 /* phase 2 of builtins */
151 _PyImport_FixupExtension("__builtin__", "__builtin__");
153 initsigs(); /* Signal handling stuff, including initintr() */
155 initmain(); /* Module __main__ */
157 initsite(); /* Module site */
161 extern void dump_counts(void);
164 /* Undo the effect of Py_Initialize().
166 Beware: if multiple interpreter and/or thread states exist, these
167 are not wiped out; only the current thread and interpreter state
168 are deleted. But since everything else is deleted, those other
169 interpreter and thread states should no longer be used.
171 (XXX We should do better, e.g. wipe out all interpreters and
181 PyInterpreterState
*interp
;
182 PyThreadState
*tstate
;
187 /* The interpreter is still entirely intact at this point, and the
188 * exit funcs may be relying on that. In particular, if some thread
189 * or exit func is still waiting to do an import, the import machinery
190 * expects Py_IsInitialized() to return true. So don't say the
191 * interpreter is uninitialized until after the exit funcs have run.
192 * Note that Threading.py uses an exit func to do a join on all the
193 * threads created thru it, so this also protects pending imports in
194 * the threads created via Threading.
199 /* Get current thread state and interpreter pointer */
200 tstate
= PyThreadState_Get();
201 interp
= tstate
->interp
;
203 /* Disable signal handling */
204 PyOS_FiniInterrupts();
206 /* Cleanup Unicode implementation */
209 /* Cleanup Codec registry */
210 _PyCodecRegistry_Fini();
212 /* Destroy all modules */
215 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
218 /* Debugging stuff */
224 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
229 #ifdef MS_WINDOWS /* Only ask on Windows if env var set */
230 getenv("PYTHONDUMPREFS") &&
231 #endif /* MS_WINDOWS */
232 _Py_AskYesNo("Print left references?")) {
233 _Py_PrintReferences(stderr
);
235 #endif /* Py_TRACE_REFS */
237 /* Now we decref the exception classes. After this point nothing
238 can raise an exception. That's okay, because each Fini() method
239 below has been checked to make sure no exceptions are ever
244 /* Delete current thread */
245 PyInterpreterState_Clear(interp
);
246 PyThreadState_Swap(NULL
);
247 PyInterpreterState_Delete(interp
);
257 /* XXX Still allocated:
258 - various static ad-hoc pointers to interned strings
259 - int and float free list blocks
260 - whatever various modules and libraries allocate
263 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
268 _Py_ResetReferences();
269 #endif /* Py_TRACE_REFS */
272 /* Create and initialize a new interpreter and thread, and return the
273 new thread. This requires that Py_Initialize() has been called
276 Unsuccessful initialization yields a NULL pointer. Note that *no*
277 exception information is available even in this case -- the
278 exception information is held in the thread, and there is no
286 Py_NewInterpreter(void)
288 PyInterpreterState
*interp
;
289 PyThreadState
*tstate
, *save_tstate
;
290 PyObject
*bimod
, *sysmod
;
293 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
295 interp
= PyInterpreterState_New();
299 tstate
= PyThreadState_New(interp
);
300 if (tstate
== NULL
) {
301 PyInterpreterState_Delete(interp
);
305 save_tstate
= PyThreadState_Swap(tstate
);
307 /* XXX The following is lax in error checking */
309 interp
->modules
= PyDict_New();
311 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
313 interp
->builtins
= PyModule_GetDict(bimod
);
314 Py_INCREF(interp
->builtins
);
316 sysmod
= _PyImport_FindExtension("sys", "sys");
317 if (bimod
!= NULL
&& sysmod
!= NULL
) {
318 interp
->sysdict
= PyModule_GetDict(sysmod
);
319 Py_INCREF(interp
->sysdict
);
320 PySys_SetPath(Py_GetPath());
321 PyDict_SetItemString(interp
->sysdict
, "modules",
328 if (!PyErr_Occurred())
331 /* Oops, it didn't work. Undo it all. */
334 PyThreadState_Clear(tstate
);
335 PyThreadState_Swap(save_tstate
);
336 PyThreadState_Delete(tstate
);
337 PyInterpreterState_Delete(interp
);
342 /* Delete an interpreter and its last thread. This requires that the
343 given thread state is current, that the thread has no remaining
344 frames, and that it is its interpreter's only remaining thread.
345 It is a fatal error to violate these constraints.
347 (Py_Finalize() doesn't have these constraints -- it zaps
348 everything, regardless.)
355 Py_EndInterpreter(PyThreadState
*tstate
)
357 PyInterpreterState
*interp
= tstate
->interp
;
359 if (tstate
!= PyThreadState_Get())
360 Py_FatalError("Py_EndInterpreter: thread is not current");
361 if (tstate
->frame
!= NULL
)
362 Py_FatalError("Py_EndInterpreter: thread still has a frame");
363 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
364 Py_FatalError("Py_EndInterpreter: not the last thread");
367 PyInterpreterState_Clear(interp
);
368 PyThreadState_Swap(NULL
);
369 PyInterpreterState_Delete(interp
);
372 static char *progname
= "python";
375 Py_SetProgramName(char *pn
)
382 Py_GetProgramName(void)
387 static char *default_home
= NULL
;
390 Py_SetPythonHome(char *home
)
396 Py_GetPythonHome(void)
398 char *home
= default_home
;
400 home
= getenv("PYTHONHOME");
404 /* Create __main__ module */
410 m
= PyImport_AddModule("__main__");
412 Py_FatalError("can't create __main__ module");
413 d
= PyModule_GetDict(m
);
414 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
415 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
417 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
418 Py_FatalError("can't add __builtins__ to __main__");
423 /* Import the site module (not into __main__ though) */
429 m
= PyImport_ImportModule("site");
431 f
= PySys_GetObject("stderr");
432 if (Py_VerboseFlag
) {
434 "'import site' failed; traceback:\n", f
);
439 "'import site' failed; use -v for traceback\n", f
);
448 /* Parse input from a file and execute it */
451 PyRun_AnyFile(FILE *fp
, char *filename
)
453 return PyRun_AnyFileEx(fp
, filename
, 0);
457 PyRun_AnyFileEx(FILE *fp
, char *filename
, int closeit
)
459 if (filename
== NULL
)
461 if (Py_FdIsInteractive(fp
, filename
)) {
462 int err
= PyRun_InteractiveLoop(fp
, filename
);
468 return PyRun_SimpleFileEx(fp
, filename
, closeit
);
472 PyRun_InteractiveLoop(FILE *fp
, char *filename
)
476 v
= PySys_GetObject("ps1");
478 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
481 v
= PySys_GetObject("ps2");
483 PySys_SetObject("ps2", v
= PyString_FromString("... "));
487 ret
= PyRun_InteractiveOne(fp
, filename
);
489 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
501 PyRun_InteractiveOne(FILE *fp
, char *filename
)
503 PyObject
*m
, *d
, *v
, *w
;
506 char *ps1
= "", *ps2
= "";
507 v
= PySys_GetObject("ps1");
512 else if (PyString_Check(v
))
513 ps1
= PyString_AsString(v
);
515 w
= PySys_GetObject("ps2");
520 else if (PyString_Check(w
))
521 ps2
= PyString_AsString(w
);
523 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
,
524 Py_single_input
, ps1
, ps2
, &err
);
528 if (err
.error
== E_EOF
) {
537 m
= PyImport_AddModule("__main__");
540 d
= PyModule_GetDict(m
);
541 v
= run_node(n
, filename
, d
, d
);
553 PyRun_SimpleFile(FILE *fp
, char *filename
)
555 return PyRun_SimpleFileEx(fp
, filename
, 0);
559 PyRun_SimpleFileEx(FILE *fp
, char *filename
, int closeit
)
564 m
= PyImport_AddModule("__main__");
567 d
= PyModule_GetDict(m
);
568 ext
= filename
+ strlen(filename
) - 4;
569 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0
571 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
572 || PyMac_getfiletype(filename
) == 'PYC '
573 || PyMac_getfiletype(filename
) == 'APPL'
574 #endif /* macintosh */
576 /* Try to run a pyc file. First, re-open in binary */
579 if( (fp
= fopen(filename
, "rb")) == NULL
) {
580 fprintf(stderr
, "python: Can't reopen .pyc file\n");
583 /* Turn on optimization if a .pyo file is given */
584 if (strcmp(ext
, ".pyo") == 0)
586 v
= run_pyc_file(fp
, filename
, d
, d
);
588 v
= PyRun_FileEx(fp
, filename
, Py_file_input
, d
, d
, closeit
);
601 PyRun_SimpleString(char *command
)
604 m
= PyImport_AddModule("__main__");
607 d
= PyModule_GetDict(m
);
608 v
= PyRun_String(command
, Py_file_input
, d
, d
);
620 parse_syntax_error(PyObject
*err
, PyObject
**message
, char **filename
,
621 int *lineno
, int *offset
, char **text
)
626 /* old style errors */
627 if (PyTuple_Check(err
))
628 return PyArg_Parse(err
, "(O(ziiz))", message
, filename
,
629 lineno
, offset
, text
);
631 /* new style errors. `err' is an instance */
633 if (! (v
= PyObject_GetAttrString(err
, "msg")))
637 if (!(v
= PyObject_GetAttrString(err
, "filename")))
641 else if (! (*filename
= PyString_AsString(v
)))
645 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
647 hold
= PyInt_AsLong(v
);
650 if (hold
< 0 && PyErr_Occurred())
654 if (!(v
= PyObject_GetAttrString(err
, "offset")))
656 hold
= PyInt_AsLong(v
);
659 if (hold
< 0 && PyErr_Occurred())
663 if (!(v
= PyObject_GetAttrString(err
, "text")))
667 else if (! (*text
= PyString_AsString(v
)))
684 PyErr_PrintEx(int set_sys_last_vars
)
687 PyObject
*exception
, *v
, *tb
, *f
;
688 PyErr_Fetch(&exception
, &v
, &tb
);
689 PyErr_NormalizeException(&exception
, &v
, &tb
);
691 if (exception
== NULL
)
694 if (PyErr_GivenExceptionMatches(exception
, PyExc_SystemExit
)) {
698 if (v
== NULL
|| v
== Py_None
)
700 if (PyInstance_Check(v
)) {
701 /* we expect the error code to be store in the
704 PyObject
*code
= PyObject_GetAttrString(v
, "code");
711 /* if we failed to dig out the "code" attribute,
712 then just let the else clause below print the
717 Py_Exit((int)PyInt_AsLong(v
));
719 /* OK to use real stderr here */
720 PyObject_Print(v
, stderr
, Py_PRINT_RAW
);
721 fprintf(stderr
, "\n");
725 if (set_sys_last_vars
) {
726 PySys_SetObject("last_type", exception
);
727 PySys_SetObject("last_value", v
);
728 PySys_SetObject("last_traceback", tb
);
730 f
= PySys_GetObject("stderr");
732 fprintf(stderr
, "lost sys.stderr\n");
737 err
= PyTraceBack_Print(tb
, f
);
739 PyErr_GivenExceptionMatches(exception
, PyExc_SyntaxError
))
742 char *filename
, *text
;
744 if (!parse_syntax_error(v
, &message
, &filename
,
745 &lineno
, &offset
, &text
))
749 PyFile_WriteString(" File \"", f
);
750 if (filename
== NULL
)
751 PyFile_WriteString("<string>", f
);
753 PyFile_WriteString(filename
, f
);
754 PyFile_WriteString("\", line ", f
);
755 sprintf(buf
, "%d", lineno
);
756 PyFile_WriteString(buf
, f
);
757 PyFile_WriteString("\n", f
);
761 offset
== (int)strlen(text
))
764 nl
= strchr(text
, '\n');
768 offset
-= (nl
+1-text
);
771 while (*text
== ' ' || *text
== '\t') {
775 PyFile_WriteString(" ", f
);
776 PyFile_WriteString(text
, f
);
778 text
[strlen(text
)-1] != '\n')
779 PyFile_WriteString("\n", f
);
780 PyFile_WriteString(" ", f
);
783 PyFile_WriteString(" ", f
);
786 PyFile_WriteString("^\n", f
);
791 /* Can't be bothered to check all those
792 PyFile_WriteString() calls */
793 if (PyErr_Occurred())
798 /* Don't do anything else */
800 else if (PyClass_Check(exception
)) {
801 PyClassObject
* exc
= (PyClassObject
*)exception
;
802 PyObject
* className
= exc
->cl_name
;
803 PyObject
* moduleName
=
804 PyDict_GetItemString(exc
->cl_dict
, "__module__");
806 if (moduleName
== NULL
)
807 err
= PyFile_WriteString("<unknown>", f
);
809 char* modstr
= PyString_AsString(moduleName
);
810 if (modstr
&& strcmp(modstr
, "exceptions"))
812 err
= PyFile_WriteString(modstr
, f
);
813 err
+= PyFile_WriteString(".", f
);
817 if (className
== NULL
)
818 err
= PyFile_WriteString("<unknown>", f
);
820 err
= PyFile_WriteObject(className
, f
,
825 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
827 if (v
!= NULL
&& v
!= Py_None
) {
828 PyObject
*s
= PyObject_Str(v
);
829 /* only print colon if the str() of the
830 object is not the empty string
834 else if (!PyString_Check(s
) ||
835 PyString_GET_SIZE(s
) != 0)
836 err
= PyFile_WriteString(": ", f
);
838 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
843 err
= PyFile_WriteString("\n", f
);
845 Py_XDECREF(exception
);
848 /* If an error happened here, don't show it.
849 XXX This is wrong, but too many callers rely on this behavior. */
855 PyRun_String(char *str
, int start
, PyObject
*globals
, PyObject
*locals
)
857 return run_err_node(PyParser_SimpleParseString(str
, start
),
858 "<string>", globals
, locals
);
862 PyRun_File(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
865 return PyRun_FileEx(fp
, filename
, start
, globals
, locals
, 0);
869 PyRun_FileEx(FILE *fp
, char *filename
, int start
, PyObject
*globals
,
870 PyObject
*locals
, int closeit
)
872 node
*n
= PyParser_SimpleParseFile(fp
, filename
, start
);
875 return run_err_node(n
, filename
, globals
, locals
);
879 run_err_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
)
883 return run_node(n
, filename
, globals
, locals
);
887 run_node(node
*n
, char *filename
, PyObject
*globals
, PyObject
*locals
)
891 co
= PyNode_Compile(n
, filename
);
895 v
= PyEval_EvalCode(co
, globals
, locals
);
901 run_pyc_file(FILE *fp
, char *filename
, PyObject
*globals
, PyObject
*locals
)
906 long PyImport_GetMagicNumber(void);
908 magic
= PyMarshal_ReadLongFromFile(fp
);
909 if (magic
!= PyImport_GetMagicNumber()) {
910 PyErr_SetString(PyExc_RuntimeError
,
911 "Bad magic number in .pyc file");
914 (void) PyMarshal_ReadLongFromFile(fp
);
915 v
= PyMarshal_ReadObjectFromFile(fp
);
917 if (v
== NULL
|| !PyCode_Check(v
)) {
919 PyErr_SetString(PyExc_RuntimeError
,
920 "Bad code object in .pyc file");
923 co
= (PyCodeObject
*)v
;
924 v
= PyEval_EvalCode(co
, globals
, locals
);
930 Py_CompileString(char *str
, char *filename
, int start
)
934 n
= PyParser_SimpleParseString(str
, start
);
937 co
= PyNode_Compile(n
, filename
);
939 return (PyObject
*)co
;
942 /* Simplified interface to parsefile -- return node or set exception */
945 PyParser_SimpleParseFile(FILE *fp
, char *filename
, int start
)
949 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
, start
,
950 (char *)0, (char *)0, &err
);
956 /* Simplified interface to parsestring -- return node or set exception */
959 PyParser_SimpleParseString(char *str
, int start
)
963 n
= PyParser_ParseString(str
, &_PyParser_Grammar
, start
, &err
);
969 /* Set the error appropriate to the given input error code (see errcode.h) */
972 err_input(perrdetail
*err
)
974 PyObject
*v
, *w
, *errtype
;
976 errtype
= PyExc_SyntaxError
;
977 v
= Py_BuildValue("(ziiz)", err
->filename
,
978 err
->lineno
, err
->offset
, err
->text
);
979 if (err
->text
!= NULL
) {
980 PyMem_DEL(err
->text
);
983 switch (err
->error
) {
985 errtype
= PyExc_IndentationError
;
986 if (err
->expected
== INDENT
)
987 msg
= "expected an indented block";
988 else if (err
->token
== INDENT
)
989 msg
= "unexpected indent";
990 else if (err
->token
== DEDENT
)
991 msg
= "unexpected unindent";
993 errtype
= PyExc_SyntaxError
;
994 msg
= "invalid syntax";
998 msg
= "invalid token";
1001 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1009 msg
= "unexpected EOF while parsing";
1012 errtype
= PyExc_TabError
;
1013 msg
= "inconsistent use of tabs and spaces in indentation";
1016 msg
= "expression too long";
1019 errtype
= PyExc_IndentationError
;
1020 msg
= "unindent does not match any outer indentation level";
1023 errtype
= PyExc_IndentationError
;
1024 msg
= "too many levels of indentation";
1027 fprintf(stderr
, "error=%d\n", err
->error
);
1028 msg
= "unknown parsing error";
1031 w
= Py_BuildValue("(sO)", msg
, v
);
1032 PyErr_SetObject(errtype
, w
);
1038 PyErr_Fetch(&errtype
, &exc
, &tb
);
1039 PyErr_NormalizeException(&errtype
, &exc
, &tb
);
1040 if (PyObject_SetAttrString(exc
, "filename",
1041 PyTuple_GET_ITEM(v
, 0)))
1043 if (PyObject_SetAttrString(exc
, "lineno",
1044 PyTuple_GET_ITEM(v
, 1)))
1046 if (PyObject_SetAttrString(exc
, "offset",
1047 PyTuple_GET_ITEM(v
, 2)))
1050 PyErr_Restore(errtype
, exc
, tb
);
1054 /* Print fatal error message and abort */
1057 Py_FatalError(char *msg
)
1059 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1064 OutputDebugString("Fatal Python error: ");
1065 OutputDebugString(msg
);
1066 OutputDebugString("\n");
1070 #endif /* MS_WIN32 */
1074 /* Clean up and exit */
1077 #include "pythread.h"
1078 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1081 #define NEXITFUNCS 32
1082 static void (*exitfuncs
[NEXITFUNCS
])(void);
1083 static int nexitfuncs
= 0;
1085 int Py_AtExit(void (*func
)(void))
1087 if (nexitfuncs
>= NEXITFUNCS
)
1089 exitfuncs
[nexitfuncs
++] = func
;
1094 call_sys_exitfunc(void)
1096 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1100 Py_INCREF(exitfunc
);
1101 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1102 f
= PySys_GetObject("stderr");
1103 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1106 PyFile_WriteString("Error in sys.exitfunc:\n", f
);
1109 Py_DECREF(exitfunc
);
1117 call_ll_exitfuncs(void)
1119 while (nexitfuncs
> 0)
1120 (*exitfuncs
[--nexitfuncs
])();
1141 #ifdef HAVE_SIGNAL_H
1143 signal(SIGPIPE
, SIG_IGN
);
1145 #endif /* HAVE_SIGNAL_H */
1146 PyOS_InitInterrupts(); /* May imply initsignal() */
1149 #ifdef Py_TRACE_REFS
1150 /* Ask a yes/no question */
1153 _Py_AskYesNo(char *prompt
)
1157 printf("%s [ny] ", prompt
);
1158 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1160 return buf
[0] == 'y' || buf
[0] == 'Y';
1166 /* Check for file descriptor connected to interactive device.
1167 Pretend that stdin is always interactive, other files never. */
1172 return fd
== fileno(stdin
);
1178 * The file descriptor fd is considered ``interactive'' if either
1179 * a) isatty(fd) is TRUE, or
1180 * b) the -i flag was given, and the filename associated with
1181 * the descriptor is NULL or "<stdin>" or "???".
1184 Py_FdIsInteractive(FILE *fp
, char *filename
)
1186 if (isatty((int)fileno(fp
)))
1188 if (!Py_InteractiveFlag
)
1190 return (filename
== NULL
) ||
1191 (strcmp(filename
, "<stdin>") == 0) ||
1192 (strcmp(filename
, "???") == 0);
1196 #if defined(USE_STACKCHECK)
1197 #if defined(WIN32) && defined(_MSC_VER)
1199 /* Stack checking for Microsoft C */
1205 * Return non-zero when we run out of memory on the stack; zero otherwise.
1208 PyOS_CheckStack(void)
1211 /* _alloca throws a stack overflow exception if there's
1212 not enough space left on the stack */
1213 _alloca(PYOS_STACK_MARGIN
* sizeof(void*));
1215 } __except (EXCEPTION_EXECUTE_HANDLER
) {
1216 /* just ignore all errors */
1221 #endif /* WIN32 && _MSC_VER */
1223 /* Alternate implementations can be added here... */
1225 #endif /* USE_STACKCHECK */
1228 /* Wrappers around sigaction() or signal(). */
1231 PyOS_getsig(int sig
)
1233 #ifdef HAVE_SIGACTION
1234 struct sigaction context
;
1235 sigaction(sig
, NULL
, &context
);
1236 return context
.sa_handler
;
1238 PyOS_sighandler_t handler
;
1239 handler
= signal(sig
, SIG_IGN
);
1240 signal(sig
, handler
);
1246 PyOS_setsig(int sig
, PyOS_sighandler_t handler
)
1248 #ifdef HAVE_SIGACTION
1249 struct sigaction context
;
1250 PyOS_sighandler_t oldhandler
;
1251 sigaction(sig
, NULL
, &context
);
1252 oldhandler
= context
.sa_handler
;
1253 context
.sa_handler
= handler
;
1254 sigaction(sig
, &context
, NULL
);
1257 return signal(sig
, handler
);