blob: fbc3b16932d6b1ccb5e1cf4e2ea164f92921f73c [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
6#include "grammar.h"
7#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +00008#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00009#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000010#include "errcode.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000012#include "symtable.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000014#include "marshal.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Guido van Rossum80bb9651996-12-05 23:27:02 +000016#ifdef HAVE_UNISTD_H
17#include <unistd.h>
18#endif
19
Guido van Rossuma110aa61994-08-29 12:50:44 +000020#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000021#include <signal.h>
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022#endif
23
Guido van Rossum9b38a141996-09-11 23:12:24 +000024#ifdef MS_WIN32
Guido van Rossuma44823b1995-03-14 15:01:17 +000025#undef BYTE
26#include "windows.h"
27#endif
28
Jack Jansencbf630f2000-07-11 21:59:16 +000029#ifdef macintosh
30#include "macglue.h"
31#endif
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000032extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000033
Guido van Rossum82598051997-03-05 00:20:32 +000034extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000035
Guido van Rossumb73cc041993-11-01 16:28:59 +000036/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000037static void initmain(void);
38static void initsite(void);
Jeremy Hylton9f324e92001-03-01 22:59:14 +000039static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
40 PyCompilerFlags *);
41static PyObject *run_node(node *, char *, PyObject *, PyObject *,
42 PyCompilerFlags *);
Jeremy Hyltonbc320242001-03-22 02:47:58 +000043static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
44 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000045static void err_input(perrdetail *);
46static void initsigs(void);
47static void call_sys_exitfunc(void);
48static void call_ll_exitfuncs(void);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000049
Guido van Rossumbffd6832000-01-20 22:32:56 +000050#ifdef Py_TRACE_REFS
51int _Py_AskYesNo(char *prompt);
52#endif
53
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000054extern void _PyUnicode_Init(void);
55extern void _PyUnicode_Fini(void);
56extern void _PyCodecRegistry_Init(void);
57extern void _PyCodecRegistry_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000058
Guido van Rossum82598051997-03-05 00:20:32 +000059int Py_DebugFlag; /* Needed by parser.c */
60int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000061int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000062int Py_NoSiteFlag; /* Suppress 'import site' */
Barry Warsaw3ce09642000-05-02 19:18:59 +000063int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000064int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000065int Py_UnicodeFlag = 0; /* Needed by compile.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000066
Guido van Rossum25ce5661997-08-02 03:10:38 +000067static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000068
Thomas Wouters7e474022000-07-16 12:04:32 +000069/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000070
71int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000073{
74 return initialized;
75}
76
Guido van Rossum25ce5661997-08-02 03:10:38 +000077/* 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
81 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +000082
Guido van Rossum25ce5661997-08-02 03:10:38 +000083 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.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000086
Guido van Rossum25ce5661997-08-02 03:10:38 +000087*/
Guido van Rossuma027efa1997-05-05 20:56:21 +000088
89void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000090Py_Initialize(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000091{
Guido van Rossuma027efa1997-05-05 20:56:21 +000092 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +000093 PyThreadState *tstate;
94 PyObject *bimod, *sysmod;
Guido van Rossumad6dfda1997-07-19 19:17:22 +000095 char *p;
Guido van Rossumad6dfda1997-07-19 19:17:22 +000096
Guido van Rossumdcc0c131997-08-29 22:32:42 +000097 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +000098 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +000099 initialized = 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000101 if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000102 Py_DebugFlag = Py_DebugFlag ? Py_DebugFlag : 1;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000103 if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000104 Py_VerboseFlag = Py_VerboseFlag ? Py_VerboseFlag : 1;
Guido van Rossum562f5b11998-10-07 14:50:42 +0000105 if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
Marc-André Lemburgdc3d6062000-08-25 21:00:46 +0000106 Py_OptimizeFlag = Py_OptimizeFlag ? Py_OptimizeFlag : 1;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000107
Guido van Rossuma027efa1997-05-05 20:56:21 +0000108 interp = PyInterpreterState_New();
109 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000111
Guido van Rossuma027efa1997-05-05 20:56:21 +0000112 tstate = PyThreadState_New(interp);
113 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000115 (void) PyThreadState_Swap(tstate);
116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 interp->modules = PyDict_New();
118 if (interp->modules == NULL)
119 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120
Guido van Rossumc94044c2000-03-10 23:03:54 +0000121 /* Init codec registry */
122 _PyCodecRegistry_Init();
123
124 /* Init Unicode implementation; relies on the codec registry */
125 _PyUnicode_Init();
126
Barry Warsawf242aa02000-05-25 23:09:49 +0000127 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128 if (bimod == NULL)
129 Py_FatalError("Py_Initialize: can't initialize __builtin__");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000130 interp->builtins = PyModule_GetDict(bimod);
131 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132
133 sysmod = _PySys_Init();
134 if (sysmod == NULL)
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");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000139 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 PyDict_SetItemString(interp->sysdict, "modules",
141 interp->modules);
142
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000143 _PyImport_Init();
144
Barry Warsawf242aa02000-05-25 23:09:49 +0000145 /* initialize builtin exceptions */
146 init_exceptions();
147
Barry Warsaw035574d1997-08-29 22:07:17 +0000148 /* phase 2 of builtins */
Barry Warsaw963b8711997-09-18 16:42:02 +0000149 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000150
Guido van Rossum25ce5661997-08-02 03:10:38 +0000151 initsigs(); /* Signal handling stuff, including initintr() */
152
153 initmain(); /* Module __main__ */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000154 if (!Py_NoSiteFlag)
155 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000156}
157
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000158#ifdef COUNT_ALLOCS
Tim Petersdbd9ba62000-07-09 03:09:57 +0000159extern void dump_counts(void);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000160#endif
161
Guido van Rossum25ce5661997-08-02 03:10:38 +0000162/* Undo the effect of Py_Initialize().
163
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.
168
169 (XXX We should do better, e.g. wipe out all interpreters and
170 threads.)
171
172 Locking: as above.
173
174*/
175
176void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000177Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000178{
179 PyInterpreterState *interp;
180 PyThreadState *tstate;
181
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000182 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000183 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000184
Tim Peters384fd102001-01-21 03:40:37 +0000185 /* 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.
193 */
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000194 call_sys_exitfunc();
Tim Peters384fd102001-01-21 03:40:37 +0000195 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000196
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000197 /* Get current thread state and interpreter pointer */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198 tstate = PyThreadState_Get();
199 interp = tstate->interp;
200
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000201 /* Disable signal handling */
202 PyOS_FiniInterrupts();
203
Guido van Rossumc94044c2000-03-10 23:03:54 +0000204 /* Cleanup Unicode implementation */
205 _PyUnicode_Fini();
206
207 /* Cleanup Codec registry */
208 _PyCodecRegistry_Fini();
209
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000210 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000212
Guido van Rossum1707aad1997-12-08 23:43:45 +0000213 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
214 _PyImport_Fini();
215
216 /* Debugging stuff */
217#ifdef COUNT_ALLOCS
218 dump_counts();
219#endif
220
221#ifdef Py_REF_DEBUG
222 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
223#endif
224
225#ifdef Py_TRACE_REFS
Guido van Rossumeca47842000-04-27 23:44:15 +0000226 if (
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?")) {
Guido van Rossum1707aad1997-12-08 23:43:45 +0000231 _Py_PrintReferences(stderr);
232 }
233#endif /* Py_TRACE_REFS */
234
Barry Warsaw035574d1997-08-29 22:07:17 +0000235 /* 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
238 raised.
239 */
Barry Warsawf242aa02000-05-25 23:09:49 +0000240 fini_exceptions();
241
242 /* Delete current thread */
243 PyInterpreterState_Clear(interp);
244 PyThreadState_Swap(NULL);
245 PyInterpreterState_Delete(interp);
246
Guido van Rossumcc283f51997-08-05 02:22:03 +0000247 PyMethod_Fini();
248 PyFrame_Fini();
249 PyCFunction_Fini();
250 PyTuple_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000251 PyString_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000252 PyInt_Fini();
253 PyFloat_Fini();
254
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
259 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260
261 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000262
263 call_ll_exitfuncs();
264
Guido van Rossumcc283f51997-08-05 02:22:03 +0000265#ifdef Py_TRACE_REFS
Guido van Rossumcc283f51997-08-05 02:22:03 +0000266 _Py_ResetReferences();
267#endif /* Py_TRACE_REFS */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268}
269
270/* Create and initialize a new interpreter and thread, and return the
271 new thread. This requires that Py_Initialize() has been called
272 first.
273
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
277 thread.
278
279 Locking: as above.
280
281*/
282
283PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000284Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000285{
286 PyInterpreterState *interp;
287 PyThreadState *tstate, *save_tstate;
288 PyObject *bimod, *sysmod;
289
290 if (!initialized)
291 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
292
293 interp = PyInterpreterState_New();
294 if (interp == NULL)
295 return NULL;
296
297 tstate = PyThreadState_New(interp);
298 if (tstate == NULL) {
299 PyInterpreterState_Delete(interp);
300 return NULL;
301 }
302
303 save_tstate = PyThreadState_Swap(tstate);
304
305 /* XXX The following is lax in error checking */
306
307 interp->modules = PyDict_New();
308
309 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
310 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000311 interp->builtins = PyModule_GetDict(bimod);
312 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313 }
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",
320 interp->modules);
321 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000322 if (!Py_NoSiteFlag)
323 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000324 }
325
326 if (!PyErr_Occurred())
327 return tstate;
328
329 /* Oops, it didn't work. Undo it all. */
330
331 PyErr_Print();
332 PyThreadState_Clear(tstate);
333 PyThreadState_Swap(save_tstate);
334 PyThreadState_Delete(tstate);
335 PyInterpreterState_Delete(interp);
336
337 return NULL;
338}
339
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.
344
345 (Py_Finalize() doesn't have these constraints -- it zaps
346 everything, regardless.)
347
348 Locking: as above.
349
350*/
351
352void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000353Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000354{
355 PyInterpreterState *interp = tstate->interp;
356
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");
363
364 PyImport_Cleanup();
365 PyInterpreterState_Clear(interp);
366 PyThreadState_Swap(NULL);
367 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000368}
369
370static char *progname = "python";
371
372void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000374{
375 if (pn && *pn)
376 progname = pn;
377}
378
379char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000380Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000381{
382 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000383}
384
Guido van Rossuma61691e1998-02-06 22:27:24 +0000385static char *default_home = NULL;
386
387void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000388Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000389{
390 default_home = home;
391}
392
393char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000394Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000395{
396 char *home = default_home;
397 if (home == NULL)
398 home = getenv("PYTHONHOME");
399 return home;
400}
401
Guido van Rossum6135a871995-01-09 17:53:26 +0000402/* Create __main__ module */
403
404static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000405initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000406{
Guido van Rossum82598051997-03-05 00:20:32 +0000407 PyObject *m, *d;
408 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000409 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000410 Py_FatalError("can't create __main__ module");
411 d = PyModule_GetDict(m);
412 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Guido van Rossum858cb731997-11-19 16:15:37 +0000413 PyObject *bimod = PyImport_ImportModule("__builtin__");
414 if (bimod == NULL ||
415 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000416 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000417 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000418 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000419}
420
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000421/* Import the site module (not into __main__ though) */
422
423static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000424initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000425{
426 PyObject *m, *f;
427 m = PyImport_ImportModule("site");
428 if (m == NULL) {
429 f = PySys_GetObject("stderr");
430 if (Py_VerboseFlag) {
431 PyFile_WriteString(
432 "'import site' failed; traceback:\n", f);
433 PyErr_Print();
434 }
435 else {
436 PyFile_WriteString(
437 "'import site' failed; use -v for traceback\n", f);
438 PyErr_Clear();
439 }
440 }
441 else {
442 Py_DECREF(m);
443 }
444}
445
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000446/* Parse input from a file and execute it */
447
448int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000449PyRun_AnyFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000450{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000451 return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
452}
453
454int
455PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
456{
457 return PyRun_AnyFileExFlags(fp, filename, 0, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000458}
459
460int
461PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
462{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000463 return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
464}
465
466int
467PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
468 PyCompilerFlags *flags)
469{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000470 if (filename == NULL)
471 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000472 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000473 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000474 if (closeit)
475 fclose(fp);
476 return err;
477 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000478 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000479 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000480}
481
482int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000483PyRun_InteractiveLoop(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000484{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000485 return PyRun_InteractiveLoopFlags(fp, filename, NULL);
486}
487
488int
489PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
490{
Guido van Rossum82598051997-03-05 00:20:32 +0000491 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000492 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000493 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000494
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000495 if (flags == NULL) {
496 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000497 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000498 }
Guido van Rossum82598051997-03-05 00:20:32 +0000499 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000500 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000501 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
502 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000503 }
Guido van Rossum82598051997-03-05 00:20:32 +0000504 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000505 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000506 PySys_SetObject("ps2", v = PyString_FromString("... "));
507 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000508 }
509 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000510 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Guido van Rossumaae0d321996-05-22 16:35:33 +0000511#ifdef Py_REF_DEBUG
Guido van Rossum6f9e4331995-03-29 16:57:48 +0000512 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000513#endif
514 if (ret == E_EOF)
515 return 0;
516 /*
517 if (ret == E_NOMEM)
518 return -1;
519 */
520 }
521}
522
523int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000524PyRun_InteractiveOne(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000525{
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000526 return PyRun_InteractiveOneFlags(fp, filename, NULL);
527}
528
529int
530PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
531{
Guido van Rossum82598051997-03-05 00:20:32 +0000532 PyObject *m, *d, *v, *w;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000533 node *n;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000534 perrdetail err;
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000535 char *ps1 = "", *ps2 = "";
Tim Petersfe2127d2001-07-16 05:37:24 +0000536
Guido van Rossum82598051997-03-05 00:20:32 +0000537 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000538 if (v != NULL) {
539 v = PyObject_Str(v);
540 if (v == NULL)
541 PyErr_Clear();
542 else if (PyString_Check(v))
543 ps1 = PyString_AsString(v);
544 }
Guido van Rossum82598051997-03-05 00:20:32 +0000545 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000546 if (w != NULL) {
547 w = PyObject_Str(w);
548 if (w == NULL)
549 PyErr_Clear();
550 else if (PyString_Check(w))
551 ps2 = PyString_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000552 }
Tim Petersfe2127d2001-07-16 05:37:24 +0000553 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
554 Py_single_input, ps1, ps2, &err,
555 (flags &&
556 flags->cf_flags & PyCF_GENERATORS) ?
557 PyPARSE_YIELD_IS_KEYWORD : 0);
Guido van Rossum82598051997-03-05 00:20:32 +0000558 Py_XDECREF(v);
559 Py_XDECREF(w);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000560 if (n == NULL) {
561 if (err.error == E_EOF) {
562 if (err.text)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000563 PyMem_DEL(err.text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000564 return E_EOF;
565 }
566 err_input(&err);
Guido van Rossum82598051997-03-05 00:20:32 +0000567 PyErr_Print();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000568 return err.error;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000569 }
Guido van Rossum82598051997-03-05 00:20:32 +0000570 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000571 if (m == NULL)
572 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000573 d = PyModule_GetDict(m);
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000574 v = run_node(n, filename, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000575 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000576 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000577 return -1;
578 }
Guido van Rossum82598051997-03-05 00:20:32 +0000579 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000580 if (Py_FlushLine())
581 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000582 return 0;
583}
584
585int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000586PyRun_SimpleFile(FILE *fp, char *filename)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000587{
Guido van Rossum0df002c2000-08-27 19:21:52 +0000588 return PyRun_SimpleFileEx(fp, filename, 0);
589}
590
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000591/* Check whether a file maybe a pyc file: Look at the extension,
592 the file type, and, if we may close it, at the first few bytes. */
593
594static int
595maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit)
596{
597 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
598 return 1;
599
600#ifdef macintosh
601 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
602 if (PyMac_getfiletype(filename) == 'PYC '
603 || PyMac_getfiletype(filename) == 'APPL')
604 return 1;
605#endif /* macintosh */
606
607 /* Only look into the file if we are allowed to close it, since
608 it then should also be seekable. */
609 if (closeit) {
610 /* Read only two bytes of the magic. If the file was opened in
611 text mode, the bytes 3 and 4 of the magic (\r\n) might not
612 be read as they are on disk. */
613 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
614 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000615 /* Mess: In case of -x, the stream is NOT at its start now,
616 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000617 which makes the current stream position formally undefined,
618 and a x-platform nightmare.
619 Unfortunately, we have no direct way to know whether -x
620 was specified. So we use a terrible hack: if the current
621 stream position is not 0, we assume -x was specified, and
622 give up. Bug 132850 on SourceForge spells out the
623 hopelessness of trying anything else (fseek and ftell
624 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000625 */
Tim Peters3e876562001-02-11 04:35:39 +0000626 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000627 if (ftell(fp) == 0) {
628 if (fread(buf, 1, 2, fp) == 2 &&
629 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
630 ispyc = 1;
631 rewind(fp);
632 }
Tim Peters3e876562001-02-11 04:35:39 +0000633 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000634 }
635 return 0;
636}
637
Guido van Rossum0df002c2000-08-27 19:21:52 +0000638int
639PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit)
640{
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000641 return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL);
642}
643
644int
645PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit,
646 PyCompilerFlags *flags)
647{
Guido van Rossum82598051997-03-05 00:20:32 +0000648 PyObject *m, *d, *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000649 char *ext;
650
Guido van Rossum82598051997-03-05 00:20:32 +0000651 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000652 if (m == NULL)
653 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000654 d = PyModule_GetDict(m);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000655 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000656 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +0000657 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +0000658 if (closeit)
659 fclose(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000660 if( (fp = fopen(filename, "rb")) == NULL ) {
661 fprintf(stderr, "python: Can't reopen .pyc file\n");
662 return -1;
663 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +0000664 /* Turn on optimization if a .pyo file is given */
665 if (strcmp(ext, ".pyo") == 0)
666 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000667 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000668 } else {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000669 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
670 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +0000671 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000672 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000673 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000674 return -1;
675 }
Guido van Rossum82598051997-03-05 00:20:32 +0000676 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000677 if (Py_FlushLine())
678 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000679 return 0;
680}
681
682int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000683PyRun_SimpleString(char *command)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000684{
Guido van Rossum82598051997-03-05 00:20:32 +0000685 PyObject *m, *d, *v;
686 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000687 if (m == NULL)
688 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +0000689 d = PyModule_GetDict(m);
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000690 v = PyRun_String(command, Py_file_input, d, d);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000691 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000692 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000693 return -1;
694 }
Guido van Rossum82598051997-03-05 00:20:32 +0000695 Py_DECREF(v);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000696 if (Py_FlushLine())
697 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000698 return 0;
699}
700
Barry Warsaw035574d1997-08-29 22:07:17 +0000701static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000702parse_syntax_error(PyObject *err, PyObject **message, char **filename,
703 int *lineno, int *offset, char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000704{
705 long hold;
706 PyObject *v;
707
708 /* old style errors */
709 if (PyTuple_Check(err))
710 return PyArg_Parse(err, "(O(ziiz))", message, filename,
711 lineno, offset, text);
712
713 /* new style errors. `err' is an instance */
714
715 if (! (v = PyObject_GetAttrString(err, "msg")))
716 goto finally;
717 *message = v;
718
719 if (!(v = PyObject_GetAttrString(err, "filename")))
720 goto finally;
721 if (v == Py_None)
722 *filename = NULL;
723 else if (! (*filename = PyString_AsString(v)))
724 goto finally;
725
726 Py_DECREF(v);
727 if (!(v = PyObject_GetAttrString(err, "lineno")))
728 goto finally;
729 hold = PyInt_AsLong(v);
730 Py_DECREF(v);
731 v = NULL;
732 if (hold < 0 && PyErr_Occurred())
733 goto finally;
734 *lineno = (int)hold;
735
736 if (!(v = PyObject_GetAttrString(err, "offset")))
737 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000738 if (v == Py_None) {
739 *offset = -1;
740 Py_DECREF(v);
741 v = NULL;
742 } else {
743 hold = PyInt_AsLong(v);
744 Py_DECREF(v);
745 v = NULL;
746 if (hold < 0 && PyErr_Occurred())
747 goto finally;
748 *offset = (int)hold;
749 }
Barry Warsaw035574d1997-08-29 22:07:17 +0000750
751 if (!(v = PyObject_GetAttrString(err, "text")))
752 goto finally;
753 if (v == Py_None)
754 *text = NULL;
755 else if (! (*text = PyString_AsString(v)))
756 goto finally;
757 Py_DECREF(v);
758 return 1;
759
760finally:
761 Py_XDECREF(v);
762 return 0;
763}
764
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000765void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000766PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000767{
Guido van Rossuma61691e1998-02-06 22:27:24 +0000768 PyErr_PrintEx(1);
769}
770
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000771static void
772print_error_text(PyObject *f, int offset, char *text)
773{
774 char *nl;
775 if (offset >= 0) {
776 if (offset > 0 && offset == (int)strlen(text))
777 offset--;
778 for (;;) {
779 nl = strchr(text, '\n');
780 if (nl == NULL || nl-text >= offset)
781 break;
782 offset -= (nl+1-text);
783 text = nl+1;
784 }
785 while (*text == ' ' || *text == '\t') {
786 text++;
787 offset--;
788 }
789 }
790 PyFile_WriteString(" ", f);
791 PyFile_WriteString(text, f);
792 if (*text == '\0' || text[strlen(text)-1] != '\n')
793 PyFile_WriteString("\n", f);
794 if (offset == -1)
795 return;
796 PyFile_WriteString(" ", f);
797 offset--;
798 while (offset > 0) {
799 PyFile_WriteString(" ", f);
800 offset--;
801 }
802 PyFile_WriteString("^\n", f);
803}
804
Guido van Rossum66e8e862001-03-23 17:54:43 +0000805static void
806handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000807{
Guido van Rossum66e8e862001-03-23 17:54:43 +0000808 PyObject *exception, *value, *tb;
809 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +0000810 if (Py_FlushLine())
811 PyErr_Clear();
812 fflush(stdout);
813 if (value == NULL || value == Py_None)
814 Py_Exit(0);
815 if (PyInstance_Check(value)) {
816 /* The error code should be in the `code' attribute. */
817 PyObject *code = PyObject_GetAttrString(value, "code");
818 if (code) {
819 Py_DECREF(value);
820 value = code;
821 if (value == Py_None)
822 Py_Exit(0);
823 }
824 /* If we failed to dig out the 'code' attribute,
825 just let the else clause below print the error. */
826 }
827 if (PyInt_Check(value))
828 Py_Exit((int)PyInt_AsLong(value));
829 else {
830 PyObject_Print(value, stderr, Py_PRINT_RAW);
831 PySys_WriteStderr("\n");
832 Py_Exit(1);
833 }
834}
835
836void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000837PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000838{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000839 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000840
841 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
842 handle_system_exit();
843 }
Guido van Rossum82598051997-03-05 00:20:32 +0000844 PyErr_Fetch(&exception, &v, &tb);
Barry Warsaw035574d1997-08-29 22:07:17 +0000845 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000846 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +0000847 return;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000848 if (set_sys_last_vars) {
849 PySys_SetObject("last_type", exception);
850 PySys_SetObject("last_value", v);
851 PySys_SetObject("last_traceback", tb);
852 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000853 hook = PySys_GetObject("excepthook");
854 if (hook) {
855 PyObject *args = Py_BuildValue("(OOO)",
856 exception, v ? v : Py_None, tb ? tb : Py_None);
857 PyObject *result = PyEval_CallObject(hook, args);
858 if (result == NULL) {
859 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +0000860 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
861 handle_system_exit();
862 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000863 PyErr_Fetch(&exception2, &v2, &tb2);
864 PyErr_NormalizeException(&exception2, &v2, &tb2);
865 if (Py_FlushLine())
866 PyErr_Clear();
867 fflush(stdout);
868 PySys_WriteStderr("Error in sys.excepthook:\n");
869 PyErr_Display(exception2, v2, tb2);
870 PySys_WriteStderr("\nOriginal exception was:\n");
871 PyErr_Display(exception, v, tb);
872 }
873 Py_XDECREF(result);
874 Py_XDECREF(args);
875 } else {
876 PySys_WriteStderr("sys.excepthook is missing\n");
877 PyErr_Display(exception, v, tb);
878 }
879 Py_XDECREF(exception);
880 Py_XDECREF(v);
881 Py_XDECREF(tb);
882}
883
884void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
885{
886 int err = 0;
887 PyObject *v = value;
888 PyObject *f = PySys_GetObject("stderr");
Guido van Rossum3165fe61992-09-25 21:59:05 +0000889 if (f == NULL)
890 fprintf(stderr, "lost sys.stderr\n");
891 else {
Guido van Rossum0829c751998-02-28 04:31:39 +0000892 if (Py_FlushLine())
893 PyErr_Clear();
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000894 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000895 if (tb && tb != Py_None)
896 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +0000897 if (err == 0 &&
898 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
899 {
Guido van Rossum82598051997-03-05 00:20:32 +0000900 PyObject *message;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000901 char *filename, *text;
902 int lineno, offset;
Barry Warsaw035574d1997-08-29 22:07:17 +0000903 if (!parse_syntax_error(v, &message, &filename,
904 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +0000905 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000906 else {
907 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +0000908 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000909 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000910 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000911 else
Guido van Rossum82598051997-03-05 00:20:32 +0000912 PyFile_WriteString(filename, f);
913 PyFile_WriteString("\", line ", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000914 sprintf(buf, "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +0000915 PyFile_WriteString(buf, f);
916 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +0000917 if (text != NULL)
918 print_error_text(f, offset, text);
Guido van Rossuma110aa61994-08-29 12:50:44 +0000919 v = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000920 /* Can't be bothered to check all those
921 PyFile_WriteString() calls */
922 if (PyErr_Occurred())
923 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +0000924 }
925 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000926 if (err) {
927 /* Don't do anything else */
928 }
929 else if (PyClass_Check(exception)) {
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000930 PyClassObject* exc = (PyClassObject*)exception;
931 PyObject* className = exc->cl_name;
932 PyObject* moduleName =
933 PyDict_GetItemString(exc->cl_dict, "__module__");
934
935 if (moduleName == NULL)
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000936 err = PyFile_WriteString("<unknown>", f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +0000937 else {
938 char* modstr = PyString_AsString(moduleName);
939 if (modstr && strcmp(modstr, "exceptions"))
940 {
941 err = PyFile_WriteString(modstr, f);
942 err += PyFile_WriteString(".", f);
943 }
944 }
945 if (err == 0) {
946 if (className == NULL)
947 err = PyFile_WriteString("<unknown>", f);
948 else
949 err = PyFile_WriteObject(className, f,
950 Py_PRINT_RAW);
951 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000952 }
953 else
954 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
955 if (err == 0) {
956 if (v != NULL && v != Py_None) {
Barry Warsaw035574d1997-08-29 22:07:17 +0000957 PyObject *s = PyObject_Str(v);
958 /* only print colon if the str() of the
959 object is not the empty string
960 */
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000961 if (s == NULL)
962 err = -1;
963 else if (!PyString_Check(s) ||
964 PyString_GET_SIZE(s) != 0)
Barry Warsaw035574d1997-08-29 22:07:17 +0000965 err = PyFile_WriteString(": ", f);
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000966 if (err == 0)
Guido van Rossumd6bf45b1997-09-05 19:11:53 +0000967 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
968 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +0000969 }
Guido van Rossum262e1241995-02-07 15:30:45 +0000970 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000971 if (err == 0)
972 err = PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000973 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +0000974 /* If an error happened here, don't show it.
975 XXX This is wrong, but too many callers rely on this behavior. */
976 if (err != 0)
977 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000978}
979
Guido van Rossum82598051997-03-05 00:20:32 +0000980PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000981PyRun_String(char *str, int start, PyObject *globals, PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000982{
Guido van Rossum82598051997-03-05 00:20:32 +0000983 return run_err_node(PyParser_SimpleParseString(str, start),
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000984 "<string>", globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000985}
986
Guido van Rossum82598051997-03-05 00:20:32 +0000987PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000988PyRun_File(FILE *fp, char *filename, int start, PyObject *globals,
989 PyObject *locals)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990{
Tim Peterse8682112000-08-27 20:18:17 +0000991 return PyRun_FileEx(fp, filename, start, globals, locals, 0);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000992}
993
994PyObject *
995PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000996 PyObject *locals, int closeit)
Guido van Rossum0df002c2000-08-27 19:21:52 +0000997{
998 node *n = PyParser_SimpleParseFile(fp, filename, start);
999 if (closeit)
1000 fclose(fp);
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001001 return run_err_node(n, filename, globals, locals, NULL);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001002}
1003
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001004PyObject *
1005PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals,
1006 PyCompilerFlags *flags)
1007{
Guido van Rossuma1b3a472001-07-16 16:51:33 +00001008 return run_err_node(PyParser_SimpleParseStringFlags(
1009 str, start,
1010 (flags && flags->cf_flags & PyCF_GENERATORS) ?
1011 PyPARSE_YIELD_IS_KEYWORD : 0),
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001012 "<string>", globals, locals, flags);
1013}
1014
1015PyObject *
1016PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals,
1017 PyObject *locals, PyCompilerFlags *flags)
1018{
1019 return PyRun_FileExFlags(fp, filename, start, globals, locals, 0,
1020 flags);
1021}
1022
1023PyObject *
1024PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals,
1025 PyObject *locals, int closeit, PyCompilerFlags *flags)
1026{
Tim Petersfe2127d2001-07-16 05:37:24 +00001027 node *n = PyParser_SimpleParseFileFlags(fp, filename, start,
1028 (flags && flags->cf_flags & PyCF_GENERATORS) ?
1029 PyPARSE_YIELD_IS_KEYWORD : 0);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001030 if (closeit)
1031 fclose(fp);
1032 return run_err_node(n, filename, globals, locals, flags);
1033}
1034
Guido van Rossum82598051997-03-05 00:20:32 +00001035static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001036run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1037 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001038{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001039 if (n == NULL)
1040 return NULL;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001041 return run_node(n, filename, globals, locals, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001042}
1043
Guido van Rossum82598051997-03-05 00:20:32 +00001044static PyObject *
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001045run_node(node *n, char *filename, PyObject *globals, PyObject *locals,
1046 PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001047{
Guido van Rossum82598051997-03-05 00:20:32 +00001048 PyCodeObject *co;
1049 PyObject *v;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001050 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001051 PyNode_Free(n);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001052 if (co == NULL)
1053 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001054 v = PyEval_EvalCode(co, globals, locals);
1055 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056 return v;
1057}
1058
Guido van Rossum82598051997-03-05 00:20:32 +00001059static PyObject *
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001060run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals,
1061 PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001062{
Guido van Rossum82598051997-03-05 00:20:32 +00001063 PyCodeObject *co;
1064 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001065 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001066 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001067
Guido van Rossum82598051997-03-05 00:20:32 +00001068 magic = PyMarshal_ReadLongFromFile(fp);
1069 if (magic != PyImport_GetMagicNumber()) {
1070 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001071 "Bad magic number in .pyc file");
1072 return NULL;
1073 }
Guido van Rossum82598051997-03-05 00:20:32 +00001074 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001075 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001076 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001077 if (v == NULL || !PyCode_Check(v)) {
1078 Py_XDECREF(v);
1079 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001080 "Bad code object in .pyc file");
1081 return NULL;
1082 }
Guido van Rossum82598051997-03-05 00:20:32 +00001083 co = (PyCodeObject *)v;
1084 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001085 if (v && flags) {
1086 if (co->co_flags & CO_NESTED)
Tim Peters5ba58662001-07-16 02:29:45 +00001087 flags->cf_flags |= PyCF_NESTED_SCOPES;
Tim Peters51d76f12001-07-16 03:11:48 +00001088 if (co->co_flags & CO_GENERATOR_ALLOWED)
Tim Peters5ba58662001-07-16 02:29:45 +00001089 flags->cf_flags |= PyCF_GENERATORS;
Marc-André Lemburg464fe3a2001-06-13 17:18:06 +00001090#if 0
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001091 fprintf(stderr, "run_pyc_file: nested_scopes: %d\n",
Tim Peters5ba58662001-07-16 02:29:45 +00001092 flags->cf_flags & PyCF_NESTED_SCOPES);
1093 fprintf(stderr, "run_pyc_file: generators: %d\n",
1094 flags->cf_flags & PyCF_GENERATORS);
Marc-André Lemburg464fe3a2001-06-13 17:18:06 +00001095#endif
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001096 }
Guido van Rossum82598051997-03-05 00:20:32 +00001097 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001098 return v;
1099}
1100
Guido van Rossum82598051997-03-05 00:20:32 +00001101PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001102Py_CompileString(char *str, char *filename, int start)
Guido van Rossum5b722181993-03-30 17:46:03 +00001103{
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001104 return Py_CompileStringFlags(str, filename, start, NULL);
1105}
1106
1107PyObject *
1108Py_CompileStringFlags(char *str, char *filename, int start,
1109 PyCompilerFlags *flags)
1110{
Guido van Rossum5b722181993-03-30 17:46:03 +00001111 node *n;
Guido van Rossum82598051997-03-05 00:20:32 +00001112 PyCodeObject *co;
Tim Petersfe2127d2001-07-16 05:37:24 +00001113 n = PyParser_SimpleParseStringFlags(str, start,
1114 (flags && flags->cf_flags & PyCF_GENERATORS) ?
1115 PyPARSE_YIELD_IS_KEYWORD : 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001116 if (n == NULL)
Guido van Rossum5b722181993-03-30 17:46:03 +00001117 return NULL;
Jeremy Hylton673a4fd2001-03-26 19:53:38 +00001118 co = PyNode_CompileFlags(n, filename, flags);
Guido van Rossum82598051997-03-05 00:20:32 +00001119 PyNode_Free(n);
1120 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001121}
1122
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001123struct symtable *
1124Py_SymtableString(char *str, char *filename, int start)
1125{
1126 node *n;
1127 struct symtable *st;
1128 n = PyParser_SimpleParseString(str, start);
1129 if (n == NULL)
1130 return NULL;
1131 st = PyNode_CompileSymtable(n, filename);
1132 PyNode_Free(n);
1133 return st;
1134}
1135
Guido van Rossuma110aa61994-08-29 12:50:44 +00001136/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001137
Guido van Rossuma110aa61994-08-29 12:50:44 +00001138node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001139PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001140{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001141 node *n;
1142 perrdetail err;
Tim Petersfe2127d2001-07-16 05:37:24 +00001143 n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, start,
1144 (char *)0, (char *)0, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001145 if (n == NULL)
1146 err_input(&err);
1147 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001148}
1149
Tim Petersfe2127d2001-07-16 05:37:24 +00001150node *
1151PyParser_SimpleParseFile(FILE *fp, char *filename, int start)
1152{
1153 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
1154}
1155
Guido van Rossuma110aa61994-08-29 12:50:44 +00001156/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001157
Guido van Rossuma110aa61994-08-29 12:50:44 +00001158node *
Tim Petersfe2127d2001-07-16 05:37:24 +00001159PyParser_SimpleParseStringFlags(char *str, int start, int flags)
1160{
1161 node *n;
1162 perrdetail err;
1163 n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err,
1164 flags);
1165 if (n == NULL)
1166 err_input(&err);
1167 return n;
1168}
1169
1170node *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001171PyParser_SimpleParseString(char *str, int start)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001172{
Tim Petersfe2127d2001-07-16 05:37:24 +00001173 return PyParser_SimpleParseStringFlags(str, start, 0);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001174}
1175
1176/* Set the error appropriate to the given input error code (see errcode.h) */
1177
1178static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001179err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001180{
Fred Drake85f36392000-07-11 17:53:00 +00001181 PyObject *v, *w, *errtype;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001182 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001183 errtype = PyExc_SyntaxError;
Guido van Rossum82598051997-03-05 00:20:32 +00001184 v = Py_BuildValue("(ziiz)", err->filename,
Guido van Rossuma110aa61994-08-29 12:50:44 +00001185 err->lineno, err->offset, err->text);
1186 if (err->text != NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001187 PyMem_DEL(err->text);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001188 err->text = NULL;
1189 }
1190 switch (err->error) {
1191 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001192 errtype = PyExc_IndentationError;
1193 if (err->expected == INDENT)
1194 msg = "expected an indented block";
1195 else if (err->token == INDENT)
1196 msg = "unexpected indent";
1197 else if (err->token == DEDENT)
1198 msg = "unexpected unindent";
1199 else {
1200 errtype = PyExc_SyntaxError;
1201 msg = "invalid syntax";
1202 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001203 break;
1204 case E_TOKEN:
1205 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001206 break;
1207 case E_INTR:
Guido van Rossum82598051997-03-05 00:20:32 +00001208 PyErr_SetNone(PyExc_KeyboardInterrupt);
Barry Warsawc80baa31999-01-27 16:39:40 +00001209 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001210 return;
1211 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001212 PyErr_NoMemory();
Barry Warsawc80baa31999-01-27 16:39:40 +00001213 Py_XDECREF(v);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001214 return;
1215 case E_EOF:
1216 msg = "unexpected EOF while parsing";
1217 break;
Fred Drake85f36392000-07-11 17:53:00 +00001218 case E_TABSPACE:
1219 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001220 msg = "inconsistent use of tabs and spaces in indentation";
1221 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001222 case E_OVERFLOW:
1223 msg = "expression too long";
1224 break;
Fred Drake85f36392000-07-11 17:53:00 +00001225 case E_DEDENT:
1226 errtype = PyExc_IndentationError;
1227 msg = "unindent does not match any outer indentation level";
1228 break;
1229 case E_TOODEEP:
1230 errtype = PyExc_IndentationError;
1231 msg = "too many levels of indentation";
1232 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001233 default:
1234 fprintf(stderr, "error=%d\n", err->error);
1235 msg = "unknown parsing error";
1236 break;
1237 }
Guido van Rossum82598051997-03-05 00:20:32 +00001238 w = Py_BuildValue("(sO)", msg, v);
Guido van Rossum41318302001-03-23 04:01:07 +00001239 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001240 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001241 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001242}
1243
1244/* Print fatal error message and abort */
1245
1246void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001247Py_FatalError(char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001248{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001249 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossum8ae87c01995-01-26 00:40:38 +00001250#ifdef macintosh
1251 for (;;);
1252#endif
Guido van Rossum9b38a141996-09-11 23:12:24 +00001253#ifdef MS_WIN32
Guido van Rossum23c94461997-05-22 20:21:30 +00001254 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001255 OutputDebugString(msg);
1256 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001257#ifdef _DEBUG
1258 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001259#endif
Guido van Rossum0ba35361998-08-13 13:33:16 +00001260#endif /* MS_WIN32 */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001261 abort();
1262}
1263
1264/* Clean up and exit */
1265
Guido van Rossuma110aa61994-08-29 12:50:44 +00001266#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001267#include "pythread.h"
Guido van Rossum82598051997-03-05 00:20:32 +00001268int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001269#endif
1270
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001271#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001272static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001273static int nexitfuncs = 0;
1274
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001275int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001276{
1277 if (nexitfuncs >= NEXITFUNCS)
1278 return -1;
1279 exitfuncs[nexitfuncs++] = func;
1280 return 0;
1281}
1282
Guido van Rossumcc283f51997-08-05 02:22:03 +00001283static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001284call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001285{
Guido van Rossum82598051997-03-05 00:20:32 +00001286 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001287
1288 if (exitfunc) {
Fred Drake6a12d8d2001-03-23 17:34:02 +00001289 PyObject *res;
Guido van Rossum82598051997-03-05 00:20:32 +00001290 Py_INCREF(exitfunc);
1291 PySys_SetObject("exitfunc", (PyObject *)NULL);
1292 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
Guido van Rossum59bff391992-09-03 20:28:00 +00001293 if (res == NULL) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001294 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1295 PySys_WriteStderr("Error in sys.exitfunc:\n");
1296 }
Guido van Rossum82598051997-03-05 00:20:32 +00001297 PyErr_Print();
Guido van Rossum59bff391992-09-03 20:28:00 +00001298 }
Guido van Rossum82598051997-03-05 00:20:32 +00001299 Py_DECREF(exitfunc);
Guido van Rossum59bff391992-09-03 20:28:00 +00001300 }
1301
Guido van Rossum0829c751998-02-28 04:31:39 +00001302 if (Py_FlushLine())
1303 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001304}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001305
Guido van Rossumcc283f51997-08-05 02:22:03 +00001306static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001307call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001308{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001309 while (nexitfuncs > 0)
1310 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001311
1312 fflush(stdout);
1313 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001314}
1315
1316void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001317Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001318{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001319 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001320
Jack Jansen66a89771995-10-27 13:22:14 +00001321#ifdef macintosh
1322 PyMac_Exit(sts);
1323#else
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001324 exit(sts);
Jack Jansen66a89771995-10-27 13:22:14 +00001325#endif
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001326}
1327
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001328static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001329initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001330{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001331#ifdef HAVE_SIGNAL_H
1332#ifdef SIGPIPE
1333 signal(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001334#endif
Guido van Rossuma110aa61994-08-29 12:50:44 +00001335#endif /* HAVE_SIGNAL_H */
Guido van Rossum82598051997-03-05 00:20:32 +00001336 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001337}
1338
Guido van Rossumaae0d321996-05-22 16:35:33 +00001339#ifdef Py_TRACE_REFS
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340/* Ask a yes/no question */
1341
Guido van Rossum59bff391992-09-03 20:28:00 +00001342int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001343_Py_AskYesNo(char *prompt)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001344{
1345 char buf[256];
1346
1347 printf("%s [ny] ", prompt);
1348 if (fgets(buf, sizeof buf, stdin) == NULL)
1349 return 0;
1350 return buf[0] == 'y' || buf[0] == 'Y';
1351}
1352#endif
1353
Guido van Rossuma110aa61994-08-29 12:50:44 +00001354#ifdef MPW
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001355
1356/* Check for file descriptor connected to interactive device.
1357 Pretend that stdin is always interactive, other files never. */
1358
1359int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001360isatty(int fd)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001361{
1362 return fd == fileno(stdin);
1363}
1364
1365#endif
Guido van Rossum7433b121997-02-14 19:45:36 +00001366
1367/*
1368 * The file descriptor fd is considered ``interactive'' if either
1369 * a) isatty(fd) is TRUE, or
1370 * b) the -i flag was given, and the filename associated with
1371 * the descriptor is NULL or "<stdin>" or "???".
1372 */
1373int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001374Py_FdIsInteractive(FILE *fp, char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001375{
1376 if (isatty((int)fileno(fp)))
1377 return 1;
1378 if (!Py_InteractiveFlag)
1379 return 0;
1380 return (filename == NULL) ||
1381 (strcmp(filename, "<stdin>") == 0) ||
1382 (strcmp(filename, "???") == 0);
1383}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001384
1385
1386#if defined(USE_STACKCHECK)
1387#if defined(WIN32) && defined(_MSC_VER)
1388
1389/* Stack checking for Microsoft C */
1390
1391#include <malloc.h>
1392#include <excpt.h>
1393
Fred Drakee8de31c2000-08-31 05:38:39 +00001394/*
1395 * Return non-zero when we run out of memory on the stack; zero otherwise.
1396 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001397int
Fred Drake399739f2000-08-31 05:52:44 +00001398PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001399{
1400 __try {
1401 /* _alloca throws a stack overflow exception if there's
1402 not enough space left on the stack */
1403 _alloca(PYOS_STACK_MARGIN * sizeof(void*));
1404 return 0;
1405 } __except (EXCEPTION_EXECUTE_HANDLER) {
1406 /* just ignore all errors */
1407 }
1408 return 1;
1409}
1410
1411#endif /* WIN32 && _MSC_VER */
1412
1413/* Alternate implementations can be added here... */
1414
1415#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001416
1417
1418/* Wrappers around sigaction() or signal(). */
1419
1420PyOS_sighandler_t
1421PyOS_getsig(int sig)
1422{
1423#ifdef HAVE_SIGACTION
1424 struct sigaction context;
1425 sigaction(sig, NULL, &context);
1426 return context.sa_handler;
1427#else
1428 PyOS_sighandler_t handler;
1429 handler = signal(sig, SIG_IGN);
1430 signal(sig, handler);
1431 return handler;
1432#endif
1433}
1434
1435PyOS_sighandler_t
1436PyOS_setsig(int sig, PyOS_sighandler_t handler)
1437{
1438#ifdef HAVE_SIGACTION
1439 struct sigaction context;
1440 PyOS_sighandler_t oldhandler;
1441 sigaction(sig, NULL, &context);
1442 oldhandler = context.sa_handler;
1443 context.sa_handler = handler;
1444 sigaction(sig, &context, NULL);
1445 return oldhandler;
1446#else
1447 return signal(sig, handler);
1448#endif
1449}