home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / py2s152.zip / Python / sysmodule.c < prev    next >
C/C++ Source or Header  |  1999-06-27  |  19KB  |  687 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. /* System module */
  33.  
  34. /*
  35. Various bits of information used by the interpreter are collected in
  36. module 'sys'.
  37. Function member:
  38. - exit(sts): raise SystemExit
  39. Data members:
  40. - stdin, stdout, stderr: standard file objects
  41. - modules: the table of modules (dictionary)
  42. - path: module search path (list of strings)
  43. - argv: script arguments (list of strings)
  44. - ps1, ps2: optional primary and secondary prompts (strings)
  45. */
  46.  
  47. #include "Python.h"
  48.  
  49. #include "osdefs.h"
  50.  
  51. #ifdef HAVE_UNISTD_H
  52. #include <unistd.h>
  53. #endif
  54.  
  55. #ifdef MS_COREDLL
  56. extern void *PyWin_DLLhModule;
  57. /* A string loaded from the DLL at startup: */
  58. extern const char *PyWin_DLLVersionString;
  59. #endif
  60.  
  61. PyObject *
  62. PySys_GetObject(name)
  63.     char *name;
  64. {
  65.     PyThreadState *tstate = PyThreadState_Get();
  66.     PyObject *sd = tstate->interp->sysdict;
  67.     return PyDict_GetItemString(sd, name);
  68. }
  69.  
  70. FILE *
  71. PySys_GetFile(name, def)
  72.     char *name;
  73.     FILE *def;
  74. {
  75.     FILE *fp = NULL;
  76.     PyObject *v = PySys_GetObject(name);
  77.     if (v != NULL && PyFile_Check(v))
  78.         fp = PyFile_AsFile(v);
  79.     if (fp == NULL)
  80.         fp = def;
  81.     return fp;
  82. }
  83.  
  84. int
  85. PySys_SetObject(name, v)
  86.     char *name;
  87.     PyObject *v;
  88. {
  89.     PyThreadState *tstate = PyThreadState_Get();
  90.     PyObject *sd = tstate->interp->sysdict;
  91.     if (v == NULL) {
  92.         if (PyDict_GetItemString(sd, name) == NULL)
  93.             return 0;
  94.         else
  95.             return PyDict_DelItemString(sd, name);
  96.     }
  97.     else
  98.         return PyDict_SetItemString(sd, name, v);
  99. }
  100.  
  101. static PyObject *
  102. sys_exc_info(self, args)
  103.     PyObject *self;
  104.     PyObject *args;
  105. {
  106.     PyThreadState *tstate;
  107.     if (!PyArg_Parse(args, ""))
  108.         return NULL;
  109.     tstate = PyThreadState_Get();
  110.     return Py_BuildValue(
  111.         "(OOO)",
  112.         tstate->exc_type != NULL ? tstate->exc_type : Py_None,
  113.         tstate->exc_value != NULL ? tstate->exc_value : Py_None,
  114.         tstate->exc_traceback != NULL ?
  115.             tstate->exc_traceback : Py_None);
  116. }
  117.  
  118. static char exc_info_doc[] =
  119. "exc_info() -> (type, value, traceback)\n\
  120. \n\
  121. Return information about the exception that is currently being handled.\n\
  122. This should be called from inside an except clause only.";
  123.  
  124. static PyObject *
  125. sys_exit(self, args)
  126.     PyObject *self;
  127.     PyObject *args;
  128. {
  129.     /* Raise SystemExit so callers may catch it or clean up. */
  130.     PyErr_SetObject(PyExc_SystemExit, args);
  131.     return NULL;
  132. }
  133.  
  134. static char exit_doc[] =
  135. "exit([status])\n\
  136. \n\
  137. Exit the interpreter by raising SystemExit(status).\n\
  138. If the status is omitted or None, it defaults to zero (i.e., success).\n\
  139. If the status numeric, it will be used as the system exit status.\n\
  140. If it is another kind of object, it will be printed and the system\n\
  141. exit status will be one (i.e., failure).";
  142.  
  143. static PyObject *
  144. sys_settrace(self, args)
  145.     PyObject *self;
  146.     PyObject *args;
  147. {
  148.     PyThreadState *tstate = PyThreadState_Get();
  149.     if (args == Py_None)
  150.         args = NULL;
  151.     else
  152.         Py_XINCREF(args);
  153.     Py_XDECREF(tstate->sys_tracefunc);
  154.     tstate->sys_tracefunc = args;
  155.     Py_INCREF(Py_None);
  156.     return Py_None;
  157. }
  158.  
  159. static char settrace_doc[] =
  160. "settrace(function)\n\
  161. \n\
  162. Set the global debug tracing function.  It will be called on each\n\
  163. function call.  See the debugger chapter in the library manual.";
  164.  
  165. static PyObject *
  166. sys_setprofile(self, args)
  167.     PyObject *self;
  168.     PyObject *args;
  169. {
  170.     PyThreadState *tstate = PyThreadState_Get();
  171.     if (args == Py_None)
  172.         args = NULL;
  173.     else
  174.         Py_XINCREF(args);
  175.     Py_XDECREF(tstate->sys_profilefunc);
  176.     tstate->sys_profilefunc = args;
  177.     Py_INCREF(Py_None);
  178.     return Py_None;
  179. }
  180.  
  181. static char setprofile_doc[] =
  182. "setprofile(function)\n\
  183. \n\
  184. Set the profiling function.  It will be called on each function call\n\
  185. and return.  See the profiler chapter in the library manual.";
  186.  
  187. static PyObject *
  188. sys_setcheckinterval(self, args)
  189.     PyObject *self;
  190.     PyObject *args;
  191. {
  192.     PyThreadState *tstate = PyThreadState_Get();
  193.     if (!PyArg_ParseTuple(args, "i", &tstate->interp->checkinterval))
  194.         return NULL;
  195.     Py_INCREF(Py_None);
  196.     return Py_None;
  197. }
  198.  
  199. static char setcheckinterval_doc[] =
  200. "setcheckinterval(n)\n\
  201. \n\
  202. Tell the Python interpreter to check for asynchronous events every\n\
  203. n instructions.  This also affects how often thread switches occur.";
  204.  
  205. #ifdef USE_MALLOPT
  206. /* Link with -lmalloc (or -lmpc) on an SGI */
  207. #include <malloc.h>
  208.  
  209. static PyObject *
  210. sys_mdebug(self, args)
  211.     PyObject *self;
  212.     PyObject *args;
  213. {
  214.     int flag;
  215.     if (!PyArg_Parse(args, "i", &flag))
  216.         return NULL;
  217.     mallopt(M_DEBUG, flag);
  218.     Py_INCREF(Py_None);
  219.     return Py_None;
  220. }
  221. #endif /* USE_MALLOPT */
  222.  
  223. static PyObject *
  224. sys_getrefcount(self, args)
  225.     PyObject *self;
  226.     PyObject *args;
  227. {
  228.     PyObject *arg;
  229.     if (!PyArg_Parse(args, "O", &arg))
  230.         return NULL;
  231.     return PyInt_FromLong((long) arg->ob_refcnt);
  232. }
  233.  
  234. static char getrefcount_doc[] =
  235. "getrefcount(object) -> integer\n\
  236. \n\
  237. Return the current reference count for the object.  This includes the\n\
  238. temporary reference in the argument list, so it is at least 2.";
  239.  
  240. #ifdef COUNT_ALLOCS
  241. static PyObject *
  242. sys_getcounts(self, args)
  243.     PyObject *self, *args;
  244. {
  245.     extern PyObject *get_counts Py_PROTO((void));
  246.  
  247.     if (!PyArg_Parse(args, ""))
  248.         return NULL;
  249.     return get_counts();
  250. }
  251. #endif
  252.  
  253. #ifdef Py_TRACE_REFS
  254. /* Defined in objects.c because it uses static globals if that file */
  255. extern PyObject *_Py_GetObjects Py_PROTO((PyObject *, PyObject *));
  256. #endif
  257.  
  258. #ifdef DYNAMIC_EXECUTION_PROFILE
  259. /* Defined in ceval.c because it uses static globals if that file */
  260. extern PyObject *_Py_GetDXProfile Py_PROTO((PyObject *,  PyObject *));
  261. #endif
  262.  
  263. static PyMethodDef sys_methods[] = {
  264.     /* Might as well keep this in alphabetic order */
  265.     {"exc_info",    sys_exc_info, 0, exc_info_doc},
  266.     {"exit",    sys_exit, 0, exit_doc},
  267. #ifdef COUNT_ALLOCS
  268.     {"getcounts",    sys_getcounts, 0},
  269. #endif
  270. #ifdef DYNAMIC_EXECUTION_PROFILE
  271.     {"getdxp",    _Py_GetDXProfile, 1},
  272. #endif
  273. #ifdef Py_TRACE_REFS
  274.     {"getobjects",    _Py_GetObjects, 1},
  275. #endif
  276.     {"getrefcount",    sys_getrefcount, 0, getrefcount_doc},
  277. #ifdef USE_MALLOPT
  278.     {"mdebug",    sys_mdebug, 0},
  279. #endif
  280.     {"setcheckinterval",    sys_setcheckinterval, 1, setcheckinterval_doc},
  281.     {"setprofile",    sys_setprofile, 0, setprofile_doc},
  282.     {"settrace",    sys_settrace, 0, settrace_doc},
  283.     {NULL,        NULL}        /* sentinel */
  284. };
  285.  
  286. static PyObject *
  287. list_builtin_module_names()
  288. {
  289.     PyObject *list = PyList_New(0);
  290.     int i;
  291.     if (list == NULL)
  292.         return NULL;
  293.     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
  294.         PyObject *name = PyString_FromString(
  295.             PyImport_Inittab[i].name);
  296.         if (name == NULL)
  297.             break;
  298.         PyList_Append(list, name);
  299.         Py_DECREF(name);
  300.     }
  301.     if (PyList_Sort(list) != 0) {
  302.         Py_DECREF(list);
  303.         list = NULL;
  304.     }
  305.     if (list) {
  306.         PyObject *v = PyList_AsTuple(list);
  307.         Py_DECREF(list);
  308.         list = v;
  309.     }
  310.     return list;
  311. }
  312.  
  313. /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
  314.    Two literals concatenated works just fine.  If you have a K&R compiler
  315.    or other abomination that however *does* understand longer strings,
  316.    get rid of the !!! comment in the middle and the quotes that surround it. */
  317. static char sys_doc[] =
  318. "This module provides access to some objects used or maintained by the\n\
  319. interpreter and to functions that interact strongly with the interpreter.\n\
  320. \n\
  321. Dynamic objects:\n\
  322. \n\
  323. argv -- command line arguments; argv[0] is the script pathname if known\n\
  324. path -- module search path; path[0] is the script directory, else ''\n\
  325. modules -- dictionary of loaded modules\n\
  326. exitfunc -- you may set this to a function to be called when Python exits\n\
  327. \n\
  328. stdin -- standard input file object; used by raw_input() and input()\n\
  329. stdout -- standard output file object; used by the print statement\n\
  330. stderr -- standard error object; used for error messages\n\
  331.   By assigning another file object (or an object that behaves like a file)\n\
  332.   to one of these, it is possible to redirect all of the interpreter's I/O.\n\
  333. \n\
  334. last_type -- type of last uncaught exception\n\
  335. last_value -- value of last uncaught exception\n\
  336. last_traceback -- traceback of last uncaught exception\n\
  337.   These three are only available in an interactive session after a\n\
  338.   traceback has been printed.\n\
  339. \n\
  340. exc_type -- type of exception currently being handled\n\
  341. exc_value -- value of exception currently being handled\n\
  342. exc_traceback -- traceback of exception currently being handled\n\
  343.   The function exc_info() should be used instead of these three,\n\
  344.   because it is thread-safe.\n\
  345. "
  346. #ifndef MS_WIN16
  347. /* Concatenating string here */
  348. "\n\
  349. Static objects:\n\
  350. \n\
  351. maxint -- the largest supported integer (the smallest is -maxint-1)\n\
  352. builtin_module_names -- tuple of module names built into this intepreter\n\
  353. version -- the version of this interpreter\n\
  354. copyright -- copyright notice pertaining to this interpreter\n\
  355. platform -- platform identifier\n\
  356. executable -- pathname of this Python interpreter\n\
  357. prefix -- prefix used to find the Python library\n\
  358. exec_prefix -- prefix used to find the machine-specific Python library\n\
  359. dllhandle -- [Windows only] integer handle of the Python DLL\n\
  360. winver -- [Windows only] version number of the Python DLL\n\
  361. __stdin__ -- the original stdin; don't use!\n\
  362. __stdout__ -- the original stdout; don't use!\n\
  363. __stderr__ -- the original stderr; don't use!\n\
  364. \n\
  365. Functions:\n\
  366. \n\
  367. exc_info() -- return thread-safe information about the current exception\n\
  368. exit() -- exit the interpreter by raising SystemExit\n\
  369. getrefcount() -- return the reference count for an object (plus one :-)\n\
  370. setcheckinterval() -- control how often the interpreter checks for events\n\
  371. setprofile() -- set the global profiling function\n\
  372. settrace() -- set the global debug tracing function\n\
  373. ";
  374. #endif
  375.  
  376. PyObject *
  377. _PySys_Init()
  378. {
  379.     extern int fclose Py_PROTO((FILE *));
  380.     PyObject *m, *v, *sysdict;
  381.     PyObject *sysin, *sysout, *syserr;
  382.  
  383.     m = Py_InitModule3("sys", sys_methods, sys_doc);
  384.     sysdict = PyModule_GetDict(m);
  385.  
  386.     sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
  387.     sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
  388.     syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
  389.     if (PyErr_Occurred())
  390.         return NULL;
  391.     PyDict_SetItemString(sysdict, "stdin", sysin);
  392.     PyDict_SetItemString(sysdict, "stdout", sysout);
  393.     PyDict_SetItemString(sysdict, "stderr", syserr);
  394.     /* Make backup copies for cleanup */
  395.     PyDict_SetItemString(sysdict, "__stdin__", sysin);
  396.     PyDict_SetItemString(sysdict, "__stdout__", sysout);
  397.     PyDict_SetItemString(sysdict, "__stderr__", syserr);
  398.     Py_XDECREF(sysin);
  399.     Py_XDECREF(sysout);
  400.     Py_XDECREF(syserr);
  401.     PyDict_SetItemString(sysdict, "version",
  402.                  v = PyString_FromString(Py_GetVersion()));
  403.     Py_XDECREF(v);
  404.     PyDict_SetItemString(sysdict, "hexversion",
  405.                  v = PyInt_FromLong(PY_VERSION_HEX));
  406.     Py_XDECREF(v);
  407.     PyDict_SetItemString(sysdict, "copyright",
  408.                  v = PyString_FromString(Py_GetCopyright()));
  409.     Py_XDECREF(v);
  410.     PyDict_SetItemString(sysdict, "platform",
  411.                  v = PyString_FromString(Py_GetPlatform()));
  412.     Py_XDECREF(v);
  413.     PyDict_SetItemString(sysdict, "executable",
  414.                  v = PyString_FromString(Py_GetProgramFullPath()));
  415.     Py_XDECREF(v);
  416.     PyDict_SetItemString(sysdict, "prefix",
  417.                  v = PyString_FromString(Py_GetPrefix()));
  418.     Py_XDECREF(v);
  419.     PyDict_SetItemString(sysdict, "exec_prefix",
  420.            v = PyString_FromString(Py_GetExecPrefix()));
  421.     Py_XDECREF(v);
  422.     PyDict_SetItemString(sysdict, "maxint",
  423.                  v = PyInt_FromLong(PyInt_GetMax()));
  424.     Py_XDECREF(v);
  425.     PyDict_SetItemString(sysdict, "builtin_module_names",
  426.            v = list_builtin_module_names());
  427.     Py_XDECREF(v);
  428. #ifdef MS_COREDLL
  429.     PyDict_SetItemString(sysdict, "dllhandle",
  430.                  v = PyInt_FromLong((int)PyWin_DLLhModule));
  431.     Py_XDECREF(v);
  432.     PyDict_SetItemString(sysdict, "winver",
  433.                  v = PyString_FromString(PyWin_DLLVersionString));
  434.     Py_XDECREF(v);
  435. #endif
  436.     if (PyErr_Occurred())
  437.         return NULL;
  438.     return m;
  439. }
  440.  
  441. static PyObject *
  442. makepathobject(path, delim)
  443.     char *path;
  444.     int delim;
  445. {
  446.     int i, n;
  447.     char *p;
  448.     PyObject *v, *w;
  449.     
  450.     n = 1;
  451.     p = path;
  452.     while ((p = strchr(p, delim)) != NULL) {
  453.         n++;
  454.         p++;
  455.     }
  456.     v = PyList_New(n);
  457.     if (v == NULL)
  458.         return NULL;
  459.     for (i = 0; ; i++) {
  460.         p = strchr(path, delim);
  461.         if (p == NULL)
  462.             p = strchr(path, '\0'); /* End of string */
  463.         w = PyString_FromStringAndSize(path, (int) (p - path));
  464.         if (w == NULL) {
  465.             Py_DECREF(v);
  466.             return NULL;
  467.         }
  468.         PyList_SetItem(v, i, w);
  469.         if (*p == '\0')
  470.             break;
  471.         path = p+1;
  472.     }
  473.     return v;
  474. }
  475.  
  476. void
  477. PySys_SetPath(path)
  478.     char *path;
  479. {
  480.     PyObject *v;
  481.     if ((v = makepathobject(path, DELIM)) == NULL)
  482.         Py_FatalError("can't create sys.path");
  483.     if (PySys_SetObject("path", v) != 0)
  484.         Py_FatalError("can't assign sys.path");
  485.     Py_DECREF(v);
  486. }
  487.  
  488. static PyObject *
  489. makeargvobject(argc, argv)
  490.     int argc;
  491.     char **argv;
  492. {
  493.     PyObject *av;
  494.     if (argc <= 0 || argv == NULL) {
  495.         /* Ensure at least one (empty) argument is seen */
  496.         static char *empty_argv[1] = {""};
  497.         argv = empty_argv;
  498.         argc = 1;
  499.     }
  500.     av = PyList_New(argc);
  501.     if (av != NULL) {
  502.         int i;
  503.         for (i = 0; i < argc; i++) {
  504.             PyObject *v = PyString_FromString(argv[i]);
  505.             if (v == NULL) {
  506.                 Py_DECREF(av);
  507.                 av = NULL;
  508.                 break;
  509.             }
  510.             PyList_SetItem(av, i, v);
  511.         }
  512.     }
  513.     return av;
  514. }
  515.  
  516. void
  517. PySys_SetArgv(argc, argv)
  518.     int argc;
  519.     char **argv;
  520. {
  521.     PyObject *av = makeargvobject(argc, argv);
  522.     PyObject *path = PySys_GetObject("path");
  523.     if (av == NULL)
  524.         Py_FatalError("no mem for sys.argv");
  525.     if (PySys_SetObject("argv", av) != 0)
  526.         Py_FatalError("can't assign sys.argv");
  527.     if (path != NULL) {
  528.         char *argv0 = argv[0];
  529.         char *p = NULL;
  530.         int n = 0;
  531.         PyObject *a;
  532. #ifdef HAVE_READLINK
  533.         char link[MAXPATHLEN+1];
  534.         char argv0copy[2*MAXPATHLEN+1];
  535.         int nr = 0;
  536.         if (argc > 0 && argv0 != NULL)
  537.             nr = readlink(argv0, link, MAXPATHLEN);
  538.         if (nr > 0) {
  539.             /* It's a symlink */
  540.             link[nr] = '\0';
  541.             if (link[0] == SEP)
  542.                 argv0 = link; /* Link to absolute path */
  543.             else if (strchr(link, SEP) == NULL)
  544.                 ; /* Link without path */
  545.             else {
  546.                 /* Must join(dirname(argv0), link) */
  547.                 char *q = strrchr(argv0, SEP);
  548.                 if (q == NULL)
  549.                     argv0 = link; /* argv0 without path */
  550.                 else {
  551.                     /* Must make a copy */
  552.                     strcpy(argv0copy, argv0);
  553.                     q = strrchr(argv0copy, SEP);
  554.                     strcpy(q+1, link);
  555.                     argv0 = argv0copy;
  556.                 }
  557.             }
  558.         }
  559. #endif /* HAVE_READLINK */
  560. #if SEP == '\\' /* Special case for MS filename syntax */
  561.         if (argc > 0 && argv0 != NULL) {
  562.             char *q;
  563.             p = strrchr(argv0, SEP);
  564.             /* Test for alternate separator */
  565.             q = strrchr(p ? p : argv0, '/');
  566.             if (q != NULL)
  567.                 p = q;
  568.             if (p != NULL) {
  569.                 n = p + 1 - argv0;
  570.                 if (n > 1 && p[-1] != ':')
  571.                     n--; /* Drop trailing separator */
  572.             }
  573.         }
  574. #else /* All other filename syntaxes */
  575.         if (argc > 0 && argv0 != NULL)
  576.             p = strrchr(argv0, SEP);
  577.         if (p != NULL) {
  578.             n = p + 1 - argv0;
  579. #if SEP == '/' /* Special case for Unix filename syntax */
  580.             if (n > 1)
  581.                 n--; /* Drop trailing separator */
  582. #endif /* Unix */
  583.         }
  584. #endif /* All others */
  585.         a = PyString_FromStringAndSize(argv0, n);
  586.         if (a == NULL)
  587.             Py_FatalError("no mem for sys.path insertion");
  588.         if (PyList_Insert(path, 0, a) < 0)
  589.             Py_FatalError("sys.path.insert(0) failed");
  590.         Py_DECREF(a);
  591.     }
  592.     Py_DECREF(av);
  593. }
  594.  
  595.  
  596. /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
  597.    Adapted from code submitted by Just van Rossum.
  598.  
  599.    PySys_WriteStdout(format, ...)
  600.    PySys_WriteStderr(format, ...)
  601.  
  602.       The first function writes to sys.stdout; the second to sys.stderr.  When
  603.       there is a problem, they write to the real (C level) stdout or stderr;
  604.       no exceptions are raised.
  605.  
  606.       Both take a printf-style format string as their first argument followed
  607.       by a variable length argument list determined by the format string.
  608.  
  609.       *** WARNING ***
  610.  
  611.       The format should limit the total size of the formatted output string to
  612.       1000 bytes.  In particular, this means that no unrestricted "%s" formats
  613.       should occur; these should be limited using "%.<N>s where <N> is a
  614.       decimal number calculated so that <N> plus the maximum size of other
  615.       formatted text does not exceed 1000 bytes.  Also watch out for "%f",
  616.       which can print hundreds of digits for very large numbers.
  617.  
  618.  */
  619.  
  620. static void
  621. mywrite(name, fp, format, va)
  622.     char *name;
  623.     FILE *fp;
  624.     const char *format;
  625.     va_list va;
  626. {
  627.     PyObject *file;
  628.     PyObject *error_type, *error_value, *error_traceback;
  629.  
  630.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  631.     file = PySys_GetObject(name);
  632.     if (file == NULL || PyFile_AsFile(file) == fp)
  633.         vfprintf(fp, format, va);
  634.     else {
  635.         char buffer[1001];
  636.         if (vsprintf(buffer, format, va) >= sizeof(buffer))
  637.             Py_FatalError("PySys_WriteStdout/err: buffer overrun");
  638.         if (PyFile_WriteString(buffer, file) != 0) {
  639.             PyErr_Clear();
  640.             fputs(buffer, fp);
  641.         }
  642.     }
  643.     PyErr_Restore(error_type, error_value, error_traceback);
  644. }
  645.  
  646. void
  647. #ifdef HAVE_STDARG_PROTOTYPES
  648. PySys_WriteStdout(const char *format, ...)
  649. #else
  650. PySys_WriteStdout(va_alist)
  651.     va_dcl
  652. #endif
  653. {
  654.     va_list va;
  655.  
  656. #ifdef HAVE_STDARG_PROTOTYPES
  657.     va_start(va, format);
  658. #else
  659.     char *format;
  660.     va_start(va);
  661.     format = va_arg(va, char *);
  662. #endif
  663.     mywrite("stdout", stdout, format, va);
  664.     va_end(va);
  665. }
  666.  
  667. void
  668. #ifdef HAVE_STDARG_PROTOTYPES
  669. PySys_WriteStderr(const char *format, ...)
  670. #else
  671. PySys_WriteStderr(va_alist)
  672.     va_dcl
  673. #endif
  674. {
  675.     va_list va;
  676.  
  677. #ifdef HAVE_STDARG_PROTOTYPES
  678.     va_start(va, format);
  679. #else
  680.     char *format;
  681.     va_start(va);
  682.     format = va_arg(va, char *);
  683. #endif
  684.     mywrite("stderr", stderr, format, va);
  685.     va_end(va);
  686. }
  687.