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));
75 int Py_DebugFlag
; /* Needed by parser.c */
76 int Py_VerboseFlag
; /* Needed by import.c */
77 int Py_InteractiveFlag
; /* Needed by Py_FdIsInteractive() below */
78 int Py_NoSiteFlag
; /* Suppress 'import site' */
79 int Py_UseClassExceptionsFlag
= 1; /* Needed by bltinmodule.c */
80 int Py_FrozenFlag
; /* Needed by getpath.c */
82 static int initialized
= 0;
84 /* API to access the initialized flag -- useful for eroteric use */
92 /* Global initializations. Can be undone by Py_Finalize(). Don't
93 call this twice without an intervening Py_Finalize() call. When
94 initializations fail, a fatal error is issued and the function does
95 not return. On return, the first thread and interpreter state have
98 Locking: you must hold the interpreter lock while calling this.
99 (If the lock has not yet been initialized, that's equivalent to
100 having the lock, but you cannot use multiple threads.)
107 PyInterpreterState
*interp
;
108 PyThreadState
*tstate
;
109 PyObject
*bimod
, *sysmod
;
116 if ((p
= getenv("PYTHONDEBUG")) && *p
!= '\0')
118 if ((p
= getenv("PYTHONVERBOSE")) && *p
!= '\0')
120 if ((p
= getenv("PYTHONOPTIMIZE")) && *p
!= '\0')
123 interp
= PyInterpreterState_New();
125 Py_FatalError("Py_Initialize: can't make first interpreter");
127 tstate
= PyThreadState_New(interp
);
129 Py_FatalError("Py_Initialize: can't make first thread");
130 (void) PyThreadState_Swap(tstate
);
132 interp
->modules
= PyDict_New();
133 if (interp
->modules
== NULL
)
134 Py_FatalError("Py_Initialize: can't make modules dictionary");
136 bimod
= _PyBuiltin_Init_1();
138 Py_FatalError("Py_Initialize: can't initialize __builtin__");
139 interp
->builtins
= PyModule_GetDict(bimod
);
140 Py_INCREF(interp
->builtins
);
142 sysmod
= _PySys_Init();
144 Py_FatalError("Py_Initialize: can't initialize sys");
145 interp
->sysdict
= PyModule_GetDict(sysmod
);
146 Py_INCREF(interp
->sysdict
);
147 _PyImport_FixupExtension("sys", "sys");
148 PySys_SetPath(Py_GetPath());
149 PyDict_SetItemString(interp
->sysdict
, "modules",
152 /* phase 2 of builtins */
153 _PyBuiltin_Init_2(interp
->builtins
);
154 _PyImport_FixupExtension("__builtin__", "__builtin__");
158 initsigs(); /* Signal handling stuff, including initintr() */
160 initmain(); /* Module __main__ */
162 initsite(); /* Module site */
166 extern void dump_counts
Py_PROTO((void));
169 /* Undo the effect of Py_Initialize().
171 Beware: if multiple interpreter and/or thread states exist, these
172 are not wiped out; only the current thread and interpreter state
173 are deleted. But since everything else is deleted, those other
174 interpreter and thread states should no longer be used.
176 (XXX We should do better, e.g. wipe out all interpreters and
186 PyInterpreterState
*interp
;
187 PyThreadState
*tstate
;
195 /* Get current thread state and interpreter pointer */
196 tstate
= PyThreadState_Get();
197 interp
= tstate
->interp
;
199 /* Disable signal handling */
200 PyOS_FiniInterrupts();
202 /* Destroy PyExc_MemoryErrorInst */
205 /* Destroy all modules */
208 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
211 /* Debugging stuff */
217 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
221 if (_Py_AskYesNo("Print left references?")) {
222 _Py_PrintReferences(stderr
);
224 #endif /* Py_TRACE_REFS */
226 /* Delete current thread */
227 PyInterpreterState_Clear(interp
);
228 PyThreadState_Swap(NULL
);
229 PyInterpreterState_Delete(interp
);
231 /* Now we decref the exception classes. After this point nothing
232 can raise an exception. That's okay, because each Fini() method
233 below has been checked to make sure no exceptions are ever
245 /* XXX Still allocated:
246 - various static ad-hoc pointers to interned strings
247 - int and float free list blocks
248 - whatever various modules and libraries allocate
251 PyGrammar_RemoveAccelerators(&_PyParser_Grammar
);
256 _Py_ResetReferences();
257 #endif /* Py_TRACE_REFS */
260 /* Create and initialize a new interpreter and thread, and return the
261 new thread. This requires that Py_Initialize() has been called
264 Unsuccessful initialization yields a NULL pointer. Note that *no*
265 exception information is available even in this case -- the
266 exception information is held in the thread, and there is no
276 PyInterpreterState
*interp
;
277 PyThreadState
*tstate
, *save_tstate
;
278 PyObject
*bimod
, *sysmod
;
281 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
283 interp
= PyInterpreterState_New();
287 tstate
= PyThreadState_New(interp
);
288 if (tstate
== NULL
) {
289 PyInterpreterState_Delete(interp
);
293 save_tstate
= PyThreadState_Swap(tstate
);
295 /* XXX The following is lax in error checking */
297 interp
->modules
= PyDict_New();
299 bimod
= _PyImport_FindExtension("__builtin__", "__builtin__");
301 interp
->builtins
= PyModule_GetDict(bimod
);
302 Py_INCREF(interp
->builtins
);
304 sysmod
= _PyImport_FindExtension("sys", "sys");
305 if (bimod
!= NULL
&& sysmod
!= NULL
) {
306 interp
->sysdict
= PyModule_GetDict(sysmod
);
307 Py_INCREF(interp
->sysdict
);
308 PySys_SetPath(Py_GetPath());
309 PyDict_SetItemString(interp
->sysdict
, "modules",
316 if (!PyErr_Occurred())
319 /* Oops, it didn't work. Undo it all. */
322 PyThreadState_Clear(tstate
);
323 PyThreadState_Swap(save_tstate
);
324 PyThreadState_Delete(tstate
);
325 PyInterpreterState_Delete(interp
);
330 /* Delete an interpreter and its last thread. This requires that the
331 given thread state is current, that the thread has no remaining
332 frames, and that it is its interpreter's only remaining thread.
333 It is a fatal error to violate these constraints.
335 (Py_Finalize() doesn't have these constraints -- it zaps
336 everything, regardless.)
343 Py_EndInterpreter(tstate
)
344 PyThreadState
*tstate
;
346 PyInterpreterState
*interp
= tstate
->interp
;
348 if (tstate
!= PyThreadState_Get())
349 Py_FatalError("Py_EndInterpreter: thread is not current");
350 if (tstate
->frame
!= NULL
)
351 Py_FatalError("Py_EndInterpreter: thread still has a frame");
352 if (tstate
!= interp
->tstate_head
|| tstate
->next
!= NULL
)
353 Py_FatalError("Py_EndInterpreter: not the last thread");
356 PyInterpreterState_Clear(interp
);
357 PyThreadState_Swap(NULL
);
358 PyInterpreterState_Delete(interp
);
361 static char *progname
= "python";
364 Py_SetProgramName(pn
)
377 static char *default_home
= NULL
;
380 Py_SetPythonHome(home
)
389 char *home
= default_home
;
391 home
= getenv("PYTHONHOME");
395 /* Create __main__ module */
401 m
= PyImport_AddModule("__main__");
403 Py_FatalError("can't create __main__ module");
404 d
= PyModule_GetDict(m
);
405 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
406 PyObject
*bimod
= PyImport_ImportModule("__builtin__");
408 PyDict_SetItemString(d
, "__builtins__", bimod
) != 0)
409 Py_FatalError("can't add __builtins__ to __main__");
414 /* Import the site module (not into __main__ though) */
420 m
= PyImport_ImportModule("site");
422 f
= PySys_GetObject("stderr");
423 if (Py_VerboseFlag
) {
425 "'import site' failed; traceback:\n", f
);
430 "'import site' failed; use -v for traceback\n", f
);
439 /* Parse input from a file and execute it */
442 PyRun_AnyFile(fp
, filename
)
446 if (filename
== NULL
)
448 if (Py_FdIsInteractive(fp
, filename
))
449 return PyRun_InteractiveLoop(fp
, filename
);
451 return PyRun_SimpleFile(fp
, filename
);
455 PyRun_InteractiveLoop(fp
, filename
)
461 v
= PySys_GetObject("ps1");
463 PySys_SetObject("ps1", v
= PyString_FromString(">>> "));
466 v
= PySys_GetObject("ps2");
468 PySys_SetObject("ps2", v
= PyString_FromString("... "));
472 ret
= PyRun_InteractiveOne(fp
, filename
);
474 fprintf(stderr
, "[%ld refs]\n", _Py_RefTotal
);
486 PyRun_InteractiveOne(fp
, filename
)
490 PyObject
*m
, *d
, *v
, *w
;
493 char *ps1
= "", *ps2
= "";
494 v
= PySys_GetObject("ps1");
499 else if (PyString_Check(v
))
500 ps1
= PyString_AsString(v
);
502 w
= PySys_GetObject("ps2");
507 else if (PyString_Check(w
))
508 ps2
= PyString_AsString(w
);
510 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
,
511 Py_single_input
, ps1
, ps2
, &err
);
515 if (err
.error
== E_EOF
) {
524 m
= PyImport_AddModule("__main__");
527 d
= PyModule_GetDict(m
);
528 v
= run_node(n
, filename
, d
, d
);
540 PyRun_SimpleFile(fp
, filename
)
547 m
= PyImport_AddModule("__main__");
550 d
= PyModule_GetDict(m
);
551 ext
= filename
+ strlen(filename
) - 4;
552 if (strcmp(ext
, ".pyc") == 0 || strcmp(ext
, ".pyo") == 0
554 /* On a mac, we also assume a pyc file for types 'PYC ' and 'APPL' */
555 || getfiletype(filename
) == 'PYC '
556 || getfiletype(filename
) == 'APPL'
557 #endif /* macintosh */
559 /* Try to run a pyc file. First, re-open in binary */
560 /* Don't close, done in main: fclose(fp); */
561 if( (fp
= fopen(filename
, "rb")) == NULL
) {
562 fprintf(stderr
, "python: Can't reopen .pyc file\n");
565 /* Turn on optimization if a .pyo file is given */
566 if (strcmp(ext
, ".pyo") == 0)
568 v
= run_pyc_file(fp
, filename
, d
, d
);
570 v
= PyRun_File(fp
, filename
, Py_file_input
, d
, d
);
583 PyRun_SimpleString(command
)
587 m
= PyImport_AddModule("__main__");
590 d
= PyModule_GetDict(m
);
591 v
= PyRun_String(command
, Py_file_input
, d
, d
);
603 parse_syntax_error(err
, message
, filename
, lineno
, offset
, text
)
614 /* old style errors */
615 if (PyTuple_Check(err
))
616 return PyArg_Parse(err
, "(O(ziiz))", message
, filename
,
617 lineno
, offset
, text
);
619 /* new style errors. `err' is an instance */
621 if (! (v
= PyObject_GetAttrString(err
, "msg")))
625 if (!(v
= PyObject_GetAttrString(err
, "filename")))
629 else if (! (*filename
= PyString_AsString(v
)))
633 if (!(v
= PyObject_GetAttrString(err
, "lineno")))
635 hold
= PyInt_AsLong(v
);
638 if (hold
< 0 && PyErr_Occurred())
642 if (!(v
= PyObject_GetAttrString(err
, "offset")))
644 hold
= PyInt_AsLong(v
);
647 if (hold
< 0 && PyErr_Occurred())
651 if (!(v
= PyObject_GetAttrString(err
, "text")))
655 else if (! (*text
= PyString_AsString(v
)))
672 PyErr_PrintEx(set_sys_last_vars
)
673 int set_sys_last_vars
;
676 PyObject
*exception
, *v
, *tb
, *f
;
677 PyErr_Fetch(&exception
, &v
, &tb
);
678 PyErr_NormalizeException(&exception
, &v
, &tb
);
680 if (exception
== NULL
)
683 if (PyErr_GivenExceptionMatches(exception
, PyExc_SystemExit
)) {
687 if (v
== NULL
|| v
== Py_None
)
689 if (PyInstance_Check(v
)) {
690 /* we expect the error code to be store in the
693 PyObject
*code
= PyObject_GetAttrString(v
, "code");
700 /* if we failed to dig out the "code" attribute,
701 then just let the else clause below print the
706 Py_Exit((int)PyInt_AsLong(v
));
708 /* OK to use real stderr here */
709 PyObject_Print(v
, stderr
, Py_PRINT_RAW
);
710 fprintf(stderr
, "\n");
714 if (set_sys_last_vars
) {
715 PySys_SetObject("last_type", exception
);
716 PySys_SetObject("last_value", v
);
717 PySys_SetObject("last_traceback", tb
);
719 f
= PySys_GetObject("stderr");
721 fprintf(stderr
, "lost sys.stderr\n");
726 err
= PyTraceBack_Print(tb
, f
);
728 PyErr_GivenExceptionMatches(exception
, PyExc_SyntaxError
))
731 char *filename
, *text
;
733 if (!parse_syntax_error(v
, &message
, &filename
,
734 &lineno
, &offset
, &text
))
738 PyFile_WriteString(" File \"", f
);
739 if (filename
== NULL
)
740 PyFile_WriteString("<string>", f
);
742 PyFile_WriteString(filename
, f
);
743 PyFile_WriteString("\", line ", f
);
744 sprintf(buf
, "%d", lineno
);
745 PyFile_WriteString(buf
, f
);
746 PyFile_WriteString("\n", f
);
750 offset
== (int)strlen(text
))
753 nl
= strchr(text
, '\n');
757 offset
-= (nl
+1-text
);
760 while (*text
== ' ' || *text
== '\t') {
764 PyFile_WriteString(" ", f
);
765 PyFile_WriteString(text
, f
);
767 text
[strlen(text
)-1] != '\n')
768 PyFile_WriteString("\n", f
);
769 PyFile_WriteString(" ", f
);
772 PyFile_WriteString(" ", f
);
775 PyFile_WriteString("^\n", f
);
780 /* Can't be bothered to check all those
781 PyFile_WriteString() calls */
782 if (PyErr_Occurred())
787 /* Don't do anything else */
789 else if (PyClass_Check(exception
)) {
790 PyClassObject
* exc
= (PyClassObject
*)exception
;
791 PyObject
* className
= exc
->cl_name
;
792 PyObject
* moduleName
=
793 PyDict_GetItemString(exc
->cl_dict
, "__module__");
795 if (moduleName
== NULL
)
796 err
= PyFile_WriteString("<unknown>", f
);
798 char* modstr
= PyString_AsString(moduleName
);
799 if (modstr
&& strcmp(modstr
, "exceptions"))
801 err
= PyFile_WriteString(modstr
, f
);
802 err
+= PyFile_WriteString(".", f
);
806 if (className
== NULL
)
807 err
= PyFile_WriteString("<unknown>", f
);
809 err
= PyFile_WriteObject(className
, f
,
814 err
= PyFile_WriteObject(exception
, f
, Py_PRINT_RAW
);
816 if (v
!= NULL
&& v
!= Py_None
) {
817 PyObject
*s
= PyObject_Str(v
);
818 /* only print colon if the str() of the
819 object is not the empty string
823 else if (!PyString_Check(s
) ||
824 PyString_GET_SIZE(s
) != 0)
825 err
= PyFile_WriteString(": ", f
);
827 err
= PyFile_WriteObject(s
, f
, Py_PRINT_RAW
);
832 err
= PyFile_WriteString("\n", f
);
834 Py_XDECREF(exception
);
837 /* If an error happened here, don't show it.
838 XXX This is wrong, but too many callers rely on this behavior. */
844 PyRun_String(str
, start
, globals
, locals
)
847 PyObject
*globals
, *locals
;
849 return run_err_node(PyParser_SimpleParseString(str
, start
),
850 "<string>", globals
, locals
);
854 PyRun_File(fp
, filename
, start
, globals
, locals
)
858 PyObject
*globals
, *locals
;
860 return run_err_node(PyParser_SimpleParseFile(fp
, filename
, start
),
861 filename
, globals
, locals
);
865 run_err_node(n
, filename
, globals
, locals
)
868 PyObject
*globals
, *locals
;
872 return run_node(n
, filename
, globals
, locals
);
876 run_node(n
, filename
, globals
, locals
)
879 PyObject
*globals
, *locals
;
883 co
= PyNode_Compile(n
, filename
);
887 v
= PyEval_EvalCode(co
, globals
, locals
);
893 run_pyc_file(fp
, filename
, globals
, locals
)
896 PyObject
*globals
, *locals
;
901 long PyImport_GetMagicNumber();
903 magic
= PyMarshal_ReadLongFromFile(fp
);
904 if (magic
!= PyImport_GetMagicNumber()) {
905 PyErr_SetString(PyExc_RuntimeError
,
906 "Bad magic number in .pyc file");
909 (void) PyMarshal_ReadLongFromFile(fp
);
910 v
= PyMarshal_ReadObjectFromFile(fp
);
912 if (v
== NULL
|| !PyCode_Check(v
)) {
914 PyErr_SetString(PyExc_RuntimeError
,
915 "Bad code object in .pyc file");
918 co
= (PyCodeObject
*)v
;
919 v
= PyEval_EvalCode(co
, globals
, locals
);
925 Py_CompileString(str
, filename
, start
)
932 n
= PyParser_SimpleParseString(str
, start
);
935 co
= PyNode_Compile(n
, filename
);
937 return (PyObject
*)co
;
940 /* Simplified interface to parsefile -- return node or set exception */
943 PyParser_SimpleParseFile(fp
, filename
, start
)
950 n
= PyParser_ParseFile(fp
, filename
, &_PyParser_Grammar
, start
,
951 (char *)0, (char *)0, &err
);
957 /* Simplified interface to parsestring -- return node or set exception */
960 PyParser_SimpleParseString(str
, start
)
966 n
= PyParser_ParseString(str
, &_PyParser_Grammar
, start
, &err
);
972 /* Set the error appropriate to the given input error code (see errcode.h) */
980 v
= Py_BuildValue("(ziiz)", err
->filename
,
981 err
->lineno
, err
->offset
, err
->text
);
982 if (err
->text
!= NULL
) {
986 switch (err
->error
) {
988 msg
= "invalid syntax";
991 msg
= "invalid token";
994 PyErr_SetNone(PyExc_KeyboardInterrupt
);
1002 msg
= "unexpected EOF while parsing";
1005 msg
= "inconsistent use of tabs and spaces in indentation";
1008 fprintf(stderr
, "error=%d\n", err
->error
);
1009 msg
= "unknown parsing error";
1012 w
= Py_BuildValue("(sO)", msg
, v
);
1014 PyErr_SetObject(PyExc_SyntaxError
, w
);
1018 /* Print fatal error message and abort */
1024 fprintf(stderr
, "Fatal Python error: %s\n", msg
);
1029 OutputDebugString("Fatal Python error: ");
1030 OutputDebugString(msg
);
1031 OutputDebugString("\n");
1035 #endif /* MS_WIN32 */
1039 /* Clean up and exit */
1042 #include "pythread.h"
1043 int _PyThread_Started
= 0; /* Set by threadmodule.c and maybe others */
1046 #define NEXITFUNCS 32
1047 static void (*exitfuncs
[NEXITFUNCS
])();
1048 static int nexitfuncs
= 0;
1051 void (*func
) Py_PROTO((void));
1053 if (nexitfuncs
>= NEXITFUNCS
)
1055 exitfuncs
[nexitfuncs
++] = func
;
1062 PyObject
*exitfunc
= PySys_GetObject("exitfunc");
1066 Py_INCREF(exitfunc
);
1067 PySys_SetObject("exitfunc", (PyObject
*)NULL
);
1068 f
= PySys_GetObject("stderr");
1069 res
= PyEval_CallObject(exitfunc
, (PyObject
*)NULL
);
1072 PyFile_WriteString("Error in sys.exitfunc:\n", f
);
1075 Py_DECREF(exitfunc
);
1085 while (nexitfuncs
> 0)
1086 (*exitfuncs
[--nexitfuncs
])();
1108 #ifdef HAVE_SIGNAL_H
1110 signal(SIGPIPE
, SIG_IGN
);
1112 #endif /* HAVE_SIGNAL_H */
1113 PyOS_InitInterrupts(); /* May imply initsignal() */
1116 #ifdef Py_TRACE_REFS
1117 /* Ask a yes/no question */
1120 _Py_AskYesNo(prompt
)
1125 printf("%s [ny] ", prompt
);
1126 if (fgets(buf
, sizeof buf
, stdin
) == NULL
)
1128 return buf
[0] == 'y' || buf
[0] == 'Y';
1134 /* Check for file descriptor connected to interactive device.
1135 Pretend that stdin is always interactive, other files never. */
1141 return fd
== fileno(stdin
);
1147 * The file descriptor fd is considered ``interactive'' if either
1148 * a) isatty(fd) is TRUE, or
1149 * b) the -i flag was given, and the filename associated with
1150 * the descriptor is NULL or "<stdin>" or "???".
1153 Py_FdIsInteractive(fp
, filename
)
1157 if (isatty((int)fileno(fp
)))
1159 if (!Py_InteractiveFlag
)
1161 return (filename
== NULL
) ||
1162 (strcmp(filename
, "<stdin>") == 0) ||
1163 (strcmp(filename
, "???") == 0);