Class around PixMap objects that allows more python-like access. By Joe Strout.
[python/dscho.git] / Python / pythonrun.c
blob0b5d0d17e82e084216eb77ca43c9fb17feb4b06a
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 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 */
86 int
87 Py_IsInitialized()
89 return initialized;
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
96 been created.
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.)
104 void
105 Py_Initialize()
107 PyInterpreterState *interp;
108 PyThreadState *tstate;
109 PyObject *bimod, *sysmod;
110 char *p;
112 if (initialized)
113 return;
114 initialized = 1;
116 if ((p = getenv("PYTHONDEBUG")) && *p != '\0')
117 Py_DebugFlag = 1;
118 if ((p = getenv("PYTHONVERBOSE")) && *p != '\0')
119 Py_VerboseFlag = 1;
120 if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0')
121 Py_OptimizeFlag = 1;
123 interp = PyInterpreterState_New();
124 if (interp == NULL)
125 Py_FatalError("Py_Initialize: can't make first interpreter");
127 tstate = PyThreadState_New(interp);
128 if (tstate == NULL)
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();
137 if (bimod == NULL)
138 Py_FatalError("Py_Initialize: can't initialize __builtin__");
139 interp->builtins = PyModule_GetDict(bimod);
140 Py_INCREF(interp->builtins);
142 sysmod = _PySys_Init();
143 if (sysmod == NULL)
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",
150 interp->modules);
152 /* phase 2 of builtins */
153 _PyBuiltin_Init_2(interp->builtins);
154 _PyImport_FixupExtension("__builtin__", "__builtin__");
156 _PyImport_Init();
158 initsigs(); /* Signal handling stuff, including initintr() */
160 initmain(); /* Module __main__ */
161 if (!Py_NoSiteFlag)
162 initsite(); /* Module site */
165 #ifdef COUNT_ALLOCS
166 extern void dump_counts Py_PROTO((void));
167 #endif
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
177 threads.)
179 Locking: as above.
183 void
184 Py_Finalize()
186 PyInterpreterState *interp;
187 PyThreadState *tstate;
189 if (!initialized)
190 return;
191 initialized = 0;
193 call_sys_exitfunc();
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 */
203 _PyBuiltin_Fini_1();
205 /* Destroy all modules */
206 PyImport_Cleanup();
208 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
209 _PyImport_Fini();
211 /* Debugging stuff */
212 #ifdef COUNT_ALLOCS
213 dump_counts();
214 #endif
216 #ifdef Py_REF_DEBUG
217 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
218 #endif
220 #ifdef Py_TRACE_REFS
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
234 raised.
236 _PyBuiltin_Fini_2();
237 PyMethod_Fini();
238 PyFrame_Fini();
239 PyCFunction_Fini();
240 PyTuple_Fini();
241 PyString_Fini();
242 PyInt_Fini();
243 PyFloat_Fini();
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);
253 call_ll_exitfuncs();
255 #ifdef Py_TRACE_REFS
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
262 first.
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
267 thread.
269 Locking: as above.
273 PyThreadState *
274 Py_NewInterpreter()
276 PyInterpreterState *interp;
277 PyThreadState *tstate, *save_tstate;
278 PyObject *bimod, *sysmod;
280 if (!initialized)
281 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
283 interp = PyInterpreterState_New();
284 if (interp == NULL)
285 return NULL;
287 tstate = PyThreadState_New(interp);
288 if (tstate == NULL) {
289 PyInterpreterState_Delete(interp);
290 return NULL;
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__");
300 if (bimod != NULL) {
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",
310 interp->modules);
311 initmain();
312 if (!Py_NoSiteFlag)
313 initsite();
316 if (!PyErr_Occurred())
317 return tstate;
319 /* Oops, it didn't work. Undo it all. */
321 PyErr_Print();
322 PyThreadState_Clear(tstate);
323 PyThreadState_Swap(save_tstate);
324 PyThreadState_Delete(tstate);
325 PyInterpreterState_Delete(interp);
327 return NULL;
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.)
338 Locking: as above.
342 void
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");
355 PyImport_Cleanup();
356 PyInterpreterState_Clear(interp);
357 PyThreadState_Swap(NULL);
358 PyInterpreterState_Delete(interp);
361 static char *progname = "python";
363 void
364 Py_SetProgramName(pn)
365 char *pn;
367 if (pn && *pn)
368 progname = pn;
371 char *
372 Py_GetProgramName()
374 return progname;
377 static char *default_home = NULL;
379 void
380 Py_SetPythonHome(home)
381 char *home;
383 default_home = home;
386 char *
387 Py_GetPythonHome()
389 char *home = default_home;
390 if (home == NULL)
391 home = getenv("PYTHONHOME");
392 return home;
395 /* Create __main__ module */
397 static void
398 initmain()
400 PyObject *m, *d;
401 m = PyImport_AddModule("__main__");
402 if (m == NULL)
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__");
407 if (bimod == NULL ||
408 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
409 Py_FatalError("can't add __builtins__ to __main__");
410 Py_DECREF(bimod);
414 /* Import the site module (not into __main__ though) */
416 static void
417 initsite()
419 PyObject *m, *f;
420 m = PyImport_ImportModule("site");
421 if (m == NULL) {
422 f = PySys_GetObject("stderr");
423 if (Py_VerboseFlag) {
424 PyFile_WriteString(
425 "'import site' failed; traceback:\n", f);
426 PyErr_Print();
428 else {
429 PyFile_WriteString(
430 "'import site' failed; use -v for traceback\n", f);
431 PyErr_Clear();
434 else {
435 Py_DECREF(m);
439 /* Parse input from a file and execute it */
442 PyRun_AnyFile(fp, filename)
443 FILE *fp;
444 char *filename;
446 if (filename == NULL)
447 filename = "???";
448 if (Py_FdIsInteractive(fp, filename))
449 return PyRun_InteractiveLoop(fp, filename);
450 else
451 return PyRun_SimpleFile(fp, filename);
455 PyRun_InteractiveLoop(fp, filename)
456 FILE *fp;
457 char *filename;
459 PyObject *v;
460 int ret;
461 v = PySys_GetObject("ps1");
462 if (v == NULL) {
463 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
464 Py_XDECREF(v);
466 v = PySys_GetObject("ps2");
467 if (v == NULL) {
468 PySys_SetObject("ps2", v = PyString_FromString("... "));
469 Py_XDECREF(v);
471 for (;;) {
472 ret = PyRun_InteractiveOne(fp, filename);
473 #ifdef Py_REF_DEBUG
474 fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
475 #endif
476 if (ret == E_EOF)
477 return 0;
479 if (ret == E_NOMEM)
480 return -1;
486 PyRun_InteractiveOne(fp, filename)
487 FILE *fp;
488 char *filename;
490 PyObject *m, *d, *v, *w;
491 node *n;
492 perrdetail err;
493 char *ps1 = "", *ps2 = "";
494 v = PySys_GetObject("ps1");
495 if (v != NULL) {
496 v = PyObject_Str(v);
497 if (v == NULL)
498 PyErr_Clear();
499 else if (PyString_Check(v))
500 ps1 = PyString_AsString(v);
502 w = PySys_GetObject("ps2");
503 if (w != NULL) {
504 w = PyObject_Str(w);
505 if (w == NULL)
506 PyErr_Clear();
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);
512 Py_XDECREF(v);
513 Py_XDECREF(w);
514 if (n == NULL) {
515 if (err.error == E_EOF) {
516 if (err.text)
517 free(err.text);
518 return E_EOF;
520 err_input(&err);
521 PyErr_Print();
522 return err.error;
524 m = PyImport_AddModule("__main__");
525 if (m == NULL)
526 return -1;
527 d = PyModule_GetDict(m);
528 v = run_node(n, filename, d, d);
529 if (v == NULL) {
530 PyErr_Print();
531 return -1;
533 Py_DECREF(v);
534 if (Py_FlushLine())
535 PyErr_Clear();
536 return 0;
540 PyRun_SimpleFile(fp, filename)
541 FILE *fp;
542 char *filename;
544 PyObject *m, *d, *v;
545 char *ext;
547 m = PyImport_AddModule("__main__");
548 if (m == NULL)
549 return -1;
550 d = PyModule_GetDict(m);
551 ext = filename + strlen(filename) - 4;
552 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0
553 #ifdef macintosh
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");
563 return -1;
565 /* Turn on optimization if a .pyo file is given */
566 if (strcmp(ext, ".pyo") == 0)
567 Py_OptimizeFlag = 1;
568 v = run_pyc_file(fp, filename, d, d);
569 } else {
570 v = PyRun_File(fp, filename, Py_file_input, d, d);
572 if (v == NULL) {
573 PyErr_Print();
574 return -1;
576 Py_DECREF(v);
577 if (Py_FlushLine())
578 PyErr_Clear();
579 return 0;
583 PyRun_SimpleString(command)
584 char *command;
586 PyObject *m, *d, *v;
587 m = PyImport_AddModule("__main__");
588 if (m == NULL)
589 return -1;
590 d = PyModule_GetDict(m);
591 v = PyRun_String(command, Py_file_input, d, d);
592 if (v == NULL) {
593 PyErr_Print();
594 return -1;
596 Py_DECREF(v);
597 if (Py_FlushLine())
598 PyErr_Clear();
599 return 0;
602 static int
603 parse_syntax_error(err, message, filename, lineno, offset, text)
604 PyObject* err;
605 PyObject** message;
606 char** filename;
607 int* lineno;
608 int* offset;
609 char** text;
611 long hold;
612 PyObject *v;
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")))
622 goto finally;
623 *message = v;
625 if (!(v = PyObject_GetAttrString(err, "filename")))
626 goto finally;
627 if (v == Py_None)
628 *filename = NULL;
629 else if (! (*filename = PyString_AsString(v)))
630 goto finally;
632 Py_DECREF(v);
633 if (!(v = PyObject_GetAttrString(err, "lineno")))
634 goto finally;
635 hold = PyInt_AsLong(v);
636 Py_DECREF(v);
637 v = NULL;
638 if (hold < 0 && PyErr_Occurred())
639 goto finally;
640 *lineno = (int)hold;
642 if (!(v = PyObject_GetAttrString(err, "offset")))
643 goto finally;
644 hold = PyInt_AsLong(v);
645 Py_DECREF(v);
646 v = NULL;
647 if (hold < 0 && PyErr_Occurred())
648 goto finally;
649 *offset = (int)hold;
651 if (!(v = PyObject_GetAttrString(err, "text")))
652 goto finally;
653 if (v == Py_None)
654 *text = NULL;
655 else if (! (*text = PyString_AsString(v)))
656 goto finally;
657 Py_DECREF(v);
658 return 1;
660 finally:
661 Py_XDECREF(v);
662 return 0;
665 void
666 PyErr_Print()
668 PyErr_PrintEx(1);
671 void
672 PyErr_PrintEx(set_sys_last_vars)
673 int set_sys_last_vars;
675 int err = 0;
676 PyObject *exception, *v, *tb, *f;
677 PyErr_Fetch(&exception, &v, &tb);
678 PyErr_NormalizeException(&exception, &v, &tb);
680 if (exception == NULL)
681 return;
683 if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
684 if (Py_FlushLine())
685 PyErr_Clear();
686 fflush(stdout);
687 if (v == NULL || v == Py_None)
688 Py_Exit(0);
689 if (PyInstance_Check(v)) {
690 /* we expect the error code to be store in the
691 `code' attribute
693 PyObject *code = PyObject_GetAttrString(v, "code");
694 if (code) {
695 Py_DECREF(v);
696 v = code;
697 if (v == Py_None)
698 Py_Exit(0);
700 /* if we failed to dig out the "code" attribute,
701 then just let the else clause below print the
702 error
705 if (PyInt_Check(v))
706 Py_Exit((int)PyInt_AsLong(v));
707 else {
708 /* OK to use real stderr here */
709 PyObject_Print(v, stderr, Py_PRINT_RAW);
710 fprintf(stderr, "\n");
711 Py_Exit(1);
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");
720 if (f == NULL)
721 fprintf(stderr, "lost sys.stderr\n");
722 else {
723 if (Py_FlushLine())
724 PyErr_Clear();
725 fflush(stdout);
726 err = PyTraceBack_Print(tb, f);
727 if (err == 0 &&
728 PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
730 PyObject *message;
731 char *filename, *text;
732 int lineno, offset;
733 if (!parse_syntax_error(v, &message, &filename,
734 &lineno, &offset, &text))
735 PyErr_Clear();
736 else {
737 char buf[10];
738 PyFile_WriteString(" File \"", f);
739 if (filename == NULL)
740 PyFile_WriteString("<string>", f);
741 else
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);
747 if (text != NULL) {
748 char *nl;
749 if (offset > 0 &&
750 offset == (int)strlen(text))
751 offset--;
752 for (;;) {
753 nl = strchr(text, '\n');
754 if (nl == NULL ||
755 nl-text >= offset)
756 break;
757 offset -= (nl+1-text);
758 text = nl+1;
760 while (*text == ' ' || *text == '\t') {
761 text++;
762 offset--;
764 PyFile_WriteString(" ", f);
765 PyFile_WriteString(text, f);
766 if (*text == '\0' ||
767 text[strlen(text)-1] != '\n')
768 PyFile_WriteString("\n", f);
769 PyFile_WriteString(" ", f);
770 offset--;
771 while (offset > 0) {
772 PyFile_WriteString(" ", f);
773 offset--;
775 PyFile_WriteString("^\n", f);
777 Py_INCREF(message);
778 Py_DECREF(v);
779 v = message;
780 /* Can't be bothered to check all those
781 PyFile_WriteString() calls */
782 if (PyErr_Occurred())
783 err = -1;
786 if (err) {
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);
797 else {
798 char* modstr = PyString_AsString(moduleName);
799 if (modstr && strcmp(modstr, "exceptions"))
801 err = PyFile_WriteString(modstr, f);
802 err += PyFile_WriteString(".", f);
805 if (err == 0) {
806 if (className == NULL)
807 err = PyFile_WriteString("<unknown>", f);
808 else
809 err = PyFile_WriteObject(className, f,
810 Py_PRINT_RAW);
813 else
814 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
815 if (err == 0) {
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
821 if (s == NULL)
822 err = -1;
823 else if (!PyString_Check(s) ||
824 PyString_GET_SIZE(s) != 0)
825 err = PyFile_WriteString(": ", f);
826 if (err == 0)
827 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
828 Py_XDECREF(s);
831 if (err == 0)
832 err = PyFile_WriteString("\n", f);
834 Py_XDECREF(exception);
835 Py_XDECREF(v);
836 Py_XDECREF(tb);
837 /* If an error happened here, don't show it.
838 XXX This is wrong, but too many callers rely on this behavior. */
839 if (err != 0)
840 PyErr_Clear();
843 PyObject *
844 PyRun_String(str, start, globals, locals)
845 char *str;
846 int start;
847 PyObject *globals, *locals;
849 return run_err_node(PyParser_SimpleParseString(str, start),
850 "<string>", globals, locals);
853 PyObject *
854 PyRun_File(fp, filename, start, globals, locals)
855 FILE *fp;
856 char *filename;
857 int start;
858 PyObject *globals, *locals;
860 return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
861 filename, globals, locals);
864 static PyObject *
865 run_err_node(n, filename, globals, locals)
866 node *n;
867 char *filename;
868 PyObject *globals, *locals;
870 if (n == NULL)
871 return NULL;
872 return run_node(n, filename, globals, locals);
875 static PyObject *
876 run_node(n, filename, globals, locals)
877 node *n;
878 char *filename;
879 PyObject *globals, *locals;
881 PyCodeObject *co;
882 PyObject *v;
883 co = PyNode_Compile(n, filename);
884 PyNode_Free(n);
885 if (co == NULL)
886 return NULL;
887 v = PyEval_EvalCode(co, globals, locals);
888 Py_DECREF(co);
889 return v;
892 static PyObject *
893 run_pyc_file(fp, filename, globals, locals)
894 FILE *fp;
895 char *filename;
896 PyObject *globals, *locals;
898 PyCodeObject *co;
899 PyObject *v;
900 long magic;
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");
907 return NULL;
909 (void) PyMarshal_ReadLongFromFile(fp);
910 v = PyMarshal_ReadObjectFromFile(fp);
911 fclose(fp);
912 if (v == NULL || !PyCode_Check(v)) {
913 Py_XDECREF(v);
914 PyErr_SetString(PyExc_RuntimeError,
915 "Bad code object in .pyc file");
916 return NULL;
918 co = (PyCodeObject *)v;
919 v = PyEval_EvalCode(co, globals, locals);
920 Py_DECREF(co);
921 return v;
924 PyObject *
925 Py_CompileString(str, filename, start)
926 char *str;
927 char *filename;
928 int start;
930 node *n;
931 PyCodeObject *co;
932 n = PyParser_SimpleParseString(str, start);
933 if (n == NULL)
934 return NULL;
935 co = PyNode_Compile(n, filename);
936 PyNode_Free(n);
937 return (PyObject *)co;
940 /* Simplified interface to parsefile -- return node or set exception */
942 node *
943 PyParser_SimpleParseFile(fp, filename, start)
944 FILE *fp;
945 char *filename;
946 int start;
948 node *n;
949 perrdetail err;
950 n = PyParser_ParseFile(fp, filename, &_PyParser_Grammar, start,
951 (char *)0, (char *)0, &err);
952 if (n == NULL)
953 err_input(&err);
954 return n;
957 /* Simplified interface to parsestring -- return node or set exception */
959 node *
960 PyParser_SimpleParseString(str, start)
961 char *str;
962 int start;
964 node *n;
965 perrdetail err;
966 n = PyParser_ParseString(str, &_PyParser_Grammar, start, &err);
967 if (n == NULL)
968 err_input(&err);
969 return n;
972 /* Set the error appropriate to the given input error code (see errcode.h) */
974 static void
975 err_input(err)
976 perrdetail *err;
978 PyObject *v, *w;
979 char *msg = NULL;
980 v = Py_BuildValue("(ziiz)", err->filename,
981 err->lineno, err->offset, err->text);
982 if (err->text != NULL) {
983 free(err->text);
984 err->text = NULL;
986 switch (err->error) {
987 case E_SYNTAX:
988 msg = "invalid syntax";
989 break;
990 case E_TOKEN:
991 msg = "invalid token";
992 break;
993 case E_INTR:
994 PyErr_SetNone(PyExc_KeyboardInterrupt);
995 Py_XDECREF(v);
996 return;
997 case E_NOMEM:
998 PyErr_NoMemory();
999 Py_XDECREF(v);
1000 return;
1001 case E_EOF:
1002 msg = "unexpected EOF while parsing";
1003 break;
1004 case E_INDENT:
1005 msg = "inconsistent use of tabs and spaces in indentation";
1006 break;
1007 default:
1008 fprintf(stderr, "error=%d\n", err->error);
1009 msg = "unknown parsing error";
1010 break;
1012 w = Py_BuildValue("(sO)", msg, v);
1013 Py_XDECREF(v);
1014 PyErr_SetObject(PyExc_SyntaxError, w);
1015 Py_XDECREF(w);
1018 /* Print fatal error message and abort */
1020 void
1021 Py_FatalError(msg)
1022 char *msg;
1024 fprintf(stderr, "Fatal Python error: %s\n", msg);
1025 #ifdef macintosh
1026 for (;;);
1027 #endif
1028 #ifdef MS_WIN32
1029 OutputDebugString("Fatal Python error: ");
1030 OutputDebugString(msg);
1031 OutputDebugString("\n");
1032 #ifdef _DEBUG
1033 DebugBreak();
1034 #endif
1035 #endif /* MS_WIN32 */
1036 abort();
1039 /* Clean up and exit */
1041 #ifdef WITH_THREAD
1042 #include "pythread.h"
1043 int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
1044 #endif
1046 #define NEXITFUNCS 32
1047 static void (*exitfuncs[NEXITFUNCS])();
1048 static int nexitfuncs = 0;
1050 int Py_AtExit(func)
1051 void (*func) Py_PROTO((void));
1053 if (nexitfuncs >= NEXITFUNCS)
1054 return -1;
1055 exitfuncs[nexitfuncs++] = func;
1056 return 0;
1059 static void
1060 call_sys_exitfunc()
1062 PyObject *exitfunc = PySys_GetObject("exitfunc");
1064 if (exitfunc) {
1065 PyObject *res, *f;
1066 Py_INCREF(exitfunc);
1067 PySys_SetObject("exitfunc", (PyObject *)NULL);
1068 f = PySys_GetObject("stderr");
1069 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1070 if (res == NULL) {
1071 if (f)
1072 PyFile_WriteString("Error in sys.exitfunc:\n", f);
1073 PyErr_Print();
1075 Py_DECREF(exitfunc);
1078 if (Py_FlushLine())
1079 PyErr_Clear();
1082 static void
1083 call_ll_exitfuncs()
1085 while (nexitfuncs > 0)
1086 (*exitfuncs[--nexitfuncs])();
1088 fflush(stdout);
1089 fflush(stderr);
1092 void
1093 Py_Exit(sts)
1094 int sts;
1096 Py_Finalize();
1098 #ifdef macintosh
1099 PyMac_Exit(sts);
1100 #else
1101 exit(sts);
1102 #endif
1105 static void
1106 initsigs()
1108 #ifdef HAVE_SIGNAL_H
1109 #ifdef SIGPIPE
1110 signal(SIGPIPE, SIG_IGN);
1111 #endif
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)
1121 char *prompt;
1123 char buf[256];
1125 printf("%s [ny] ", prompt);
1126 if (fgets(buf, sizeof buf, stdin) == NULL)
1127 return 0;
1128 return buf[0] == 'y' || buf[0] == 'Y';
1130 #endif
1132 #ifdef MPW
1134 /* Check for file descriptor connected to interactive device.
1135 Pretend that stdin is always interactive, other files never. */
1138 isatty(fd)
1139 int fd;
1141 return fd == fileno(stdin);
1144 #endif
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)
1154 FILE *fp;
1155 char *filename;
1157 if (isatty((int)fileno(fp)))
1158 return 1;
1159 if (!Py_InteractiveFlag)
1160 return 0;
1161 return (filename == NULL) ||
1162 (strcmp(filename, "<stdin>") == 0) ||
1163 (strcmp(filename, "???") == 0);