blob: 0ce61a55580d02202f3276d23fadefe4f2be3642 [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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000095
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020096PyThreadState *_Py_Finalizing = NULL;
97
Christian Heimes33fe8092008-04-13 13:53:33 +000098/* PyModule_GetWarningsModule is no longer necessary as of 2.6
99since _warnings is builtin. This API should not be used. */
100PyObject *
101PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000104}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000105
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000107
Thomas Wouters7e474022000-07-16 12:04:32 +0000108/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109
110int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000111Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114}
115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116/* Global initializations. Can be undone by Py_Finalize(). Don't
117 call this twice without an intervening Py_Finalize() call. When
118 initializations fail, a fatal error is issued and the function does
119 not return. On return, the first thread and interpreter state have
120 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Locking: you must hold the interpreter lock while calling this.
123 (If the lock has not yet been initialized, that's equivalent to
124 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000125
Guido van Rossum25ce5661997-08-02 03:10:38 +0000126*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000128static int
129add_flag(int flag, const char *envs)
130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int env = atoi(envs);
132 if (flag < env)
133 flag = env;
134 if (flag < 1)
135 flag = 1;
136 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000137}
138
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000140get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141{
Victor Stinner94908bb2010-08-18 21:23:25 +0000142 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000143 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200144 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000145
Victor Stinner94908bb2010-08-18 21:23:25 +0000146 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (!codec)
148 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000149
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200150 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 Py_CLEAR(codec);
152 if (!name)
153 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000154
Victor Stinner94908bb2010-08-18 21:23:25 +0000155 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100156 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000157 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000158 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000160 if (name_str == NULL) {
161 PyErr_NoMemory();
162 return NULL;
163 }
164 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000165
166error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000168 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000170}
Victor Stinner94908bb2010-08-18 21:23:25 +0000171
Victor Stinner94908bb2010-08-18 21:23:25 +0000172static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200173get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000174{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200175#ifdef MS_WINDOWS
176 char codepage[100];
177 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
178 return get_codec_name(codepage);
179#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000180 char* codeset = nl_langinfo(CODESET);
181 if (!codeset || codeset[0] == '\0') {
182 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
183 return NULL;
184 }
185 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200186#else
187 PyErr_SetNone(PyExc_NotImplementedError);
188 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000189#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200190}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000191
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000193Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyInterpreterState *interp;
196 PyThreadState *tstate;
197 PyObject *bimod, *sysmod, *pstderr;
198 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (initialized)
202 return;
203 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200204 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000205
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000206#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* Set up the LC_CTYPE locale, so we can obtain
208 the locale's charset without having to switch
209 locales. */
210 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000211#endif
212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
214 Py_DebugFlag = add_flag(Py_DebugFlag, p);
215 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
216 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
217 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
218 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
219 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
220 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 interp = PyInterpreterState_New();
223 if (interp == NULL)
224 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 tstate = PyThreadState_New(interp);
227 if (tstate == NULL)
228 Py_FatalError("Py_Initialize: can't make first thread");
229 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000230
Victor Stinner6961bd62010-08-17 22:26:51 +0000231#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000232 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
233 destroying the GIL might fail when it is being referenced from
234 another running thread (see issue #9901).
235 Instead we destroy the previously created GIL here, which ensures
236 that we can call Py_Initialize / Py_Finalize multiple times. */
237 _PyEval_FiniThreads();
238
239 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000240 _PyGILState_Init(interp, tstate);
241#endif /* WITH_THREAD */
242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (!_PyFrame_Init())
246 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (!_PyLong_Init())
249 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (!PyByteArray_Init())
252 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 interp->modules = PyDict_New();
257 if (interp->modules == NULL)
258 Py_FatalError("Py_Initialize: can't make modules dictionary");
259 interp->modules_reloading = PyDict_New();
260 if (interp->modules_reloading == NULL)
261 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* Init Unicode implementation; relies on the codec registry */
264 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 bimod = _PyBuiltin_Init();
267 if (bimod == NULL)
268 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000269 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 interp->builtins = PyModule_GetDict(bimod);
271 if (interp->builtins == NULL)
272 Py_FatalError("Py_Initialize: can't initialize builtins dict");
273 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* initialize builtin exceptions */
276 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 sysmod = _PySys_Init();
279 if (sysmod == NULL)
280 Py_FatalError("Py_Initialize: can't initialize sys");
281 interp->sysdict = PyModule_GetDict(sysmod);
282 if (interp->sysdict == NULL)
283 Py_FatalError("Py_Initialize: can't initialize sys dict");
284 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000285 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 PySys_SetPath(Py_GetPath());
287 PyDict_SetItemString(interp->sysdict, "modules",
288 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* Set up a preliminary stderr printer until we have enough
291 infrastructure for the io module in place. */
292 pstderr = PyFile_NewStdPrinter(fileno(stderr));
293 if (pstderr == NULL)
294 Py_FatalError("Py_Initialize: can't set preliminary stderr");
295 PySys_SetObject("stderr", pstderr);
296 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000297 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000302
Victor Stinner024e37a2011-03-31 01:31:06 +0200303 /* initialize the faulthandler module */
304 if (_PyFaulthandler_Init())
305 Py_FatalError("Py_Initialize: can't initialize faulthandler");
306
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000307 /* Initialize _warnings. */
308 _PyWarnings_Init();
309
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000310 _PyTime_Init();
311
Victor Stinner793b5312011-04-27 00:24:21 +0200312 if (initfsencoding(interp) < 0)
313 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (install_sigs)
316 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 initmain(); /* Module __main__ */
319 if (initstdio() < 0)
320 Py_FatalError(
321 "Py_Initialize: can't initialize sys standard streams");
322
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000323 /* Initialize warnings. */
324 if (PySys_HasWarnOptions()) {
325 PyObject *warnings_module = PyImport_ImportModule("warnings");
326 if (warnings_module == NULL) {
327 fprintf(stderr, "'import warnings' failed; traceback:\n");
328 PyErr_Print();
329 }
330 Py_XDECREF(warnings_module);
331 }
332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (!Py_NoSiteFlag)
334 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000335}
336
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000337void
338Py_Initialize(void)
339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000341}
342
343
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000344#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000345extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000346#endif
347
Guido van Rossume8432ac2007-07-09 15:04:50 +0000348/* Flush stdout and stderr */
349
Neal Norwitz2bad9702007-08-27 06:19:22 +0000350static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000351flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject *fout = PySys_GetObject("stdout");
354 PyObject *ferr = PySys_GetObject("stderr");
355 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200356 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (fout != NULL && fout != Py_None) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200359 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000361 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else
363 Py_DECREF(tmp);
364 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000365
Victor Stinner9467b212010-05-14 00:59:09 +0000366 if (ferr != NULL && ferr != Py_None) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200367 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (tmp == NULL)
369 PyErr_Clear();
370 else
371 Py_DECREF(tmp);
372 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000373}
374
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375/* Undo the effect of Py_Initialize().
376
377 Beware: if multiple interpreter and/or thread states exist, these
378 are not wiped out; only the current thread and interpreter state
379 are deleted. But since everything else is deleted, those other
380 interpreter and thread states should no longer be used.
381
382 (XXX We should do better, e.g. wipe out all interpreters and
383 threads.)
384
385 Locking: as above.
386
387*/
388
389void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000390Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyInterpreterState *interp;
393 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (!initialized)
396 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* The interpreter is still entirely intact at this point, and the
401 * exit funcs may be relying on that. In particular, if some thread
402 * or exit func is still waiting to do an import, the import machinery
403 * expects Py_IsInitialized() to return true. So don't say the
404 * interpreter is uninitialized until after the exit funcs have run.
405 * Note that Threading.py uses an exit func to do a join on all the
406 * threads created thru it, so this also protects pending imports in
407 * the threads created via Threading.
408 */
409 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* Get current thread state and interpreter pointer */
412 tstate = PyThreadState_GET();
413 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000414
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200415 /* Remaining threads (e.g. daemon threads) will automatically exit
416 after taking the GIL (in PyEval_RestoreThread()). */
417 _Py_Finalizing = tstate;
418 initialized = 0;
419
420 /* Flush stdout+stderr */
421 flush_std_files();
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* Disable signal handling */
424 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* Clear type lookup cache */
427 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Collect garbage. This may call finalizers; it's nice to call these
430 * before all modules are destroyed.
431 * XXX If a __del__ or weakref callback is triggered here, and tries to
432 * XXX import a module, bad things can happen, because Python no
433 * XXX longer believes it's initialized.
434 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
435 * XXX is easy to provoke that way. I've also seen, e.g.,
436 * XXX Exception exceptions.ImportError: 'No module named sha'
437 * XXX in <function callback at 0x008F5718> ignored
438 * XXX but I'm unclear on exactly how that one happens. In any case,
439 * XXX I haven't seen a real-life report of either of these.
440 */
441 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000442#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* With COUNT_ALLOCS, it helps to run GC multiple times:
444 each collection might release some types from the type
445 list, so they become garbage. */
446 while (PyGC_Collect() > 0)
447 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000448#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000449 /* We run this while most interpreter state is still alive, so that
450 debug information can be printed out */
451 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Destroy all modules */
454 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Flush stdout+stderr (again, in case more was printed) */
457 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 /* Collect final garbage. This disposes of cycles created by
460 * new-style class definitions, for example.
461 * XXX This is disabled because it caused too many problems. If
462 * XXX a __del__ or weakref callback triggers here, Python code has
463 * XXX a hard time running, because even the sys module has been
464 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
465 * XXX One symptom is a sequence of information-free messages
466 * XXX coming from threads (if a __del__ or callback is invoked,
467 * XXX other threads can execute too, and any exception they encounter
468 * XXX triggers a comedy of errors as subsystem after subsystem
469 * XXX fails to find what it *expects* to find in sys to help report
470 * XXX the exception and consequent unexpected failures). I've also
471 * XXX seen segfaults then, after adding print statements to the
472 * XXX Python code getting called.
473 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000474#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000476#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
479 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000480
Victor Stinner024e37a2011-03-31 01:31:06 +0200481 /* unload faulthandler module */
482 _PyFaulthandler_Fini();
483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000485#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000487#endif
488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000490
Tim Peters9cf25ce2003-04-17 15:21:01 +0000491#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* Display all objects still alive -- this can invoke arbitrary
493 * __repr__ overrides, so requires a mostly-intact interpreter.
494 * Alas, a lot of stuff may still be alive now that will be cleaned
495 * up later.
496 */
497 if (Py_GETENV("PYTHONDUMPREFS"))
498 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000499#endif /* Py_TRACE_REFS */
500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Clear interpreter state */
502 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Now we decref the exception classes. After this point nothing
505 can raise an exception. That's okay, because each Fini() method
506 below has been checked to make sure no exceptions are ever
507 raised.
508 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000513#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000515#endif /* WITH_THREAD */
516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Delete current thread */
518 PyThreadState_Swap(NULL);
519 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* Sundry finalizers */
522 PyMethod_Fini();
523 PyFrame_Fini();
524 PyCFunction_Fini();
525 PyTuple_Fini();
526 PyList_Fini();
527 PySet_Fini();
528 PyBytes_Fini();
529 PyByteArray_Fini();
530 PyLong_Fini();
531 PyFloat_Fini();
532 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* Cleanup Unicode implementation */
535 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000538 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 free((char*)Py_FileSystemDefaultEncoding);
540 Py_FileSystemDefaultEncoding = NULL;
541 }
Christian Heimesc8967002007-11-30 10:18:26 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 /* XXX Still allocated:
544 - various static ad-hoc pointers to interned strings
545 - int and float free list blocks
546 - whatever various modules and libraries allocate
547 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000550
Tim Peters269b2a62003-04-17 19:52:29 +0000551#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* Display addresses (& refcnts) of all objects still alive.
553 * An address can be used to find the repr of the object, printed
554 * above by _Py_PrintReferences.
555 */
556 if (Py_GETENV("PYTHONDUMPREFS"))
557 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000558#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000559#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (Py_GETENV("PYTHONMALLOCSTATS"))
561 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000562#endif
563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565}
566
567/* Create and initialize a new interpreter and thread, and return the
568 new thread. This requires that Py_Initialize() has been called
569 first.
570
571 Unsuccessful initialization yields a NULL pointer. Note that *no*
572 exception information is available even in this case -- the
573 exception information is held in the thread, and there is no
574 thread.
575
576 Locking: as above.
577
578*/
579
580PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000581Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyInterpreterState *interp;
584 PyThreadState *tstate, *save_tstate;
585 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 if (!initialized)
588 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 interp = PyInterpreterState_New();
591 if (interp == NULL)
592 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 tstate = PyThreadState_New(interp);
595 if (tstate == NULL) {
596 PyInterpreterState_Delete(interp);
597 return NULL;
598 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 interp->modules = PyDict_New();
605 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606
Victor Stinner49d3f252010-10-17 01:24:53 +0000607 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (bimod != NULL) {
609 interp->builtins = PyModule_GetDict(bimod);
610 if (interp->builtins == NULL)
611 goto handle_error;
612 Py_INCREF(interp->builtins);
613 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* initialize builtin exceptions */
616 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000617
Victor Stinner49d3f252010-10-17 01:24:53 +0000618 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (bimod != NULL && sysmod != NULL) {
620 PyObject *pstderr;
621 interp->sysdict = PyModule_GetDict(sysmod);
622 if (interp->sysdict == NULL)
623 goto handle_error;
624 Py_INCREF(interp->sysdict);
625 PySys_SetPath(Py_GetPath());
626 PyDict_SetItemString(interp->sysdict, "modules",
627 interp->modules);
628 /* Set up a preliminary stderr printer until we have enough
629 infrastructure for the io module in place. */
630 pstderr = PyFile_NewStdPrinter(fileno(stderr));
631 if (pstderr == NULL)
632 Py_FatalError("Py_Initialize: can't set preliminary stderr");
633 PySys_SetObject("stderr", pstderr);
634 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000635 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200638
639 if (initfsencoding(interp) < 0)
640 goto handle_error;
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (initstdio() < 0)
643 Py_FatalError(
644 "Py_Initialize: can't initialize sys standard streams");
645 initmain();
646 if (!Py_NoSiteFlag)
647 initsite();
648 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (!PyErr_Occurred())
651 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000652
Thomas Wouters89f507f2006-12-13 04:49:30 +0000653handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655
Victor Stinnerc40a3502011-04-27 00:20:27 +0200656 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyThreadState_Clear(tstate);
658 PyThreadState_Swap(save_tstate);
659 PyThreadState_Delete(tstate);
660 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000663}
664
665/* Delete an interpreter and its last thread. This requires that the
666 given thread state is current, that the thread has no remaining
667 frames, and that it is its interpreter's only remaining thread.
668 It is a fatal error to violate these constraints.
669
670 (Py_Finalize() doesn't have these constraints -- it zaps
671 everything, regardless.)
672
673 Locking: as above.
674
675*/
676
677void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000678Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (tstate != PyThreadState_GET())
683 Py_FatalError("Py_EndInterpreter: thread is not current");
684 if (tstate->frame != NULL)
685 Py_FatalError("Py_EndInterpreter: thread still has a frame");
686 if (tstate != interp->tstate_head || tstate->next != NULL)
687 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyImport_Cleanup();
690 PyInterpreterState_Clear(interp);
691 PyThreadState_Swap(NULL);
692 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000693}
694
Martin v. Löwis790465f2008-04-05 20:41:37 +0000695static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000696
697void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (pn && *pn)
701 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000702}
703
Martin v. Löwis790465f2008-04-05 20:41:37 +0000704wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000705Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000708}
709
Martin v. Löwis790465f2008-04-05 20:41:37 +0000710static wchar_t *default_home = NULL;
711static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000712
713void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000714Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000717}
718
Martin v. Löwis790465f2008-04-05 20:41:37 +0000719wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000720Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 wchar_t *home = default_home;
723 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
724 char* chome = Py_GETENV("PYTHONHOME");
725 if (chome) {
726 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
727 if (r != (size_t)-1 && r <= PATH_MAX)
728 home = env_home;
729 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 }
732 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000733}
734
Guido van Rossum6135a871995-01-09 17:53:26 +0000735/* Create __main__ module */
736
737static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000738initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyObject *m, *d;
741 m = PyImport_AddModule("__main__");
742 if (m == NULL)
743 Py_FatalError("can't create __main__ module");
744 d = PyModule_GetDict(m);
745 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
746 PyObject *bimod = PyImport_ImportModule("builtins");
747 if (bimod == NULL ||
748 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
749 Py_FatalError("can't add __builtins__ to __main__");
750 Py_DECREF(bimod);
751 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000752}
753
Victor Stinner793b5312011-04-27 00:24:21 +0200754static int
755initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000756{
757 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000758
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200759 if (Py_FileSystemDefaultEncoding == NULL)
760 {
761 Py_FileSystemDefaultEncoding = get_locale_encoding();
762 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000763 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000764
Victor Stinnere4743092010-10-19 00:05:51 +0000765 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200766 interp->fscodec_initialized = 1;
767 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000768 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000769
770 /* the encoding is mbcs, utf-8 or ascii */
771 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
772 if (!codec) {
773 /* Such error can only occurs in critical situations: no more
774 * memory, import a module of the standard library failed,
775 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200776 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000777 }
Victor Stinner793b5312011-04-27 00:24:21 +0200778 Py_DECREF(codec);
779 interp->fscodec_initialized = 1;
780 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000781}
782
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000783/* Import the site module (not into __main__ though) */
784
785static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000786initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyObject *m;
789 m = PyImport_ImportModule("site");
790 if (m == NULL) {
791 PyErr_Print();
792 Py_Finalize();
793 exit(1);
794 }
795 else {
796 Py_DECREF(m);
797 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000798}
799
Antoine Pitrou05608432009-01-09 18:53:14 +0000800static PyObject*
801create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 int fd, int write_mode, char* name,
803 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
806 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000807 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyObject *line_buffering;
809 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200810 _Py_IDENTIFIER(open);
811 _Py_IDENTIFIER(isatty);
812 _Py_IDENTIFIER(TextIOWrapper);
Antoine Pitrou05608432009-01-09 18:53:14 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 /* stdin is always opened in buffered mode, first because it shouldn't
815 make a difference in common use cases, second because TextIOWrapper
816 depends on the presence of a read1() method which only exists on
817 buffered streams.
818 */
819 if (Py_UnbufferedStdioFlag && write_mode)
820 buffering = 0;
821 else
822 buffering = -1;
823 if (write_mode)
824 mode = "wb";
825 else
826 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200827 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
828 fd, mode, buffering,
829 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (buf == NULL)
831 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200834 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200835 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (raw == NULL)
837 goto error;
838 }
839 else {
840 raw = buf;
841 Py_INCREF(raw);
842 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 text = PyUnicode_FromString(name);
845 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
846 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200847 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (res == NULL)
849 goto error;
850 isatty = PyObject_IsTrue(res);
851 Py_DECREF(res);
852 if (isatty == -1)
853 goto error;
854 if (isatty || Py_UnbufferedStdioFlag)
855 line_buffering = Py_True;
856 else
857 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_CLEAR(raw);
860 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000861
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000862 newline = "\n";
863#ifdef MS_WINDOWS
864 if (!write_mode) {
865 /* translate \r\n to \n for sys.stdin on Windows */
866 newline = NULL;
867 }
868#endif
869
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200870 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
871 buf, encoding, errors,
872 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 Py_CLEAR(buf);
874 if (stream == NULL)
875 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (write_mode)
878 mode = "w";
879 else
880 mode = "r";
881 text = PyUnicode_FromString(mode);
882 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
883 goto error;
884 Py_CLEAR(text);
885 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000886
887error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 Py_XDECREF(buf);
889 Py_XDECREF(stream);
890 Py_XDECREF(text);
891 Py_XDECREF(raw);
892 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000893}
894
Georg Brandl1a3284e2007-12-02 09:40:06 +0000895/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000896static int
897initstdio(void)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyObject *iomod = NULL, *wrapper;
900 PyObject *bimod = NULL;
901 PyObject *m;
902 PyObject *std = NULL;
903 int status = 0, fd;
904 PyObject * encoding_attr;
905 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Hack to avoid a nasty recursion issue when Python is invoked
908 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
909 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
910 goto error;
911 }
912 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
915 goto error;
916 }
917 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (!(bimod = PyImport_ImportModule("builtins"))) {
920 goto error;
921 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (!(iomod = PyImport_ImportModule("io"))) {
924 goto error;
925 }
926 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
927 goto error;
928 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 /* Set builtins.open */
931 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000932 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 goto error;
934 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000935 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 encoding = Py_GETENV("PYTHONIOENCODING");
938 errors = NULL;
939 if (encoding) {
940 encoding = strdup(encoding);
941 errors = strchr(encoding, ':');
942 if (errors) {
943 *errors = '\0';
944 errors++;
945 }
946 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Set sys.stdin */
949 fd = fileno(stdin);
950 /* Under some conditions stdin, stdout and stderr may not be connected
951 * and fileno() may point to an invalid file descriptor. For example
952 * GUI apps don't have valid standard streams by default.
953 */
954 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000955#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 std = Py_None;
957 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000958#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000960#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
962 else {
963 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
964 if (std == NULL)
965 goto error;
966 } /* if (fd < 0) */
967 PySys_SetObject("__stdin__", std);
968 PySys_SetObject("stdin", std);
969 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Set sys.stdout */
972 fd = fileno(stdout);
973 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000974#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 std = Py_None;
976 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000977#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000979#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 }
981 else {
982 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
983 if (std == NULL)
984 goto error;
985 } /* if (fd < 0) */
986 PySys_SetObject("__stdout__", std);
987 PySys_SetObject("stdout", std);
988 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000989
Guido van Rossum98297ee2007-11-06 21:34:58 +0000990#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* Set sys.stderr, replaces the preliminary stderr */
992 fd = fileno(stderr);
993 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000994#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 std = Py_None;
996 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000997#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000999#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 }
1001 else {
1002 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1003 if (std == NULL)
1004 goto error;
1005 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* Same as hack above, pre-import stderr's codec to avoid recursion
1008 when import.c tries to write to stderr in verbose mode. */
1009 encoding_attr = PyObject_GetAttrString(std, "encoding");
1010 if (encoding_attr != NULL) {
1011 const char * encoding;
1012 encoding = _PyUnicode_AsString(encoding_attr);
1013 if (encoding != NULL) {
1014 _PyCodec_Lookup(encoding);
1015 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001016 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 }
1018 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PySys_SetObject("__stderr__", std);
1021 PySys_SetObject("stderr", std);
1022 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001023#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001026 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 status = -1;
1028 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (encoding)
1031 free(encoding);
1032 Py_XDECREF(bimod);
1033 Py_XDECREF(iomod);
1034 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001035}
1036
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001037/* Parse input from a file and execute it */
1038
1039int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001040PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (filename == NULL)
1044 filename = "???";
1045 if (Py_FdIsInteractive(fp, filename)) {
1046 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1047 if (closeit)
1048 fclose(fp);
1049 return err;
1050 }
1051 else
1052 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001053}
1054
1055int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001056PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyObject *v;
1059 int ret;
1060 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 if (flags == NULL) {
1063 flags = &local_flags;
1064 local_flags.cf_flags = 0;
1065 }
1066 v = PySys_GetObject("ps1");
1067 if (v == NULL) {
1068 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1069 Py_XDECREF(v);
1070 }
1071 v = PySys_GetObject("ps2");
1072 if (v == NULL) {
1073 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1074 Py_XDECREF(v);
1075 }
1076 for (;;) {
1077 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1078 PRINT_TOTAL_REFS();
1079 if (ret == E_EOF)
1080 return 0;
1081 /*
1082 if (ret == E_NOMEM)
1083 return -1;
1084 */
1085 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086}
1087
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001088/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001089static int PARSER_FLAGS(PyCompilerFlags *flags)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 int parser_flags = 0;
1092 if (!flags)
1093 return 0;
1094 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1095 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1096 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1097 parser_flags |= PyPARSE_IGNORE_COOKIE;
1098 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1099 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1100 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001101}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001102
Thomas Wouters89f507f2006-12-13 04:49:30 +00001103#if 0
1104/* Keep an example of flags with future keyword support. */
1105#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1107 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1108 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1109 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001110#endif
1111
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001112int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001113PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *m, *d, *v, *w, *oenc = NULL;
1116 mod_ty mod;
1117 PyArena *arena;
1118 char *ps1 = "", *ps2 = "", *enc = NULL;
1119 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001120 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (fp == stdin) {
1123 /* Fetch encoding from sys.stdin */
1124 v = PySys_GetObject("stdin");
1125 if (v == NULL || v == Py_None)
1126 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001127 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (!oenc)
1129 return -1;
1130 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001131 if (enc == NULL)
1132 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
1134 v = PySys_GetObject("ps1");
1135 if (v != NULL) {
1136 v = PyObject_Str(v);
1137 if (v == NULL)
1138 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001139 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001141 if (ps1 == NULL) {
1142 PyErr_Clear();
1143 ps1 = "";
1144 }
1145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 }
1147 w = PySys_GetObject("ps2");
1148 if (w != NULL) {
1149 w = PyObject_Str(w);
1150 if (w == NULL)
1151 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001152 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001154 if (ps2 == NULL) {
1155 PyErr_Clear();
1156 ps2 = "";
1157 }
1158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
1160 arena = PyArena_New();
1161 if (arena == NULL) {
1162 Py_XDECREF(v);
1163 Py_XDECREF(w);
1164 Py_XDECREF(oenc);
1165 return -1;
1166 }
1167 mod = PyParser_ASTFromFile(fp, filename, enc,
1168 Py_single_input, ps1, ps2,
1169 flags, &errcode, arena);
1170 Py_XDECREF(v);
1171 Py_XDECREF(w);
1172 Py_XDECREF(oenc);
1173 if (mod == NULL) {
1174 PyArena_Free(arena);
1175 if (errcode == E_EOF) {
1176 PyErr_Clear();
1177 return E_EOF;
1178 }
1179 PyErr_Print();
1180 return -1;
1181 }
1182 m = PyImport_AddModule("__main__");
1183 if (m == NULL) {
1184 PyArena_Free(arena);
1185 return -1;
1186 }
1187 d = PyModule_GetDict(m);
1188 v = run_mod(mod, filename, d, d, flags, arena);
1189 PyArena_Free(arena);
1190 flush_io();
1191 if (v == NULL) {
1192 PyErr_Print();
1193 return -1;
1194 }
1195 Py_DECREF(v);
1196 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001197}
1198
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001199/* Check whether a file maybe a pyc file: Look at the extension,
1200 the file type, and, if we may close it, at the first few bytes. */
1201
1202static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001203maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1206 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Only look into the file if we are allowed to close it, since
1209 it then should also be seekable. */
1210 if (closeit) {
1211 /* Read only two bytes of the magic. If the file was opened in
1212 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1213 be read as they are on disk. */
1214 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1215 unsigned char buf[2];
1216 /* Mess: In case of -x, the stream is NOT at its start now,
1217 and ungetc() was used to push back the first newline,
1218 which makes the current stream position formally undefined,
1219 and a x-platform nightmare.
1220 Unfortunately, we have no direct way to know whether -x
1221 was specified. So we use a terrible hack: if the current
1222 stream position is not 0, we assume -x was specified, and
1223 give up. Bug 132850 on SourceForge spells out the
1224 hopelessness of trying anything else (fseek and ftell
1225 don't work predictably x-platform for text-mode files).
1226 */
1227 int ispyc = 0;
1228 if (ftell(fp) == 0) {
1229 if (fread(buf, 1, 2, fp) == 2 &&
1230 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1231 ispyc = 1;
1232 rewind(fp);
1233 }
1234 return ispyc;
1235 }
1236 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001237}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001238
Guido van Rossum0df002c2000-08-27 19:21:52 +00001239int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001240PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 PyObject *m, *d, *v;
1244 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001245 int set_file_name = 0, ret;
1246 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 m = PyImport_AddModule("__main__");
1249 if (m == NULL)
1250 return -1;
1251 d = PyModule_GetDict(m);
1252 if (PyDict_GetItemString(d, "__file__") == NULL) {
1253 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001254 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (f == NULL)
1256 return -1;
1257 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1258 Py_DECREF(f);
1259 return -1;
1260 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001261 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1262 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 set_file_name = 1;
1266 Py_DECREF(f);
1267 }
1268 len = strlen(filename);
1269 ext = filename + len - (len > 4 ? 4 : 0);
1270 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1271 /* Try to run a pyc file. First, re-open in binary */
1272 if (closeit)
1273 fclose(fp);
1274 if ((fp = fopen(filename, "rb")) == NULL) {
1275 fprintf(stderr, "python: Can't reopen .pyc file\n");
1276 ret = -1;
1277 goto done;
1278 }
1279 /* Turn on optimization if a .pyo file is given */
1280 if (strcmp(ext, ".pyo") == 0)
1281 Py_OptimizeFlag = 1;
1282 v = run_pyc_file(fp, filename, d, d, flags);
1283 } else {
1284 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1285 closeit, flags);
1286 }
1287 flush_io();
1288 if (v == NULL) {
1289 PyErr_Print();
1290 ret = -1;
1291 goto done;
1292 }
1293 Py_DECREF(v);
1294 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001295 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1297 PyErr_Clear();
1298 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001299}
1300
1301int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001302PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *m, *d, *v;
1305 m = PyImport_AddModule("__main__");
1306 if (m == NULL)
1307 return -1;
1308 d = PyModule_GetDict(m);
1309 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1310 if (v == NULL) {
1311 PyErr_Print();
1312 return -1;
1313 }
1314 Py_DECREF(v);
1315 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001316}
1317
Barry Warsaw035574d1997-08-29 22:07:17 +00001318static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001319parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 long hold;
1323 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001324 _Py_IDENTIFIER(msg);
1325 _Py_IDENTIFIER(filename);
1326 _Py_IDENTIFIER(lineno);
1327 _Py_IDENTIFIER(offset);
1328 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* old style errors */
1331 if (PyTuple_Check(err))
1332 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1333 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001336
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001337 if (! (v = _PyObject_GetAttrId(err, &PyId_msg)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 goto finally;
1339 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001340
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001341 if (!(v = _PyObject_GetAttrId(err, &PyId_filename)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 goto finally;
1343 if (v == Py_None)
1344 *filename = NULL;
1345 else if (! (*filename = _PyUnicode_AsString(v)))
1346 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 Py_DECREF(v);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001349 if (!(v = _PyObject_GetAttrId(err, &PyId_lineno)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 goto finally;
1351 hold = PyLong_AsLong(v);
1352 Py_DECREF(v);
1353 v = NULL;
1354 if (hold < 0 && PyErr_Occurred())
1355 goto finally;
1356 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001357
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001358 if (!(v = _PyObject_GetAttrId(err, &PyId_offset)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 goto finally;
1360 if (v == Py_None) {
1361 *offset = -1;
1362 Py_DECREF(v);
1363 v = NULL;
1364 } else {
1365 hold = PyLong_AsLong(v);
1366 Py_DECREF(v);
1367 v = NULL;
1368 if (hold < 0 && PyErr_Occurred())
1369 goto finally;
1370 *offset = (int)hold;
1371 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001372
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001373 if (!(v = _PyObject_GetAttrId(err, &PyId_text)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 goto finally;
1375 if (v == Py_None)
1376 *text = NULL;
1377 else if (!PyUnicode_Check(v) ||
1378 !(*text = _PyUnicode_AsString(v)))
1379 goto finally;
1380 Py_DECREF(v);
1381 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001382
1383finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 Py_XDECREF(v);
1385 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001386}
1387
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001388void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001389PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001392}
1393
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001394static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001395print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 char *nl;
1398 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001399 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1400 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 for (;;) {
1402 nl = strchr(text, '\n');
1403 if (nl == NULL || nl-text >= offset)
1404 break;
1405 offset -= (int)(nl+1-text);
1406 text = nl+1;
1407 }
1408 while (*text == ' ' || *text == '\t') {
1409 text++;
1410 offset--;
1411 }
1412 }
1413 PyFile_WriteString(" ", f);
1414 PyFile_WriteString(text, f);
1415 if (*text == '\0' || text[strlen(text)-1] != '\n')
1416 PyFile_WriteString("\n", f);
1417 if (offset == -1)
1418 return;
1419 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001420 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001423}
1424
Guido van Rossum66e8e862001-03-23 17:54:43 +00001425static void
1426handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 PyObject *exception, *value, *tb;
1429 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (Py_InspectFlag)
1432 /* Don't exit if -i flag was given. This flag is set to 0
1433 * when entering interactive mode for inspecting. */
1434 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyErr_Fetch(&exception, &value, &tb);
1437 fflush(stdout);
1438 if (value == NULL || value == Py_None)
1439 goto done;
1440 if (PyExceptionInstance_Check(value)) {
1441 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001442 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001443 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (code) {
1445 Py_DECREF(value);
1446 value = code;
1447 if (value == Py_None)
1448 goto done;
1449 }
1450 /* If we failed to dig out the 'code' attribute,
1451 just let the else clause below print the error. */
1452 }
1453 if (PyLong_Check(value))
1454 exitcode = (int)PyLong_AsLong(value);
1455 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001456 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001457 if (sys_stderr != NULL && sys_stderr != Py_None) {
1458 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1459 } else {
1460 PyObject_Print(value, stderr, Py_PRINT_RAW);
1461 fflush(stderr);
1462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PySys_WriteStderr("\n");
1464 exitcode = 1;
1465 }
Tim Peterscf615b52003-04-19 18:47:02 +00001466 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 /* Restore and clear the exception info, in order to properly decref
1468 * the exception, value, and traceback. If we just exit instead,
1469 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1470 * some finalizers from running.
1471 */
1472 PyErr_Restore(exception, value, tb);
1473 PyErr_Clear();
1474 Py_Exit(exitcode);
1475 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001476}
1477
1478void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001479PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1484 handle_system_exit();
1485 }
1486 PyErr_Fetch(&exception, &v, &tb);
1487 if (exception == NULL)
1488 return;
1489 PyErr_NormalizeException(&exception, &v, &tb);
1490 if (tb == NULL) {
1491 tb = Py_None;
1492 Py_INCREF(tb);
1493 }
1494 PyException_SetTraceback(v, tb);
1495 if (exception == NULL)
1496 return;
1497 /* Now we know v != NULL too */
1498 if (set_sys_last_vars) {
1499 PySys_SetObject("last_type", exception);
1500 PySys_SetObject("last_value", v);
1501 PySys_SetObject("last_traceback", tb);
1502 }
1503 hook = PySys_GetObject("excepthook");
1504 if (hook) {
1505 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1506 PyObject *result = PyEval_CallObject(hook, args);
1507 if (result == NULL) {
1508 PyObject *exception2, *v2, *tb2;
1509 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1510 handle_system_exit();
1511 }
1512 PyErr_Fetch(&exception2, &v2, &tb2);
1513 PyErr_NormalizeException(&exception2, &v2, &tb2);
1514 /* It should not be possible for exception2 or v2
1515 to be NULL. However PyErr_Display() can't
1516 tolerate NULLs, so just be safe. */
1517 if (exception2 == NULL) {
1518 exception2 = Py_None;
1519 Py_INCREF(exception2);
1520 }
1521 if (v2 == NULL) {
1522 v2 = Py_None;
1523 Py_INCREF(v2);
1524 }
1525 fflush(stdout);
1526 PySys_WriteStderr("Error in sys.excepthook:\n");
1527 PyErr_Display(exception2, v2, tb2);
1528 PySys_WriteStderr("\nOriginal exception was:\n");
1529 PyErr_Display(exception, v, tb);
1530 Py_DECREF(exception2);
1531 Py_DECREF(v2);
1532 Py_XDECREF(tb2);
1533 }
1534 Py_XDECREF(result);
1535 Py_XDECREF(args);
1536 } else {
1537 PySys_WriteStderr("sys.excepthook is missing\n");
1538 PyErr_Display(exception, v, tb);
1539 }
1540 Py_XDECREF(exception);
1541 Py_XDECREF(v);
1542 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001543}
1544
Benjamin Petersone6528212008-07-15 15:32:09 +00001545static void
1546print_exception(PyObject *f, PyObject *value)
1547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 int err = 0;
1549 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 if (!PyExceptionInstance_Check(value)) {
1552 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1553 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1554 PyFile_WriteString(" found\n", f);
1555 return;
1556 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 Py_INCREF(value);
1559 fflush(stdout);
1560 type = (PyObject *) Py_TYPE(value);
1561 tb = PyException_GetTraceback(value);
1562 if (tb && tb != Py_None)
1563 err = PyTraceBack_Print(tb, f);
1564 if (err == 0 &&
1565 PyObject_HasAttrString(value, "print_file_and_line"))
1566 {
1567 PyObject *message;
1568 const char *filename, *text;
1569 int lineno, offset;
1570 if (!parse_syntax_error(value, &message, &filename,
1571 &lineno, &offset, &text))
1572 PyErr_Clear();
1573 else {
1574 char buf[10];
1575 PyFile_WriteString(" File \"", f);
1576 if (filename == NULL)
1577 PyFile_WriteString("<string>", f);
1578 else
1579 PyFile_WriteString(filename, f);
1580 PyFile_WriteString("\", line ", f);
1581 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1582 PyFile_WriteString(buf, f);
1583 PyFile_WriteString("\n", f);
1584 if (text != NULL)
1585 print_error_text(f, offset, text);
1586 Py_DECREF(value);
1587 value = message;
1588 /* Can't be bothered to check all those
1589 PyFile_WriteString() calls */
1590 if (PyErr_Occurred())
1591 err = -1;
1592 }
1593 }
1594 if (err) {
1595 /* Don't do anything else */
1596 }
1597 else {
1598 PyObject* moduleName;
1599 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001600 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 assert(PyExceptionClass_Check(type));
1602 className = PyExceptionClass_Name(type);
1603 if (className != NULL) {
1604 char *dot = strrchr(className, '.');
1605 if (dot != NULL)
1606 className = dot+1;
1607 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001608
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001609 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1611 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001612 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 err = PyFile_WriteString("<unknown>", f);
1614 }
1615 else {
1616 char* modstr = _PyUnicode_AsString(moduleName);
1617 if (modstr && strcmp(modstr, "builtins"))
1618 {
1619 err = PyFile_WriteString(modstr, f);
1620 err += PyFile_WriteString(".", f);
1621 }
1622 Py_DECREF(moduleName);
1623 }
1624 if (err == 0) {
1625 if (className == NULL)
1626 err = PyFile_WriteString("<unknown>", f);
1627 else
1628 err = PyFile_WriteString(className, f);
1629 }
1630 }
1631 if (err == 0 && (value != Py_None)) {
1632 PyObject *s = PyObject_Str(value);
1633 /* only print colon if the str() of the
1634 object is not the empty string
1635 */
1636 if (s == NULL)
1637 err = -1;
1638 else if (!PyUnicode_Check(s) ||
1639 PyUnicode_GetSize(s) != 0)
1640 err = PyFile_WriteString(": ", f);
1641 if (err == 0)
1642 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1643 Py_XDECREF(s);
1644 }
1645 /* try to write a newline in any case */
1646 err += PyFile_WriteString("\n", f);
1647 Py_XDECREF(tb);
1648 Py_DECREF(value);
1649 /* If an error happened here, don't show it.
1650 XXX This is wrong, but too many callers rely on this behavior. */
1651 if (err != 0)
1652 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001653}
1654
1655static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 "\nThe above exception was the direct cause "
1657 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001658
1659static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 "\nDuring handling of the above exception, "
1661 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001662
1663static void
1664print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 int err = 0, res;
1667 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (seen != NULL) {
1670 /* Exception chaining */
1671 if (PySet_Add(seen, value) == -1)
1672 PyErr_Clear();
1673 else if (PyExceptionInstance_Check(value)) {
1674 cause = PyException_GetCause(value);
1675 context = PyException_GetContext(value);
1676 if (cause) {
1677 res = PySet_Contains(seen, cause);
1678 if (res == -1)
1679 PyErr_Clear();
1680 if (res == 0) {
1681 print_exception_recursive(
1682 f, cause, seen);
1683 err |= PyFile_WriteString(
1684 cause_message, f);
1685 }
1686 }
1687 else if (context) {
1688 res = PySet_Contains(seen, context);
1689 if (res == -1)
1690 PyErr_Clear();
1691 if (res == 0) {
1692 print_exception_recursive(
1693 f, context, seen);
1694 err |= PyFile_WriteString(
1695 context_message, f);
1696 }
1697 }
1698 Py_XDECREF(context);
1699 Py_XDECREF(cause);
1700 }
1701 }
1702 print_exception(f, value);
1703 if (err != 0)
1704 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001705}
1706
Thomas Wouters477c8d52006-05-27 19:21:47 +00001707void
1708PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyObject *seen;
1711 PyObject *f = PySys_GetObject("stderr");
1712 if (f == Py_None) {
1713 /* pass */
1714 }
1715 else if (f == NULL) {
1716 _PyObject_Dump(value);
1717 fprintf(stderr, "lost sys.stderr\n");
1718 }
1719 else {
1720 /* We choose to ignore seen being possibly NULL, and report
1721 at least the main exception (it could be a MemoryError).
1722 */
1723 seen = PySet_New(NULL);
1724 if (seen == NULL)
1725 PyErr_Clear();
1726 print_exception_recursive(f, value, seen);
1727 Py_XDECREF(seen);
1728 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001729}
1730
Guido van Rossum82598051997-03-05 00:20:32 +00001731PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001732PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyObject *ret = NULL;
1736 mod_ty mod;
1737 PyArena *arena = PyArena_New();
1738 if (arena == NULL)
1739 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1742 if (mod != NULL)
1743 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1744 PyArena_Free(arena);
1745 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001746}
1747
1748PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001749PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 PyObject *ret;
1753 mod_ty mod;
1754 PyArena *arena = PyArena_New();
1755 if (arena == NULL)
1756 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1759 flags, NULL, arena);
1760 if (closeit)
1761 fclose(fp);
1762 if (mod == NULL) {
1763 PyArena_Free(arena);
1764 return NULL;
1765 }
1766 ret = run_mod(mod, filename, globals, locals, flags, arena);
1767 PyArena_Free(arena);
1768 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001769}
1770
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001771static void
1772flush_io(void)
1773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyObject *f, *r;
1775 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001776 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* Save the current exception */
1779 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 f = PySys_GetObject("stderr");
1782 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001783 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (r)
1785 Py_DECREF(r);
1786 else
1787 PyErr_Clear();
1788 }
1789 f = PySys_GetObject("stdout");
1790 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001791 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 if (r)
1793 Py_DECREF(r);
1794 else
1795 PyErr_Clear();
1796 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001799}
1800
Guido van Rossum82598051997-03-05 00:20:32 +00001801static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyCodeObject *co;
1806 PyObject *v;
1807 co = PyAST_Compile(mod, filename, flags, arena);
1808 if (co == NULL)
1809 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001810 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 Py_DECREF(co);
1812 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001813}
1814
Guido van Rossum82598051997-03-05 00:20:32 +00001815static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001816run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyCodeObject *co;
1820 PyObject *v;
1821 long magic;
1822 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 magic = PyMarshal_ReadLongFromFile(fp);
1825 if (magic != PyImport_GetMagicNumber()) {
1826 PyErr_SetString(PyExc_RuntimeError,
1827 "Bad magic number in .pyc file");
1828 return NULL;
1829 }
1830 (void) PyMarshal_ReadLongFromFile(fp);
1831 v = PyMarshal_ReadLastObjectFromFile(fp);
1832 fclose(fp);
1833 if (v == NULL || !PyCode_Check(v)) {
1834 Py_XDECREF(v);
1835 PyErr_SetString(PyExc_RuntimeError,
1836 "Bad code object in .pyc file");
1837 return NULL;
1838 }
1839 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001840 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (v && flags)
1842 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1843 Py_DECREF(co);
1844 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001845}
1846
Guido van Rossum82598051997-03-05 00:20:32 +00001847PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001848Py_CompileStringExFlags(const char *str, const char *filename, int start,
1849 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyCodeObject *co;
1852 mod_ty mod;
1853 PyArena *arena = PyArena_New();
1854 if (arena == NULL)
1855 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1858 if (mod == NULL) {
1859 PyArena_Free(arena);
1860 return NULL;
1861 }
1862 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1863 PyObject *result = PyAST_mod2obj(mod);
1864 PyArena_Free(arena);
1865 return result;
1866 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001867 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyArena_Free(arena);
1869 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001870}
1871
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001872/* For use in Py_LIMITED_API */
1873#undef Py_CompileString
1874PyObject *
1875PyCompileString(const char *str, const char *filename, int start)
1876{
1877 return Py_CompileStringFlags(str, filename, start, NULL);
1878}
1879
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001880struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001881Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 struct symtable *st;
1884 mod_ty mod;
1885 PyCompilerFlags flags;
1886 PyArena *arena = PyArena_New();
1887 if (arena == NULL)
1888 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 flags.cf_flags = 0;
1891 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1892 if (mod == NULL) {
1893 PyArena_Free(arena);
1894 return NULL;
1895 }
1896 st = PySymtable_Build(mod, filename, 0);
1897 PyArena_Free(arena);
1898 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001899}
1900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901/* Preferred access to parser is through AST. */
1902mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001903PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 mod_ty mod;
1907 PyCompilerFlags localflags;
1908 perrdetail err;
1909 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1912 &_PyParser_Grammar, start, &err,
1913 &iflags);
1914 if (flags == NULL) {
1915 localflags.cf_flags = 0;
1916 flags = &localflags;
1917 }
1918 if (n) {
1919 flags->cf_flags |= iflags & PyCF_MASK;
1920 mod = PyAST_FromNode(n, flags, filename, arena);
1921 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
1923 else {
1924 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001925 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001927 err_free(&err);
1928 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929}
1930
1931mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001932PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 int start, char *ps1,
1934 char *ps2, PyCompilerFlags *flags, int *errcode,
1935 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 mod_ty mod;
1938 PyCompilerFlags localflags;
1939 perrdetail err;
1940 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1943 &_PyParser_Grammar,
1944 start, ps1, ps2, &err, &iflags);
1945 if (flags == NULL) {
1946 localflags.cf_flags = 0;
1947 flags = &localflags;
1948 }
1949 if (n) {
1950 flags->cf_flags |= iflags & PyCF_MASK;
1951 mod = PyAST_FromNode(n, flags, filename, arena);
1952 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 }
1954 else {
1955 err_input(&err);
1956 if (errcode)
1957 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001958 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001960 err_free(&err);
1961 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
Guido van Rossuma110aa61994-08-29 12:50:44 +00001964/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001965
Guido van Rossuma110aa61994-08-29 12:50:44 +00001966node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001967PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 perrdetail err;
1970 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1971 &_PyParser_Grammar,
1972 start, NULL, NULL, &err, flags);
1973 if (n == NULL)
1974 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001975 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001978}
1979
Guido van Rossuma110aa61994-08-29 12:50:44 +00001980/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001981
Guido van Rossuma110aa61994-08-29 12:50:44 +00001982node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001983PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 perrdetail err;
1986 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1987 start, &err, flags);
1988 if (n == NULL)
1989 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001990 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001992}
1993
1994node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001995PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 perrdetail err;
1999 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2000 &_PyParser_Grammar, start, &err, flags);
2001 if (n == NULL)
2002 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002003 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002005}
2006
2007node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002008PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002011}
2012
Guido van Rossum66ebd912003-04-17 16:02:26 +00002013/* May want to move a more generalized form of this to parsetok.c or
2014 even parser modules. */
2015
2016void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002017PyParser_ClearError(perrdetail *err)
2018{
2019 err_free(err);
2020}
2021
2022void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002023PyParser_SetError(perrdetail *err)
2024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002026}
2027
Victor Stinner7f2fee32011-04-05 00:39:01 +02002028static void
2029err_free(perrdetail *err)
2030{
2031 Py_CLEAR(err->filename);
2032}
2033
Guido van Rossuma110aa61994-08-29 12:50:44 +00002034/* Set the error appropriate to the given input error code (see errcode.h) */
2035
2036static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002037err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyObject *v, *w, *errtype, *errtext;
2040 PyObject *msg_obj = NULL;
2041 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 errtype = PyExc_SyntaxError;
2044 switch (err->error) {
2045 case E_ERROR:
2046 return;
2047 case E_SYNTAX:
2048 errtype = PyExc_IndentationError;
2049 if (err->expected == INDENT)
2050 msg = "expected an indented block";
2051 else if (err->token == INDENT)
2052 msg = "unexpected indent";
2053 else if (err->token == DEDENT)
2054 msg = "unexpected unindent";
2055 else {
2056 errtype = PyExc_SyntaxError;
2057 msg = "invalid syntax";
2058 }
2059 break;
2060 case E_TOKEN:
2061 msg = "invalid token";
2062 break;
2063 case E_EOFS:
2064 msg = "EOF while scanning triple-quoted string literal";
2065 break;
2066 case E_EOLS:
2067 msg = "EOL while scanning string literal";
2068 break;
2069 case E_INTR:
2070 if (!PyErr_Occurred())
2071 PyErr_SetNone(PyExc_KeyboardInterrupt);
2072 goto cleanup;
2073 case E_NOMEM:
2074 PyErr_NoMemory();
2075 goto cleanup;
2076 case E_EOF:
2077 msg = "unexpected EOF while parsing";
2078 break;
2079 case E_TABSPACE:
2080 errtype = PyExc_TabError;
2081 msg = "inconsistent use of tabs and spaces in indentation";
2082 break;
2083 case E_OVERFLOW:
2084 msg = "expression too long";
2085 break;
2086 case E_DEDENT:
2087 errtype = PyExc_IndentationError;
2088 msg = "unindent does not match any outer indentation level";
2089 break;
2090 case E_TOODEEP:
2091 errtype = PyExc_IndentationError;
2092 msg = "too many levels of indentation";
2093 break;
2094 case E_DECODE: {
2095 PyObject *type, *value, *tb;
2096 PyErr_Fetch(&type, &value, &tb);
2097 msg = "unknown decode error";
2098 if (value != NULL)
2099 msg_obj = PyObject_Str(value);
2100 Py_XDECREF(type);
2101 Py_XDECREF(value);
2102 Py_XDECREF(tb);
2103 break;
2104 }
2105 case E_LINECONT:
2106 msg = "unexpected character after line continuation character";
2107 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 case E_IDENTIFIER:
2110 msg = "invalid character in identifier";
2111 break;
2112 default:
2113 fprintf(stderr, "error=%d\n", err->error);
2114 msg = "unknown parsing error";
2115 break;
2116 }
2117 /* err->text may not be UTF-8 in case of decoding errors.
2118 Explicitly convert to an object. */
2119 if (!err->text) {
2120 errtext = Py_None;
2121 Py_INCREF(Py_None);
2122 } else {
2123 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2124 "replace");
2125 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002126 v = Py_BuildValue("(OiiN)", err->filename,
2127 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (v != NULL) {
2129 if (msg_obj)
2130 w = Py_BuildValue("(OO)", msg_obj, v);
2131 else
2132 w = Py_BuildValue("(sO)", msg, v);
2133 } else
2134 w = NULL;
2135 Py_XDECREF(v);
2136 PyErr_SetObject(errtype, w);
2137 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002138cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 Py_XDECREF(msg_obj);
2140 if (err->text != NULL) {
2141 PyObject_FREE(err->text);
2142 err->text = NULL;
2143 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002144}
2145
2146/* Print fatal error message and abort */
2147
2148void
Tim Peters7c321a82002-07-09 02:57:01 +00002149Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002150{
Victor Stinner024e37a2011-03-31 01:31:06 +02002151 const int fd = fileno(stderr);
2152 PyThreadState *tstate;
2153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 fprintf(stderr, "Fatal Python error: %s\n", msg);
2155 fflush(stderr); /* it helps in Windows debug build */
2156 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002157 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002159 else {
2160 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2161 if (tstate != NULL) {
2162 fputc('\n', stderr);
2163 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002164 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002165 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002166 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002167 }
2168
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002169#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 {
2171 size_t len = strlen(msg);
2172 WCHAR* buffer;
2173 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* Convert the message to wchar_t. This uses a simple one-to-one
2176 conversion, assuming that the this error message actually uses ASCII
2177 only. If this ceases to be true, we will have to convert. */
2178 buffer = alloca( (len+1) * (sizeof *buffer));
2179 for( i=0; i<=len; ++i)
2180 buffer[i] = msg[i];
2181 OutputDebugStringW(L"Fatal Python error: ");
2182 OutputDebugStringW(buffer);
2183 OutputDebugStringW(L"\n");
2184 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002185#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002187#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002188#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002190}
2191
2192/* Clean up and exit */
2193
Guido van Rossuma110aa61994-08-29 12:50:44 +00002194#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002195#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002196#endif
2197
Collin Winter670e6922007-03-21 02:57:17 +00002198static void (*pyexitfunc)(void) = NULL;
2199/* For the atexit module. */
2200void _Py_PyAtExit(void (*func)(void))
2201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002203}
2204
2205static void
2206call_py_exitfuncs(void)
2207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (pyexitfunc == NULL)
2209 return;
Collin Winter670e6922007-03-21 02:57:17 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 (*pyexitfunc)();
2212 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002213}
2214
Antoine Pitrou011bd622009-10-20 21:52:47 +00002215/* Wait until threading._shutdown completes, provided
2216 the threading module was imported in the first place.
2217 The shutdown routine will wait until all non-daemon
2218 "threading" threads have completed. */
2219static void
2220wait_for_thread_shutdown(void)
2221{
2222#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002223 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 PyObject *result;
2225 PyThreadState *tstate = PyThreadState_GET();
2226 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2227 "threading");
2228 if (threading == NULL) {
2229 /* threading not imported */
2230 PyErr_Clear();
2231 return;
2232 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002233 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (result == NULL) {
2235 PyErr_WriteUnraisable(threading);
2236 }
2237 else {
2238 Py_DECREF(result);
2239 }
2240 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002241#endif
2242}
2243
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002244#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002245static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002246static int nexitfuncs = 0;
2247
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002248int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 if (nexitfuncs >= NEXITFUNCS)
2251 return -1;
2252 exitfuncs[nexitfuncs++] = func;
2253 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002254}
2255
Guido van Rossumcc283f51997-08-05 02:22:03 +00002256static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002257call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 while (nexitfuncs > 0)
2260 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 fflush(stdout);
2263 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002264}
2265
2266void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002267Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002272}
2273
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002274static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002275initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002276{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002277#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002279#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002280#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002282#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002283#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002285#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002287}
2288
Guido van Rossum7433b121997-02-14 19:45:36 +00002289
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002290/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2291 *
2292 * All of the code in this function must only use async-signal-safe functions,
2293 * listed at `man 7 signal` or
2294 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2295 */
2296void
2297_Py_RestoreSignals(void)
2298{
2299#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002301#endif
2302#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002304#endif
2305#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002307#endif
2308}
2309
2310
Guido van Rossum7433b121997-02-14 19:45:36 +00002311/*
2312 * The file descriptor fd is considered ``interactive'' if either
2313 * a) isatty(fd) is TRUE, or
2314 * b) the -i flag was given, and the filename associated with
2315 * the descriptor is NULL or "<stdin>" or "???".
2316 */
2317int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002318Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 if (isatty((int)fileno(fp)))
2321 return 1;
2322 if (!Py_InteractiveFlag)
2323 return 0;
2324 return (filename == NULL) ||
2325 (strcmp(filename, "<stdin>") == 0) ||
2326 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002327}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002328
2329
Tim Petersd08e3822003-04-17 15:24:21 +00002330#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002331#if defined(WIN32) && defined(_MSC_VER)
2332
2333/* Stack checking for Microsoft C */
2334
2335#include <malloc.h>
2336#include <excpt.h>
2337
Fred Drakee8de31c2000-08-31 05:38:39 +00002338/*
2339 * Return non-zero when we run out of memory on the stack; zero otherwise.
2340 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002341int
Fred Drake399739f2000-08-31 05:52:44 +00002342PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 __try {
2345 /* alloca throws a stack overflow exception if there's
2346 not enough space left on the stack */
2347 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2348 return 0;
2349 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2350 EXCEPTION_EXECUTE_HANDLER :
2351 EXCEPTION_CONTINUE_SEARCH) {
2352 int errcode = _resetstkoflw();
2353 if (errcode == 0)
2354 {
2355 Py_FatalError("Could not reset the stack!");
2356 }
2357 }
2358 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002359}
2360
2361#endif /* WIN32 && _MSC_VER */
2362
2363/* Alternate implementations can be added here... */
2364
2365#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002366
2367
2368/* Wrappers around sigaction() or signal(). */
2369
2370PyOS_sighandler_t
2371PyOS_getsig(int sig)
2372{
2373#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 struct sigaction context;
2375 if (sigaction(sig, NULL, &context) == -1)
2376 return SIG_ERR;
2377 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002378#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002380/* Special signal handling for the secure CRT in Visual Studio 2005 */
2381#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 switch (sig) {
2383 /* Only these signals are valid */
2384 case SIGINT:
2385 case SIGILL:
2386 case SIGFPE:
2387 case SIGSEGV:
2388 case SIGTERM:
2389 case SIGBREAK:
2390 case SIGABRT:
2391 break;
2392 /* Don't call signal() with other values or it will assert */
2393 default:
2394 return SIG_ERR;
2395 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002396#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 handler = signal(sig, SIG_IGN);
2398 if (handler != SIG_ERR)
2399 signal(sig, handler);
2400 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002401#endif
2402}
2403
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002404/*
2405 * All of the code in this function must only use async-signal-safe functions,
2406 * listed at `man 7 signal` or
2407 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2408 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002409PyOS_sighandler_t
2410PyOS_setsig(int sig, PyOS_sighandler_t handler)
2411{
2412#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* Some code in Modules/signalmodule.c depends on sigaction() being
2414 * used here if HAVE_SIGACTION is defined. Fix that if this code
2415 * changes to invalidate that assumption.
2416 */
2417 struct sigaction context, ocontext;
2418 context.sa_handler = handler;
2419 sigemptyset(&context.sa_mask);
2420 context.sa_flags = 0;
2421 if (sigaction(sig, &context, &ocontext) == -1)
2422 return SIG_ERR;
2423 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002424#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 PyOS_sighandler_t oldhandler;
2426 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002427#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002429#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002431#endif
2432}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433
2434/* Deprecated C API functions still provided for binary compatiblity */
2435
2436#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002437PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441}
2442
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443#undef PyParser_SimpleParseString
2444PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445PyParser_SimpleParseString(const char *str, int start)
2446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002449
2450#undef PyRun_AnyFile
2451PyAPI_FUNC(int)
2452PyRun_AnyFile(FILE *fp, const char *name)
2453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002455}
2456
2457#undef PyRun_AnyFileEx
2458PyAPI_FUNC(int)
2459PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002462}
2463
2464#undef PyRun_AnyFileFlags
2465PyAPI_FUNC(int)
2466PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002469}
2470
2471#undef PyRun_File
2472PyAPI_FUNC(PyObject *)
2473PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002476}
2477
2478#undef PyRun_FileEx
2479PyAPI_FUNC(PyObject *)
2480PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002483}
2484
2485#undef PyRun_FileFlags
2486PyAPI_FUNC(PyObject *)
2487PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002491}
2492
2493#undef PyRun_SimpleFile
2494PyAPI_FUNC(int)
2495PyRun_SimpleFile(FILE *f, const char *p)
2496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002498}
2499
2500#undef PyRun_SimpleFileEx
2501PyAPI_FUNC(int)
2502PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002505}
2506
2507
2508#undef PyRun_String
2509PyAPI_FUNC(PyObject *)
2510PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002513}
2514
2515#undef PyRun_SimpleString
2516PyAPI_FUNC(int)
2517PyRun_SimpleString(const char *s)
2518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002520}
2521
2522#undef Py_CompileString
2523PyAPI_FUNC(PyObject *)
2524Py_CompileString(const char *str, const char *p, int s)
2525{
Georg Brandl8334fd92010-12-04 10:26:46 +00002526 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2527}
2528
2529#undef Py_CompileStringFlags
2530PyAPI_FUNC(PyObject *)
2531Py_CompileStringFlags(const char *str, const char *p, int s,
2532 PyCompilerFlags *flags)
2533{
2534 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002535}
2536
2537#undef PyRun_InteractiveOne
2538PyAPI_FUNC(int)
2539PyRun_InteractiveOne(FILE *f, const char *p)
2540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002542}
2543
2544#undef PyRun_InteractiveLoop
2545PyAPI_FUNC(int)
2546PyRun_InteractiveLoop(FILE *f, const char *p)
2547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002549}
2550
2551#ifdef __cplusplus
2552}
2553#endif