The 0.5 release happened on 2/15, not on 2/14. :-)
[python/dscho.git] / Python / pythonrun.c
blob0814038ee20e9a3ab927731c252340cb6d013485
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
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
15 permission.
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 */
34 #include "Python.h"
36 #include "grammar.h"
37 #include "node.h"
38 #include "parsetok.h"
39 #include "errcode.h"
40 #include "compile.h"
41 #include "eval.h"
42 #include "marshal.h"
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
48 #ifdef HAVE_SIGNAL_H
49 #include <signal.h>
50 #endif
52 #ifdef MS_WIN32
53 #undef BYTE
54 #include "windows.h"
55 #endif
57 extern char *Py_GetPath();
59 extern grammar _PyParser_Grammar; /* From graminit.c */
61 /* Forward */
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 #ifdef Py_TRACE_REFS
76 int _Py_AskYesNo(char *prompt);
77 #endif
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 */
90 int
91 Py_IsInitialized()
93 return initialized;
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
100 been created.
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.)
108 void
109 Py_Initialize()
111 PyInterpreterState *interp;
112 PyThreadState *tstate;
113 PyObject *bimod, *sysmod;
114 char *p;
116 if (initialized)
117 return;
118 initialized = 1;
120 if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
121 Py_DebugFlag = 1;
122 if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
123 Py_VerboseFlag = 1;
124 if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
125 Py_OptimizeFlag = 1;
127 interp = PyInterpreterState_New();
128 if (interp == NULL)
129 Py_FatalError("Py_Initialize: can't make first interpreter");
131 tstate = PyThreadState_New(interp);
132 if (tstate == NULL)
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();
141 if (bimod == NULL)
142 Py_FatalError("Py_Initialize: can't initialize __builtin__");
143 interp->builtins = PyModule_GetDict(bimod);
144 Py_INCREF(interp->builtins);
146 sysmod = _PySys_Init();
147 if (sysmod == NULL)
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",
154 interp->modules);
156 _PyImport_Init();
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__ */
165 if (!Py_NoSiteFlag)
166 initsite(); /* Module site */
169 #ifdef COUNT_ALLOCS
170 extern void dump_counts Py_PROTO((void));
171 #endif
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
181 threads.)
183 Locking: as above.
187 void
188 Py_Finalize()
190 PyInterpreterState *interp;
191 PyThreadState *tstate;
193 if (!initialized)
194 return;
195 initialized = 0;
197 call_sys_exitfunc();
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 */
207 _PyBuiltin_Fini_1();
209 /* Destroy all modules */
210 PyImport_Cleanup();
212 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
213 _PyImport_Fini();
215 /* Debugging stuff */
216 #ifdef COUNT_ALLOCS
217 dump_counts();
218 #endif
220 #ifdef Py_REF_DEBUG
221 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
222 #endif
224 #ifdef Py_TRACE_REFS
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
238 raised.
240 _PyBuiltin_Fini_2();
241 PyMethod_Fini();
242 PyFrame_Fini();
243 PyCFunction_Fini();
244 PyTuple_Fini();
245 PyString_Fini();
246 PyInt_Fini();
247 PyFloat_Fini();
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);
257 call_ll_exitfuncs();
259 #ifdef Py_TRACE_REFS
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
266 first.
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
271 thread.
273 Locking: as above.
277 PyThreadState *
278 Py_NewInterpreter()
280 PyInterpreterState *interp;
281 PyThreadState *tstate, *save_tstate;
282 PyObject *bimod, *sysmod;
284 if (!initialized)
285 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
287 interp = PyInterpreterState_New();
288 if (interp == NULL)
289 return NULL;
291 tstate = PyThreadState_New(interp);
292 if (tstate == NULL) {
293 PyInterpreterState_Delete(interp);
294 return NULL;
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__");
304 if (bimod != NULL) {
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",
314 interp->modules);
315 initmain();
316 if (!Py_NoSiteFlag)
317 initsite();
320 if (!PyErr_Occurred())
321 return tstate;
323 /* Oops, it didn't work. Undo it all. */
325 PyErr_Print();
326 PyThreadState_Clear(tstate);
327 PyThreadState_Swap(save_tstate);
328 PyThreadState_Delete(tstate);
329 PyInterpreterState_Delete(interp);
331 return NULL;
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.)
342 Locking: as above.
346 void
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");
359 PyImport_Cleanup();
360 PyInterpreterState_Clear(interp);
361 PyThreadState_Swap(NULL);
362 PyInterpreterState_Delete(interp);
365 static char *progname = "python";
367 void
368 Py_SetProgramName(pn)
369 char *pn;
371 if (pn && *pn)
372 progname = pn;
375 char *
376 Py_GetProgramName()
378 return progname;
381 static char *default_home = NULL;
383 void
384 Py_SetPythonHome(home)
385 char *home;
387 default_home = home;
390 char *
391 Py_GetPythonHome()
393 char *home = default_home;
394 if (home == NULL)
395 home = getenv("PYTHONHOME");
396 return home;
399 /* Create __main__ module */
401 static void
402 initmain()
404 PyObject *m, *d;
405 m = PyImport_AddModule("__main__");
406 if (m == NULL)
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__");
411 if (bimod == NULL ||
412 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
413 Py_FatalError("can't add __builtins__ to __main__");
414 Py_DECREF(bimod);
418 /* Import the site module (not into __main__ though) */
420 static void
421 initsite()
423 PyObject *m, *f;
424 m = PyImport_ImportModule("site");
425 if (m == NULL) {
426 f = PySys_GetObject("stderr");
427 if (Py_VerboseFlag) {
428 PyFile_WriteString(
429 "'import site' failed; traceback:\n", f);
430 PyErr_Print();
432 else {
433 PyFile_WriteString(
434 "'import site' failed; use -v for traceback\n", f);
435 PyErr_Clear();
438 else {
439 Py_DECREF(m);
443 /* Parse input from a file and execute it */
446 PyRun_AnyFile(fp, filename)
447 FILE *fp;
448 char *filename;
450 if (filename == NULL)
451 filename = "???";
452 if (Py_FdIsInteractive(fp, filename))
453 return PyRun_InteractiveLoop(fp, filename);
454 else
455 return PyRun_SimpleFile(fp, filename);
459 PyRun_InteractiveLoop(fp, filename)
460 FILE *fp;
461 char *filename;
463 PyObject *v;
464 int ret;
465 v = PySys_GetObject("ps1");
466 if (v == NULL) {
467 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
468 Py_XDECREF(v);
470 v = PySys_GetObject("ps2");
471 if (v == NULL) {
472 PySys_SetObject("ps2", v = PyString_FromString("... "));
473 Py_XDECREF(v);
475 for (;;) {
476 ret = PyRun_InteractiveOne(fp, filename);
477 #ifdef Py_REF_DEBUG
478 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
479 #endif
480 if (ret == E_EOF)
481 return 0;
483 if (ret == E_NOMEM)
484 return -1;
490 PyRun_InteractiveOne(fp, filename)
491 FILE *fp;
492 char *filename;
494 PyObject *m, *d, *v, *w;
495 node *n;
496 perrdetail err;
497 char *ps1 = "", *ps2 = "";
498 v = PySys_GetObject("ps1");
499 if (v != NULL) {
500 v = PyObject_Str(v);
501 if (v == NULL)
502 PyErr_Clear();
503 else if (PyString_Check(v))
504 ps1 = PyString_AsString(v);
506 w = PySys_GetObject("ps2");
507 if (w != NULL) {
508 w = PyObject_Str(w);
509 if (w == NULL)
510 PyErr_Clear();
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);
516 Py_XDECREF(v);
517 Py_XDECREF(w);
518 if (n == NULL) {
519 if (err.error == E_EOF) {
520 if (err.text)
521 free(err.text);
522 return E_EOF;
524 err_input(&err);
525 PyErr_Print();
526 return err.error;
528 m = PyImport_AddModule("__main__");
529 if (m == NULL)
530 return -1;
531 d = PyModule_GetDict(m);
532 v = run_node(n, filename, d, d);
533 if (v == NULL) {
534 PyErr_Print();
535 return -1;
537 Py_DECREF(v);
538 if (Py_FlushLine())
539 PyErr_Clear();
540 return 0;
544 PyRun_SimpleFile(fp, filename)
545 FILE *fp;
546 char *filename;
548 PyObject *m, *d, *v;
549 char *ext;
551 m = PyImport_AddModule("__main__");
552 if (m == NULL)
553 return -1;
554 d = PyModule_GetDict(m);
555 ext = filename + strlen(filename) - 4;
556 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
557 #ifdef macintosh
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");
567 return -1;
569 /* Turn on optimization if a .pyo file is given */
570 if (strcmp(ext, ".pyo") == 0)
571 Py_OptimizeFlag = 1;
572 v = run_pyc_file(fp, filename, d, d);
573 } else {
574 v = PyRun_File(fp, filename, Py_file_input, d, d);
576 if (v == NULL) {
577 PyErr_Print();
578 return -1;
580 Py_DECREF(v);
581 if (Py_FlushLine())
582 PyErr_Clear();
583 return 0;
587 PyRun_SimpleString(command)
588 char *command;
590 PyObject *m, *d, *v;
591 m = PyImport_AddModule("__main__");
592 if (m == NULL)
593 return -1;
594 d = PyModule_GetDict(m);
595 v = PyRun_String(command, Py_file_input, d, d);
596 if (v == NULL) {
597 PyErr_Print();
598 return -1;
600 Py_DECREF(v);
601 if (Py_FlushLine())
602 PyErr_Clear();
603 return 0;
606 static int
607 parse_syntax_error(err, message, filename, lineno, offset, text)
608 PyObject* err;
609 PyObject** message;
610 char** filename;
611 int* lineno;
612 int* offset;
613 char** text;
615 long hold;
616 PyObject *v;
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")))
626 goto finally;
627 *message = v;
629 if (!(v = PyObject_GetAttrString(err, "filename")))
630 goto finally;
631 if (v == Py_None)
632 *filename = NULL;
633 else if (! (*filename = PyString_AsString(v)))
634 goto finally;
636 Py_DECREF(v);
637 if (!(v = PyObject_GetAttrString(err, "lineno")))
638 goto finally;
639 hold = PyInt_AsLong(v);
640 Py_DECREF(v);
641 v = NULL;
642 if (hold < 0 && PyErr_Occurred())
643 goto finally;
644 *lineno = (int)hold;
646 if (!(v = PyObject_GetAttrString(err, "offset")))
647 goto finally;
648 hold = PyInt_AsLong(v);
649 Py_DECREF(v);
650 v = NULL;
651 if (hold < 0 && PyErr_Occurred())
652 goto finally;
653 *offset = (int)hold;
655 if (!(v = PyObject_GetAttrString(err, "text")))
656 goto finally;
657 if (v == Py_None)
658 *text = NULL;
659 else if (! (*text = PyString_AsString(v)))
660 goto finally;
661 Py_DECREF(v);
662 return 1;
664 finally:
665 Py_XDECREF(v);
666 return 0;
669 void
670 PyErr_Print()
672 PyErr_PrintEx(1);
675 void
676 PyErr_PrintEx(set_sys_last_vars)
677 int set_sys_last_vars;
679 int err = 0;
680 PyObject *exception, *v, *tb, *f;
681 PyErr_Fetch(&exception, &v, &tb);
682 PyErr_NormalizeException(&exception, &v, &tb);
684 if (exception == NULL)
685 return;
687 if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
688 if (Py_FlushLine())
689 PyErr_Clear();
690 fflush(stdout);
691 if (v == NULL || v == Py_None)
692 Py_Exit(0);
693 if (PyInstance_Check(v)) {
694 /* we expect the error code to be store in the
695 `code' attribute
697 PyObject *code = PyObject_GetAttrString(v, "code");
698 if (code) {
699 Py_DECREF(v);
700 v = code;
701 if (v == Py_None)
702 Py_Exit(0);
704 /* if we failed to dig out the "code" attribute,
705 then just let the else clause below print the
706 error
709 if (PyInt_Check(v))
710 Py_Exit((int)PyInt_AsLong(v));
711 else {
712 /* OK to use real stderr here */
713 PyObject_Print(v, stderr, Py_PRINT_RAW);
714 fprintf(stderr, "\n");
715 Py_Exit(1);
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");
724 if (f == NULL)
725 fprintf(stderr, "lost sys.stderr\n");
726 else {
727 if (Py_FlushLine())
728 PyErr_Clear();
729 fflush(stdout);
730 err = PyTraceBack_Print(tb, f);
731 if (err == 0 &&
732 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
734 PyObject *message;
735 char *filename, *text;
736 int lineno, offset;
737 if (!parse_syntax_error(v, &message, &filename,
738 &lineno, &offset, &text))
739 PyErr_Clear();
740 else {
741 char buf[10];
742 PyFile_WriteString(" File \"", f);
743 if (filename == NULL)
744 PyFile_WriteString("<string>", f);
745 else
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);
751 if (text != NULL) {
752 char *nl;
753 if (offset > 0 &&
754 offset == (int)strlen(text))
755 offset--;
756 for (;;) {
757 nl = strchr(text, '\n');
758 if (nl == NULL ||
759 nl-text >= offset)
760 break;
761 offset -= (nl+1-text);
762 text = nl+1;
764 while (*text == ' ' || *text == '\t') {
765 text++;
766 offset--;
768 PyFile_WriteString(" ", f);
769 PyFile_WriteString(text, f);
770 if (*text == '\0' ||
771 text[strlen(text)-1] != '\n')
772 PyFile_WriteString("\n", f);
773 PyFile_WriteString(" ", f);
774 offset--;
775 while (offset > 0) {
776 PyFile_WriteString(" ", f);
777 offset--;
779 PyFile_WriteString("^\n", f);
781 Py_INCREF(message);
782 Py_DECREF(v);
783 v = message;
784 /* Can't be bothered to check all those
785 PyFile_WriteString() calls */
786 if (PyErr_Occurred())
787 err = -1;
790 if (err) {
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);
801 else {
802 char* modstr = PyString_AsString(moduleName);
803 if (modstr && strcmp(modstr, "exceptions"))
805 err = PyFile_WriteString(modstr, f);
806 err += PyFile_WriteString(".", f);
809 if (err == 0) {
810 if (className == NULL)
811 err = PyFile_WriteString("<unknown>", f);
812 else
813 err = PyFile_WriteObject(className, f,
814 Py_PRINT_RAW);
817 else
818 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
819 if (err == 0) {
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
825 if (s == NULL)
826 err = -1;
827 else if (!PyString_Check(s) ||
828 PyString_GET_SIZE(s) != 0)
829 err = PyFile_WriteString(": ", f);
830 if (err == 0)
831 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
832 Py_XDECREF(s);
835 if (err == 0)
836 err = PyFile_WriteString("\n", f);
838 Py_XDECREF(exception);
839 Py_XDECREF(v);
840 Py_XDECREF(tb);
841 /* If an error happened here, don't show it.
842 XXX This is wrong, but too many callers rely on this behavior. */
843 if (err != 0)
844 PyErr_Clear();
847 PyObject *
848 PyRun_String(str, start, globals, locals)
849 char *str;
850 int start;
851 PyObject *globals, *locals;
853 return run_err_node(PyParser_SimpleParseString(str, start),
854 "<string>", globals, locals);
857 PyObject *
858 PyRun_File(fp, filename, start, globals, locals)
859 FILE *fp;
860 char *filename;
861 int start;
862 PyObject *globals, *locals;
864 return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
865 filename, globals, locals);
868 static PyObject *
869 run_err_node(n, filename, globals, locals)
870 node *n;
871 char *filename;
872 PyObject *globals, *locals;
874 if (n == NULL)
875 return NULL;
876 return run_node(n, filename, globals, locals);
879 static PyObject *
880 run_node(n, filename, globals, locals)
881 node *n;
882 char *filename;
883 PyObject *globals, *locals;
885 PyCodeObject *co;
886 PyObject *v;
887 co = PyNode_Compile(n, filename);
888 PyNode_Free(n);
889 if (co == NULL)
890 return NULL;
891 v = PyEval_EvalCode(co, globals, locals);
892 Py_DECREF(co);
893 return v;
896 static PyObject *
897 run_pyc_file(fp, filename, globals, locals)
898 FILE *fp;
899 char *filename;
900 PyObject *globals, *locals;
902 PyCodeObject *co;
903 PyObject *v;
904 long magic;
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");
911 return NULL;
913 (void) PyMarshal_ReadLongFromFile(fp);
914 v = PyMarshal_ReadObjectFromFile(fp);
915 fclose(fp);
916 if (v == NULL || !PyCode_Check(v)) {
917 Py_XDECREF(v);
918 PyErr_SetString(PyExc_RuntimeError,
919 "Bad code object in .pyc file");
920 return NULL;
922 co = (PyCodeObject *)v;
923 v = PyEval_EvalCode(co, globals, locals);
924 Py_DECREF(co);
925 return v;
928 PyObject *
929 Py_CompileString(str, filename, start)
930 char *str;
931 char *filename;
932 int start;
934 node *n;
935 PyCodeObject *co;
936 n = PyParser_SimpleParseString(str, start);
937 if (n == NULL)
938 return NULL;
939 co = PyNode_Compile(n, filename);
940 PyNode_Free(n);
941 return (PyObject *)co;
944 /* Simplified interface to parsefile -- return node or set exception */
946 node *
947 PyParser_SimpleParseFile(fp, filename, start)
948 FILE *fp;
949 char *filename;
950 int start;
952 node *n;
953 perrdetail err;
954 n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
955 (char *)0, (char *)0, &err);
956 if (n == NULL)
957 err_input(&err);
958 return n;
961 /* Simplified interface to parsestring -- return node or set exception */
963 node *
964 PyParser_SimpleParseString(str, start)
965 char *str;
966 int start;
968 node *n;
969 perrdetail err;
970 n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
971 if (n == NULL)
972 err_input(&err);
973 return n;
976 /* Set the error appropriate to the given input error code (see errcode.h) */
978 static void
979 err_input(err)
980 perrdetail *err;
982 PyObject *v, *w;
983 char *msg = NULL;
984 v = Py_BuildValue("(ziiz)", err->filename,
985 err->lineno, err->offset, err->text);
986 if (err->text != NULL) {
987 free(err->text);
988 err->text = NULL;
990 switch (err->error) {
991 case E_SYNTAX:
992 msg = "invalid syntax";
993 break;
994 case E_TOKEN:
995 msg = "invalid token";
996 break;
997 case E_INTR:
998 PyErr_SetNone(PyExc_KeyboardInterrupt);
999 Py_XDECREF(v);
1000 return;
1001 case E_NOMEM:
1002 PyErr_NoMemory();
1003 Py_XDECREF(v);
1004 return;
1005 case E_EOF:
1006 msg = "unexpected EOF while parsing";
1007 break;
1008 case E_INDENT:
1009 msg = "inconsistent use of tabs and spaces in indentation";
1010 break;
1011 default:
1012 fprintf(stderr, "error=%d\n", err->error);
1013 msg = "unknown parsing error";
1014 break;
1016 w = Py_BuildValue("(sO)", msg, v);
1017 Py_XDECREF(v);
1018 PyErr_SetObject(PyExc_SyntaxError, w);
1019 Py_XDECREF(w);
1022 /* Print fatal error message and abort */
1024 void
1025 Py_FatalError(msg)
1026 char *msg;
1028 fprintf(stderr, "Fatal Python error: %s\n", msg);
1029 #ifdef macintosh
1030 for (;;);
1031 #endif
1032 #ifdef MS_WIN32
1033 OutputDebugString("Fatal Python error: ");
1034 OutputDebugString(msg);
1035 OutputDebugString("\n");
1036 #ifdef _DEBUG
1037 DebugBreak();
1038 #endif
1039 #endif /* MS_WIN32 */
1040 abort();
1043 /* Clean up and exit */
1045 #ifdef WITH_THREAD
1046 #include "pythread.h"
1047 int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
1048 #endif
1050 #define NEXITFUNCS 32
1051 static void (*exitfuncs[NEXITFUNCS])();
1052 static int nexitfuncs = 0;
1054 int Py_AtExit(func)
1055 void (*func) Py_PROTO((void));
1057 if (nexitfuncs >= NEXITFUNCS)
1058 return -1;
1059 exitfuncs[nexitfuncs++] = func;
1060 return 0;
1063 static void
1064 call_sys_exitfunc()
1066 PyObject *exitfunc = PySys_GetObject("exitfunc");
1068 if (exitfunc) {
1069 PyObject *res, *f;
1070 Py_INCREF(exitfunc);
1071 PySys_SetObject("exitfunc", (PyObject *)NULL);
1072 f = PySys_GetObject("stderr");
1073 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1074 if (res == NULL) {
1075 if (f)
1076 PyFile_WriteString("Error in sys.exitfunc:\n", f);
1077 PyErr_Print();
1079 Py_DECREF(exitfunc);
1082 if (Py_FlushLine())
1083 PyErr_Clear();
1086 static void
1087 call_ll_exitfuncs()
1089 while (nexitfuncs > 0)
1090 (*exitfuncs[--nexitfuncs])();
1092 fflush(stdout);
1093 fflush(stderr);
1096 void
1097 Py_Exit(sts)
1098 int sts;
1100 Py_Finalize();
1102 #ifdef macintosh
1103 PyMac_Exit(sts);
1104 #else
1105 exit(sts);
1106 #endif
1109 static void
1110 initsigs()
1112 #ifdef HAVE_SIGNAL_H
1113 #ifdef SIGPIPE
1114 signal(SIGPIPE, SIG_IGN);
1115 #endif
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)
1125 char *prompt;
1127 char buf[256];
1129 printf("%s [ny] ", prompt);
1130 if (fgets(buf, sizeof buf, stdin) == NULL)
1131 return 0;
1132 return buf[0] == 'y' || buf[0] == 'Y';
1134 #endif
1136 #ifdef MPW
1138 /* Check for file descriptor connected to interactive device.
1139 Pretend that stdin is always interactive, other files never. */
1142 isatty(fd)
1143 int fd;
1145 return fd == fileno(stdin);
1148 #endif
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)
1158 FILE *fp;
1159 char *filename;
1161 if (isatty((int)fileno(fp)))
1162 return 1;
1163 if (!Py_InteractiveFlag)
1164 return 0;
1165 return (filename == NULL) ||
1166 (strcmp(filename, "<stdin>") == 0) ||
1167 (strcmp(filename, "???") == 0);