home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / py2s152.zip / Python / pythonrun.c < prev    next >
C/C++ Source or Header  |  1999-06-27  |  27KB  |  1,165 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  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.
  16.  
  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.
  20.  
  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.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Python interpreter top-level routines, including init/exit */
  33.  
  34. #include "Python.h"
  35.  
  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"
  43.  
  44. #ifdef HAVE_UNISTD_H
  45. #include <unistd.h>
  46. #endif
  47.  
  48. #ifdef HAVE_SIGNAL_H
  49. #include <signal.h>
  50. #endif
  51.  
  52. #ifdef MS_WIN32
  53. #undef BYTE
  54. #include "windows.h"
  55. #endif
  56.  
  57. extern char *Py_GetPath();
  58.  
  59. extern grammar _PyParser_Grammar; /* From graminit.c */
  60.  
  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));
  74.  
  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 */
  81.  
  82. static int initialized = 0;
  83.  
  84. /* API to access the initialized flag -- useful for eroteric use */
  85.  
  86. int
  87. Py_IsInitialized()
  88. {
  89.     return initialized;
  90. }
  91.  
  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.
  97.  
  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.)
  101.  
  102. */
  103.  
  104. void
  105. Py_Initialize()
  106. {
  107.     PyInterpreterState *interp;
  108.     PyThreadState *tstate;
  109.     PyObject *bimod, *sysmod;
  110.     char *p;
  111.  
  112.     if (initialized)
  113.         return;
  114.     initialized = 1;
  115.     
  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;
  122.  
  123.     interp = PyInterpreterState_New();
  124.     if (interp == NULL)
  125.         Py_FatalError("Py_Initialize: can't make first interpreter");
  126.  
  127.     tstate = PyThreadState_New(interp);
  128.     if (tstate == NULL)
  129.         Py_FatalError("Py_Initialize: can't make first thread");
  130.     (void) PyThreadState_Swap(tstate);
  131.  
  132.     interp->modules = PyDict_New();
  133.     if (interp->modules == NULL)
  134.         Py_FatalError("Py_Initialize: can't make modules dictionary");
  135.  
  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);
  141.  
  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);
  151.  
  152.     /* phase 2 of builtins */
  153.     _PyBuiltin_Init_2(interp->builtins);
  154.     _PyImport_FixupExtension("__builtin__", "__builtin__");
  155.  
  156.     _PyImport_Init();
  157.  
  158.     initsigs(); /* Signal handling stuff, including initintr() */
  159.  
  160.     initmain(); /* Module __main__ */
  161.     if (!Py_NoSiteFlag)
  162.         initsite(); /* Module site */
  163. }
  164.  
  165. #ifdef COUNT_ALLOCS
  166. extern void dump_counts Py_PROTO((void));
  167. #endif
  168.  
  169. /* Undo the effect of Py_Initialize().
  170.  
  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.
  175.  
  176.    (XXX We should do better, e.g. wipe out all interpreters and
  177.    threads.)
  178.  
  179.    Locking: as above.
  180.  
  181. */
  182.  
  183. void
  184. Py_Finalize()
  185. {
  186.     PyInterpreterState *interp;
  187.     PyThreadState *tstate;
  188.  
  189.     if (!initialized)
  190.         return;
  191.     initialized = 0;
  192.  
  193.     call_sys_exitfunc();
  194.  
  195.     /* Get current thread state and interpreter pointer */
  196.     tstate = PyThreadState_Get();
  197.     interp = tstate->interp;
  198.  
  199.     /* Disable signal handling */
  200.     PyOS_FiniInterrupts();
  201.  
  202.     /* Destroy PyExc_MemoryErrorInst */
  203.     _PyBuiltin_Fini_1();
  204.  
  205.     /* Destroy all modules */
  206.     PyImport_Cleanup();
  207.  
  208.     /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  209.     _PyImport_Fini();
  210.  
  211.     /* Debugging stuff */
  212. #ifdef COUNT_ALLOCS
  213.     dump_counts();
  214. #endif
  215.  
  216. #ifdef Py_REF_DEBUG
  217.     fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
  218. #endif
  219.  
  220. #ifdef Py_TRACE_REFS
  221.     if (_Py_AskYesNo("Print left references?")) {
  222.         _Py_PrintReferences(stderr);
  223.     }
  224. #endif /* Py_TRACE_REFS */
  225.  
  226.     /* Delete current thread */
  227.     PyInterpreterState_Clear(interp);
  228.     PyThreadState_Swap(NULL);
  229.     PyInterpreterState_Delete(interp);
  230.  
  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.
  235.     */
  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();
  244.  
  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
  249.     */
  250.  
  251.     PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  252.  
  253.     call_ll_exitfuncs();
  254.  
  255. #ifdef Py_TRACE_REFS
  256.     _Py_ResetReferences();
  257. #endif /* Py_TRACE_REFS */
  258. }
  259.  
  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.
  263.  
  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.
  268.  
  269.    Locking: as above.
  270.  
  271. */
  272.  
  273. PyThreadState *
  274. Py_NewInterpreter()
  275. {
  276.     PyInterpreterState *interp;
  277.     PyThreadState *tstate, *save_tstate;
  278.     PyObject *bimod, *sysmod;
  279.  
  280.     if (!initialized)
  281.         Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  282.  
  283.     interp = PyInterpreterState_New();
  284.     if (interp == NULL)
  285.         return NULL;
  286.  
  287.     tstate = PyThreadState_New(interp);
  288.     if (tstate == NULL) {
  289.         PyInterpreterState_Delete(interp);
  290.         return NULL;
  291.     }
  292.  
  293.     save_tstate = PyThreadState_Swap(tstate);
  294.  
  295.     /* XXX The following is lax in error checking */
  296.  
  297.     interp->modules = PyDict_New();
  298.  
  299.     bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
  300.     if (bimod != NULL) {
  301.         interp->builtins = PyModule_GetDict(bimod);
  302.         Py_INCREF(interp->builtins);
  303.     }
  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();
  314.     }
  315.  
  316.     if (!PyErr_Occurred())
  317.         return tstate;
  318.  
  319.     /* Oops, it didn't work.  Undo it all. */
  320.  
  321.     PyErr_Print();
  322.     PyThreadState_Clear(tstate);
  323.     PyThreadState_Swap(save_tstate);
  324.     PyThreadState_Delete(tstate);
  325.     PyInterpreterState_Delete(interp);
  326.  
  327.     return NULL;
  328. }
  329.  
  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.
  334.  
  335.    (Py_Finalize() doesn't have these constraints -- it zaps
  336.    everything, regardless.)
  337.  
  338.    Locking: as above.
  339.  
  340. */
  341.  
  342. void
  343. Py_EndInterpreter(tstate)
  344.     PyThreadState *tstate;
  345. {
  346.     PyInterpreterState *interp = tstate->interp;
  347.  
  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");
  354.  
  355.     PyImport_Cleanup();
  356.     PyInterpreterState_Clear(interp);
  357.     PyThreadState_Swap(NULL);
  358.     PyInterpreterState_Delete(interp);
  359. }
  360.  
  361. static char *progname = "python";
  362.  
  363. void
  364. Py_SetProgramName(pn)
  365.     char *pn;
  366. {
  367.     if (pn && *pn)
  368.         progname = pn;
  369. }
  370.  
  371. char *
  372. Py_GetProgramName()
  373. {
  374.     return progname;
  375. }
  376.  
  377. static char *default_home = NULL;
  378.  
  379. void
  380. Py_SetPythonHome(home)
  381.     char *home;
  382. {
  383.     default_home = home;
  384. }
  385.  
  386. char *
  387. Py_GetPythonHome()
  388. {
  389.     char *home = default_home;
  390.     if (home == NULL)
  391.         home = getenv("PYTHONHOME");
  392.     return home;
  393. }
  394.  
  395. /* Create __main__ module */
  396.  
  397. static void
  398. initmain()
  399. {
  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);
  411.     }
  412. }
  413.  
  414. /* Import the site module (not into __main__ though) */
  415.  
  416. static void
  417. initsite()
  418. {
  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();
  427.         }
  428.         else {
  429.             PyFile_WriteString(
  430.               "'import site' failed; use -v for traceback\n", f);
  431.             PyErr_Clear();
  432.         }
  433.     }
  434.     else {
  435.         Py_DECREF(m);
  436.     }
  437. }
  438.  
  439. /* Parse input from a file and execute it */
  440.  
  441. int
  442. PyRun_AnyFile(fp, filename)
  443.     FILE *fp;
  444.     char *filename;
  445. {
  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);
  452. }
  453.  
  454. int
  455. PyRun_InteractiveLoop(fp, filename)
  456.     FILE *fp;
  457.     char *filename;
  458. {
  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);
  465.     }
  466.     v = PySys_GetObject("ps2");
  467.     if (v == NULL) {
  468.         PySys_SetObject("ps2", v = PyString_FromString("... "));
  469.         Py_XDECREF(v);
  470.     }
  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;
  478.         /*
  479.         if (ret == E_NOMEM)
  480.             return -1;
  481.         */
  482.     }
  483. }
  484.  
  485. int
  486. PyRun_InteractiveOne(fp, filename)
  487.     FILE *fp;
  488.     char *filename;
  489. {
  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);
  501.     }
  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);
  509.     }
  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;
  519.         }
  520.         err_input(&err);
  521.         PyErr_Print();
  522.         return err.error;
  523.     }
  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;
  532.     }
  533.     Py_DECREF(v);
  534.     if (Py_FlushLine())
  535.         PyErr_Clear();
  536.     return 0;
  537. }
  538.  
  539. int
  540. PyRun_SimpleFile(fp, filename)
  541.     FILE *fp;
  542.     char *filename;
  543. {
  544.     PyObject *m, *d, *v;
  545.     char *ext;
  546.  
  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 */
  558.         ) {
  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;
  564.         }
  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);
  571.     }
  572.     if (v == NULL) {
  573.         PyErr_Print();
  574.         return -1;
  575.     }
  576.     Py_DECREF(v);
  577.     if (Py_FlushLine())
  578.         PyErr_Clear();
  579.     return 0;
  580. }
  581.  
  582. int
  583. PyRun_SimpleString(command)
  584.     char *command;
  585. {
  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;
  595.     }
  596.     Py_DECREF(v);
  597.     if (Py_FlushLine())
  598.         PyErr_Clear();
  599.     return 0;
  600. }
  601.  
  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;
  610. {
  611.     long hold;
  612.     PyObject *v;
  613.  
  614.     /* old style errors */
  615.     if (PyTuple_Check(err))
  616.         return PyArg_Parse(err, "(O(ziiz))", message, filename,
  617.                    lineno, offset, text);
  618.  
  619.     /* new style errors.  `err' is an instance */
  620.  
  621.     if (! (v = PyObject_GetAttrString(err, "msg")))
  622.         goto finally;
  623.     *message = v;
  624.  
  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;
  631.  
  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;
  641.  
  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;
  650.  
  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;
  659.  
  660. finally:
  661.     Py_XDECREF(v);
  662.     return 0;
  663. }
  664.  
  665. void
  666. PyErr_Print()
  667. {
  668.     PyErr_PrintEx(1);
  669. }
  670.  
  671. void
  672. PyErr_PrintEx(set_sys_last_vars)
  673.     int set_sys_last_vars;
  674. {
  675.     int err = 0;
  676.     PyObject *exception, *v, *tb, *f;
  677.     PyErr_Fetch(&exception, &v, &tb);
  678.     PyErr_NormalizeException(&exception, &v, &tb);
  679.  
  680.     if (exception == NULL)
  681.         return;
  682.  
  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
  692.             */
  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);
  699.             }
  700.             /* if we failed to dig out the "code" attribute,
  701.                then just let the else clause below print the
  702.                error
  703.             */
  704.         }
  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);
  712.         }
  713.     }
  714.     if (set_sys_last_vars) {
  715.         PySys_SetObject("last_type", exception);
  716.         PySys_SetObject("last_value", v);
  717.         PySys_SetObject("last_traceback", tb);
  718.     }
  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))
  729.         {
  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;
  759.                     }
  760.                     while (*text == ' ' || *text == '\t') {
  761.                         text++;
  762.                         offset--;
  763.                     }
  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--;
  774.                     }
  775.                     PyFile_WriteString("^\n", f);
  776.                 }
  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;
  784.             }
  785.         }
  786.         if (err) {
  787.             /* Don't do anything else */
  788.         }
  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__");
  794.  
  795.             if (moduleName == NULL)
  796.                 err = PyFile_WriteString("<unknown>", f);
  797.             else {
  798.                 char* modstr = PyString_AsString(moduleName);
  799.                 if (modstr && strcmp(modstr, "exceptions")) 
  800.                 {
  801.                     err = PyFile_WriteString(modstr, f);
  802.                     err += PyFile_WriteString(".", f);
  803.                 }
  804.             }
  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);
  811.             }
  812.         }
  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
  820.                 */
  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);
  829.             }
  830.         }
  831.         if (err == 0)
  832.             err = PyFile_WriteString("\n", f);
  833.     }
  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();
  841. }
  842.  
  843. PyObject *
  844. PyRun_String(str, start, globals, locals)
  845.     char *str;
  846.     int start;
  847.     PyObject *globals, *locals;
  848. {
  849.     return run_err_node(PyParser_SimpleParseString(str, start),
  850.                 "<string>", globals, locals);
  851. }
  852.  
  853. PyObject *
  854. PyRun_File(fp, filename, start, globals, locals)
  855.     FILE *fp;
  856.     char *filename;
  857.     int start;
  858.     PyObject *globals, *locals;
  859. {
  860.     return run_err_node(PyParser_SimpleParseFile(fp, filename, start),
  861.                 filename, globals, locals);
  862. }
  863.  
  864. static PyObject *
  865. run_err_node(n, filename, globals, locals)
  866.     node *n;
  867.     char *filename;
  868.     PyObject *globals, *locals;
  869. {
  870.     if (n == NULL)
  871.         return  NULL;
  872.     return run_node(n, filename, globals, locals);
  873. }
  874.  
  875. static PyObject *
  876. run_node(n, filename, globals, locals)
  877.     node *n;
  878.     char *filename;
  879.     PyObject *globals, *locals;
  880. {
  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;
  890. }
  891.  
  892. static PyObject *
  893. run_pyc_file(fp, filename, globals, locals)
  894.     FILE *fp;
  895.     char *filename;
  896.     PyObject *globals, *locals;
  897. {
  898.     PyCodeObject *co;
  899.     PyObject *v;
  900.     long magic;
  901.     long PyImport_GetMagicNumber();
  902.  
  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;
  908.     }
  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;
  917.     }
  918.     co = (PyCodeObject *)v;
  919.     v = PyEval_EvalCode(co, globals, locals);
  920.     Py_DECREF(co);
  921.     return v;
  922. }
  923.  
  924. PyObject *
  925. Py_CompileString(str, filename, start)
  926.     char *str;
  927.     char *filename;
  928.     int start;
  929. {
  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;
  938. }
  939.  
  940. /* Simplified interface to parsefile -- return node or set exception */
  941.  
  942. node *
  943. PyParser_SimpleParseFile(fp, filename, start)
  944.     FILE *fp;
  945.     char *filename;
  946.     int start;
  947. {
  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;
  955. }
  956.  
  957. /* Simplified interface to parsestring -- return node or set exception */
  958.  
  959. node *
  960. PyParser_SimpleParseString(str, start)
  961.     char *str;
  962.     int start;
  963. {
  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;
  970. }
  971.  
  972. /* Set the error appropriate to the given input error code (see errcode.h) */
  973.  
  974. static void
  975. err_input(err)
  976.     perrdetail *err;
  977. {
  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;
  985.     }
  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;
  1011.     }
  1012.     w = Py_BuildValue("(sO)", msg, v);
  1013.     Py_XDECREF(v);
  1014.     PyErr_SetObject(PyExc_SyntaxError, w);
  1015.     Py_XDECREF(w);
  1016. }
  1017.  
  1018. /* Print fatal error message and abort */
  1019.  
  1020. void
  1021. Py_FatalError(msg)
  1022.     char *msg;
  1023. {
  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();
  1037. }
  1038.  
  1039. /* Clean up and exit */
  1040.  
  1041. #ifdef WITH_THREAD
  1042. #include "pythread.h"
  1043. int _PyThread_Started = 0; /* Set by threadmodule.c and maybe others */
  1044. #endif
  1045.  
  1046. #define NEXITFUNCS 32
  1047. static void (*exitfuncs[NEXITFUNCS])();
  1048. static int nexitfuncs = 0;
  1049.  
  1050. int Py_AtExit(func)
  1051.     void (*func) Py_PROTO((void));
  1052. {
  1053.     if (nexitfuncs >= NEXITFUNCS)
  1054.         return -1;
  1055.     exitfuncs[nexitfuncs++] = func;
  1056.     return 0;
  1057. }
  1058.  
  1059. static void
  1060. call_sys_exitfunc()
  1061. {
  1062.     PyObject *exitfunc = PySys_GetObject("exitfunc");
  1063.  
  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();
  1074.         }
  1075.         Py_DECREF(exitfunc);
  1076.     }
  1077.  
  1078.     if (Py_FlushLine())
  1079.         PyErr_Clear();
  1080. }
  1081.  
  1082. static void
  1083. call_ll_exitfuncs()
  1084. {
  1085.     while (nexitfuncs > 0)
  1086.         (*exitfuncs[--nexitfuncs])();
  1087.  
  1088.     fflush(stdout);
  1089.     fflush(stderr);
  1090. }
  1091.  
  1092. void
  1093. Py_Exit(sts)
  1094.     int sts;
  1095. {
  1096.     Py_Finalize();
  1097.  
  1098. #ifdef macintosh
  1099.     PyMac_Exit(sts);
  1100. #else
  1101.     exit(sts);
  1102. #endif
  1103. }
  1104.  
  1105. static void
  1106. initsigs()
  1107. {
  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() */
  1114. }
  1115.  
  1116. #ifdef Py_TRACE_REFS
  1117. /* Ask a yes/no question */
  1118.  
  1119. int
  1120. _Py_AskYesNo(prompt)
  1121.     char *prompt;
  1122. {
  1123.     char buf[256];
  1124.     
  1125.     printf("%s [ny] ", prompt);
  1126.     if (fgets(buf, sizeof buf, stdin) == NULL)
  1127.         return 0;
  1128.     return buf[0] == 'y' || buf[0] == 'Y';
  1129. }
  1130. #endif
  1131.  
  1132. #ifdef MPW
  1133.  
  1134. /* Check for file descriptor connected to interactive device.
  1135.    Pretend that stdin is always interactive, other files never. */
  1136.  
  1137. int
  1138. isatty(fd)
  1139.     int fd;
  1140. {
  1141.     return fd == fileno(stdin);
  1142. }
  1143.  
  1144. #endif
  1145.  
  1146. /*
  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 "???".
  1151.  */
  1152. int
  1153. Py_FdIsInteractive(fp, filename)
  1154.     FILE *fp;
  1155.     char *filename;
  1156. {
  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);
  1164. }
  1165.