1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Python interpreter top-level routines, including init/exit */
57 extern char *Py_GetPath();
59 extern grammar _PyParser_Grammar
; /* From graminit.c */
62 static void initmain
Py_PROTO((void));
63 static void initsite
Py_PROTO((void));
64 static PyObject
*run_err_node
Py_PROTO((node
*n
, char *filename
,
65 PyObject
*globals
, PyObject
*locals
));
66 static PyObject
*run_node
Py_PROTO((node
*n
, char *filename
,
67 PyObject
*globals
, PyObject
*locals
));
68 static PyObject
*run_pyc_file
Py_PROTO((FILE *fp
, char *filename
,
69 PyObject
*globals
, PyObject
*locals
));
70 static void err_input
Py_PROTO((perrdetail
*));
71 static void initsigs
Py_PROTO((void));
72 static void call_sys_exitfunc
Py_PROTO((void));
73 static void call_ll_exitfuncs
Py_PROTO((void));
76 int _Py_AskYesNo(char *prompt
);
79 int Py_DebugFlag
; /* Needed by parser.c */
80 int Py_VerboseFlag
; /* Needed by import.c */
81 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
82 int Py_NoSiteFlag
; /* Suppress 'import site' */
83 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c */
84 int Py_FrozenFlag
; /* Needed by getpath.c */
86 static int initialized
= 0;
88 /* API to access the initialized flag -- useful for eroteric use */
96 /* Global initializations. Can be undone by Py_Finalize(). Don't
97 call this twice without an intervening Py_Finalize() call. When
98 initializations fail, a fatal error is issued and the function does
99 not return. On return, the first thread and interpreter state have
102 Locking: you must hold the interpreter lock while calling this.
103 (If the lock has not yet been initialized, that's equivalent to
104 having the lock, but you cannot use multiple threads.)
111 PyInterpreterState
*interp
;
112 PyThreadState
*tstate
;
113 PyObject
*bimod
, *sysmod
;
120 if ((p
= getenv("PYTHONDEBUG")) && *p
!= '\0')
122 if ((p
= getenv("PYTHONVERBOSE")) && *p
!= '\0')
124 if ((p
= getenv("PYTHONOPTIMIZE")) && *p
!= '\0')
127 interp
= PyInterpreterState_New();
129 Py_FatalError("Py_Initialize: can't make first interpreter");
131 tstate
= PyThreadState_New(interp
);
133 Py_FatalError("Py_Initialize: can't make first thread");
134 (void) PyThreadState_Swap(tstate
);
136 interp
->modules
= PyDict_New();
137 if (interp
->modules
== NULL
)
138 Py_FatalError("Py_Initialize: can't make modules dictionary");
140 bimod
= _PyBuiltin_Init_1();
142 Py_FatalError("Py_Initialize: can't initialize __builtin__");
143 interp
->builtins
= PyModule_GetDict(bimod
);
144 Py_INCREF(interp
->builtins
);
146 sysmod
= _PySys_Init();
148 Py_FatalError("Py_Initialize: can't initialize sys");
149 interp
->sysdict
= PyModule_GetDict(sysmod
);
150 Py_INCREF(interp
->sysdict
);
151 _PyImport_FixupExtension("sys", "sys");
152 PySys_SetPath(Py_GetPath());
153 PyDict_SetItemString(interp
->sysdict
, "modules",
158 /* phase 2 of builtins */
159 _PyBuiltin_Init_2(interp
->builtins
);
160 _PyImport_FixupExtension("__builtin__", "__builtin__");
162 initsigs(); /* Signal handling stuff, including initintr() */
164 initmain(); /* Module __main__ */
166 initsite(); /* Module site */
170 extern void dump_counts
Py_PROTO((void));
173 /* Undo the effect of Py_Initialize().
175 Beware: if multiple interpreter and/or thread states exist, these
176 are not wiped out; only the current thread and interpreter state
177 are deleted. But since everything else is deleted, those other
178 interpreter and thread states should no longer be used.
180 (XXX We should do better, e.g. wipe out all interpreters and
190 PyInterpreterState
*interp
;
191 PyThreadState
*tstate
;
199 /* Get current thread state and interpreter pointer */
200 tstate
= PyThreadState_Get();
201 interp
= tstate
->interp
;
203 /* Disable signal handling */
204 PyOS_FiniInterrupts();
206 /* Destroy PyExc_MemoryErrorInst */
209 /* Destroy all modules */
212 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
215 /* Debugging stuff */
221 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
225 if (_Py_AskYesNo("Print left references?")) {
226 _Py_PrintReferences(stderr
);
228 #endif /* Py_TRACE_REFS */
230 /* Delete current thread */
231 PyInterpreterState_Clear(interp
);
232 PyThreadState_Swap(NULL
);
233 PyInterpreterState_Delete(interp
);
235 /* Now we decref the exception classes. After this point nothing
236 can raise an exception. That's okay, because each Fini() method
237 below has been checked to make sure no exceptions are ever
249 /* XXX Still allocated:
250 - various static ad-hoc pointers to interned strings
251 - int and float free list blocks
252 - whatever various modules and libraries allocate
255 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
260 _Py_ResetReferences();
261 #endif /* Py_TRACE_REFS */
264 /* Create and initialize a new interpreter and thread, and return the
265 new thread. This requires that Py_Initialize() has been called
268 Unsuccessful initialization yields a NULL pointer. Note that *no*
269 exception information is available even in this case -- the
270 exception information is held in the thread, and there is no
280 PyInterpreterState
*interp
;
281 PyThreadState
*tstate
, *save_tstate
;
282 PyObject
*bimod
, *sysmod
;
285 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
287 interp
= PyInterpreterState_New();
291 tstate
= PyThreadState_New(interp
);
292 if (tstate
== NULL
) {
293 PyInterpreterState_Delete(interp
);
297 save_tstate
= PyThreadState_Swap(tstate
);
299 /* XXX The following is lax in error checking */
301 interp
->modules
= PyDict_New();
303 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
305 interp
->builtins
= PyModule_GetDict(bimod
);
306 Py_INCREF(interp
->builtins
);
308 sysmod
= _PyImport_FindExtension("sys", "sys");
309 if (bimod
!= NULL
&& sysmod
!= NULL
) {
310 interp
->sysdict
= PyModule_GetDict(sysmod
);
311 Py_INCREF(interp
->sysdict
);
312 PySys_SetPath(Py_GetPath());
313 PyDict_SetItemString(interp
->sysdict
, "modules",
320 if (!PyErr_Occurred())
323 /* Oops, it didn't work. Undo it all. */
326 PyThreadState_Clear(tstate
);
327 PyThreadState_Swap(save_tstate
);
328 PyThreadState_Delete(tstate
);
329 PyInterpreterState_Delete(interp
);
334 /* Delete an interpreter and its last thread. This requires that the
335 given thread state is current, that the thread has no remaining
336 frames, and that it is its interpreter's only remaining thread.
337 It is a fatal error to violate these constraints.
339 (Py_Finalize() doesn't have these constraints -- it zaps
340 everything, regardless.)
347 Py_EndInterpreter(tstate
)
348 PyThreadState
*tstate
;
350 PyInterpreterState
*interp
= tstate
->interp
;
352 if (tstate
!= PyThreadState_Get())
353 Py_FatalError("Py_EndInterpreter: thread is not current");
354 if (tstate
->frame
!= NULL
)
355 Py_FatalError("Py_EndInterpreter: thread still has a frame");
356 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
357 Py_FatalError("Py_EndInterpreter: not the last thread");
360 PyInterpreterState_Clear(interp
);
361 PyThreadState_Swap(NULL
);
362 PyInterpreterState_Delete(interp
);
365 static char *progname
= "python";
368 Py_SetProgramName(pn
)
381 static char *default_home
= NULL
;
384 Py_SetPythonHome(home
)
393 char *home
= default_home
;
395 home
= getenv("PYTHONHOME");
399 /* Create __main__ module */
405 m
= PyImport_AddModule("__main__");
407 Py_FatalError("can't create __main__ module");
408 d
= PyModule_GetDict(m
);
409 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
410 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
412 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
413 Py_FatalError("can't add __builtins__ to __main__");
418 /* Import the site module (not into __main__ though) */
424 m
= PyImport_ImportModule("site");
426 f
= PySys_GetObject("stderr");
427 if (Py_VerboseFlag
) {
429 "'import site' failed; traceback:\n", f
);
434 "'import site' failed; use -v for traceback\n", f
);
443 /* Parse input from a file and execute it */
446 PyRun_AnyFile(fp
, filename
)
450 if (filename
== NULL
)
452 if (Py_FdIsInteractive(fp
, filename
))
453 return PyRun_InteractiveLoop(fp
, filename
);
455 return PyRun_SimpleFile(fp
, filename
);
459 PyRun_InteractiveLoop(fp
, filename
)
465 v
= PySys_GetObject("ps1");
467 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
470 v
= PySys_GetObject("ps2");
472 PySys_SetObject("ps2", v
= PyString_FromString("... "));
476 ret
= PyRun_InteractiveOne(fp
, filename
);
478 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
490 PyRun_InteractiveOne(fp
, filename
)
494 PyObject
*m
, *d
, *v
, *w
;
497 char *ps1
= "", *ps2
= "";
498 v
= PySys_GetObject("ps1");
503 else if (PyString_Check(v
))
504 ps1
= PyString_AsString(v
);
506 w
= PySys_GetObject("ps2");
511 else if (PyString_Check(w
))
512 ps2
= PyString_AsString(w
);
514 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
,
515 Py_single_input
, ps1
, ps2
, &err
);
519 if (err
.error
== E_EOF
) {
528 m
= PyImport_AddModule("__main__");
531 d
= PyModule_GetDict(m
);
532 v
= run_node(n
, filename
, d
, d
);
544 PyRun_SimpleFile(fp
, filename
)
551 m
= PyImport_AddModule("__main__");
554 d
= PyModule_GetDict(m
);
555 ext
= filename
+ strlen(filename
) - 4;
556 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0
558 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
559 || getfiletype(filename
) == 'PYC '
560 || getfiletype(filename
) == 'APPL'
561 #endif /* macintosh */
563 /* Try to run a pyc file. First, re-open in binary */
564 /* Don't close, done in main: fclose(fp); */
565 if( (fp
= fopen(filename
, "rb")) == NULL
) {
566 fprintf(stderr
, "python: Can't reopen .pyc file\n");
569 /* Turn on optimization if a .pyo file is given */
570 if (strcmp(ext
, ".pyo") == 0)
572 v
= run_pyc_file(fp
, filename
, d
, d
);
574 v
= PyRun_File(fp
, filename
, Py_file_input
, d
, d
);
587 PyRun_SimpleString(command
)
591 m
= PyImport_AddModule("__main__");
594 d
= PyModule_GetDict(m
);
595 v
= PyRun_String(command
, Py_file_input
, d
, d
);
607 parse_syntax_error(err
, message
, filename
, lineno
, offset
, text
)
618 /* old style errors */
619 if (PyTuple_Check(err
))
620 return PyArg_Parse(err
, "(O(ziiz))", message
, filename
,
621 lineno
, offset
, text
);
623 /* new style errors. `err' is an instance */
625 if (! (v
= PyObject_GetAttrString(err
, "msg")))
629 if (!(v
= PyObject_GetAttrString(err
, "filename")))
633 else if (! (*filename
= PyString_AsString(v
)))
637 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
639 hold
= PyInt_AsLong(v
);
642 if (hold
< 0 && PyErr_Occurred())
646 if (!(v
= PyObject_GetAttrString(err
, "offset")))
648 hold
= PyInt_AsLong(v
);
651 if (hold
< 0 && PyErr_Occurred())
655 if (!(v
= PyObject_GetAttrString(err
, "text")))
659 else if (! (*text
= PyString_AsString(v
)))
676 PyErr_PrintEx(set_sys_last_vars
)
677 int set_sys_last_vars
;
680 PyObject
*exception
, *v
, *tb
, *f
;
681 PyErr_Fetch(&exception
, &v
, &tb
);
682 PyErr_NormalizeException(&exception
, &v
, &tb
);
684 if (exception
== NULL
)
687 if (PyErr_GivenExceptionMatches(exception
, PyExc_SystemExit
)) {
691 if (v
== NULL
|| v
== Py_None
)
693 if (PyInstance_Check(v
)) {
694 /* we expect the error code to be store in the
697 PyObject
*code
= PyObject_GetAttrString(v
, "code");
704 /* if we failed to dig out the "code" attribute,
705 then just let the else clause below print the
710 Py_Exit((int)PyInt_AsLong(v
));
712 /* OK to use real stderr here */
713 PyObject_Print(v
, stderr
, Py_PRINT_RAW
);
714 fprintf(stderr
, "\n");
718 if (set_sys_last_vars
) {
719 PySys_SetObject("last_type", exception
);
720 PySys_SetObject("last_value", v
);
721 PySys_SetObject("last_traceback", tb
);
723 f
= PySys_GetObject("stderr");
725 fprintf(stderr
, "lost sys.stderr\n");
730 err
= PyTraceBack_Print(tb
, f
);
732 PyErr_GivenExceptionMatches(exception
, PyExc_SyntaxError
))
735 char *filename
, *text
;
737 if (!parse_syntax_error(v
, &message
, &filename
,
738 &lineno
, &offset
, &text
))
742 PyFile_WriteString(" File \"", f
);
743 if (filename
== NULL
)
744 PyFile_WriteString("<string>", f
);
746 PyFile_WriteString(filename
, f
);
747 PyFile_WriteString("\", line ", f
);
748 sprintf(buf
, "%d", lineno
);
749 PyFile_WriteString(buf
, f
);
750 PyFile_WriteString("\n", f
);
754 offset
== (int)strlen(text
))
757 nl
= strchr(text
, '\n');
761 offset
-= (nl
+1-text
);
764 while (*text
== ' ' || *text
== '\t') {
768 PyFile_WriteString(" ", f
);
769 PyFile_WriteString(text
, f
);
771 text
[strlen(text
)-1] != '\n')
772 PyFile_WriteString("\n", f
);
773 PyFile_WriteString(" ", f
);
776 PyFile_WriteString(" ", f
);
779 PyFile_WriteString("^\n", f
);
784 /* Can't be bothered to check all those
785 PyFile_WriteString() calls */
786 if (PyErr_Occurred())
791 /* Don't do anything else */
793 else if (PyClass_Check(exception
)) {
794 PyClassObject
* exc
= (PyClassObject
*)exception
;
795 PyObject
* className
= exc
->cl_name
;
796 PyObject
* moduleName
=
797 PyDict_GetItemString(exc
->cl_dict
, "__module__");
799 if (moduleName
== NULL
)
800 err
= PyFile_WriteString("<unknown>", f
);
802 char* modstr
= PyString_AsString(moduleName
);
803 if (modstr
&& strcmp(modstr
, "exceptions"))
805 err
= PyFile_WriteString(modstr
, f
);
806 err
+= PyFile_WriteString(".", f
);
810 if (className
== NULL
)
811 err
= PyFile_WriteString("<unknown>", f
);
813 err
= PyFile_WriteObject(className
, f
,
818 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
820 if (v
!= NULL
&& v
!= Py_None
) {
821 PyObject
*s
= PyObject_Str(v
);
822 /* only print colon if the str() of the
823 object is not the empty string
827 else if (!PyString_Check(s
) ||
828 PyString_GET_SIZE(s
) != 0)
829 err
= PyFile_WriteString(": ", f
);
831 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
836 err
= PyFile_WriteString("\n", f
);
838 Py_XDECREF(exception
);
841 /* If an error happened here, don't show it.
842 XXX This is wrong, but too many callers rely on this behavior. */
848 PyRun_String(str
, start
, globals
, locals
)
851 PyObject
*globals
, *locals
;
853 return run_err_node(PyParser_SimpleParseString(str
, start
),
854 "<string>", globals
, locals
);
858 PyRun_File(fp
, filename
, start
, globals
, locals
)
862 PyObject
*globals
, *locals
;
864 return run_err_node(PyParser_SimpleParseFile(fp
, filename
, start
),
865 filename
, globals
, locals
);
869 run_err_node(n
, filename
, globals
, locals
)
872 PyObject
*globals
, *locals
;
876 return run_node(n
, filename
, globals
, locals
);
880 run_node(n
, filename
, globals
, locals
)
883 PyObject
*globals
, *locals
;
887 co
= PyNode_Compile(n
, filename
);
891 v
= PyEval_EvalCode(co
, globals
, locals
);
897 run_pyc_file(fp
, filename
, globals
, locals
)
900 PyObject
*globals
, *locals
;
905 long PyImport_GetMagicNumber();
907 magic
= PyMarshal_ReadLongFromFile(fp
);
908 if (magic
!= PyImport_GetMagicNumber()) {
909 PyErr_SetString(PyExc_RuntimeError
,
910 "Bad magic number in .pyc file");
913 (void) PyMarshal_ReadLongFromFile(fp
);
914 v
= PyMarshal_ReadObjectFromFile(fp
);
916 if (v
== NULL
|| !PyCode_Check(v
)) {
918 PyErr_SetString(PyExc_RuntimeError
,
919 "Bad code object in .pyc file");
922 co
= (PyCodeObject
*)v
;
923 v
= PyEval_EvalCode(co
, globals
, locals
);
929 Py_CompileString(str
, filename
, start
)
936 n
= PyParser_SimpleParseString(str
, start
);
939 co
= PyNode_Compile(n
, filename
);
941 return (PyObject
*)co
;
944 /* Simplified interface to parsefile -- return node or set exception */
947 PyParser_SimpleParseFile(fp
, filename
, start
)
954 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
, start
,
955 (char *)0, (char *)0, &err
);
961 /* Simplified interface to parsestring -- return node or set exception */
964 PyParser_SimpleParseString(str
, start
)
970 n
= PyParser_ParseString(str
, &_PyParser_Grammar
, start
, &err
);
976 /* Set the error appropriate to the given input error code (see errcode.h) */
984 v
= Py_BuildValue("(ziiz)", err
->filename
,
985 err
->lineno
, err
->offset
, err
->text
);
986 if (err
->text
!= NULL
) {
990 switch (err
->error
) {
992 msg
= "invalid syntax";
995 msg
= "invalid token";
998 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1006 msg
= "unexpected EOF while parsing";
1009 msg
= "inconsistent use of tabs and spaces in indentation";
1012 fprintf(stderr
, "error=%d\n", err
->error
);
1013 msg
= "unknown parsing error";
1016 w
= Py_BuildValue("(sO)", msg
, v
);
1018 PyErr_SetObject(PyExc_SyntaxError
, w
);
1022 /* Print fatal error message and abort */
1028 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1033 OutputDebugString("Fatal Python error: ");
1034 OutputDebugString(msg
);
1035 OutputDebugString("\n");
1039 #endif /* MS_WIN32 */
1043 /* Clean up and exit */
1046 #include "pythread.h"
1047 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1050 #define NEXITFUNCS 32
1051 static void (*exitfuncs
[NEXITFUNCS
])();
1052 static int nexitfuncs
= 0;
1055 void (*func
) Py_PROTO((void));
1057 if (nexitfuncs
>= NEXITFUNCS
)
1059 exitfuncs
[nexitfuncs
++] = func
;
1066 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1070 Py_INCREF(exitfunc
);
1071 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1072 f
= PySys_GetObject("stderr");
1073 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1076 PyFile_WriteString("Error in sys.exitfunc:\n", f
);
1079 Py_DECREF(exitfunc
);
1089 while (nexitfuncs
> 0)
1090 (*exitfuncs
[--nexitfuncs
])();
1112 #ifdef HAVE_SIGNAL_H
1114 signal(SIGPIPE
, SIG_IGN
);
1116 #endif /* HAVE_SIGNAL_H */
1117 PyOS_InitInterrupts(); /* May imply initsignal() */
1120 #ifdef Py_TRACE_REFS
1121 /* Ask a yes/no question */
1124 _Py_AskYesNo(prompt
)
1129 printf("%s [ny] ", prompt
);
1130 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1132 return buf
[0] == 'y' || buf
[0] == 'Y';
1138 /* Check for file descriptor connected to interactive device.
1139 Pretend that stdin is always interactive, other files never. */
1145 return fd
== fileno(stdin
);
1151 * The file descriptor fd is considered ``interactive'' if either
1152 * a) isatty(fd) is TRUE, or
1153 * b) the -i flag was given, and the filename associated with
1154 * the descriptor is NULL or "<stdin>" or "???".
1157 Py_FdIsInteractive(fp
, filename
)
1161 if (isatty((int)fileno(fp
)))
1163 if (!Py_InteractiveFlag
)
1165 return (filename
== NULL
) ||
1166 (strcmp(filename
, "<stdin>") == 0) ||
1167 (strcmp(filename
, "???") == 0);