Add forgotten initialization. Fixes bug #120994, "Traceback with
[python/dscho.git] / Python / sysmodule.c
blob33d71ac1d8f6c4ac7c862deaf558c85f6fd4af03
2 /* System module */
4 /*
5 Various bits of information used by the interpreter are collected in
6 module 'sys'.
7 Function member:
8 - exit(sts): raise SystemExit
9 Data members:
10 - stdin, stdout, stderr: standard file objects
11 - modules: the table of modules (dictionary)
12 - path: module search path (list of strings)
13 - argv: script arguments (list of strings)
14 - ps1, ps2: optional primary and secondary prompts (strings)
17 #include "Python.h"
18 #include "compile.h"
19 #include "frameobject.h"
21 #include "osdefs.h"
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
27 #ifdef MS_COREDLL
28 extern void *PyWin_DLLhModule;
29 /* A string loaded from the DLL at startup: */
30 extern const char *PyWin_DLLVersionString;
31 #endif
33 PyObject *
34 PySys_GetObject(char *name)
36 PyThreadState *tstate = PyThreadState_Get();
37 PyObject *sd = tstate->interp->sysdict;
38 if (sd == NULL)
39 return NULL;
40 return PyDict_GetItemString(sd, name);
43 FILE *
44 PySys_GetFile(char *name, FILE *def)
46 FILE *fp = NULL;
47 PyObject *v = PySys_GetObject(name);
48 if (v != NULL && PyFile_Check(v))
49 fp = PyFile_AsFile(v);
50 if (fp == NULL)
51 fp = def;
52 return fp;
55 int
56 PySys_SetObject(char *name, PyObject *v)
58 PyThreadState *tstate = PyThreadState_Get();
59 PyObject *sd = tstate->interp->sysdict;
60 if (v == NULL) {
61 if (PyDict_GetItemString(sd, name) == NULL)
62 return 0;
63 else
64 return PyDict_DelItemString(sd, name);
66 else
67 return PyDict_SetItemString(sd, name, v);
70 static PyObject *
71 sys_exc_info(PyObject *self, PyObject *args)
73 PyThreadState *tstate;
74 if (!PyArg_ParseTuple(args, ":exc_info"))
75 return NULL;
76 tstate = PyThreadState_Get();
77 return Py_BuildValue(
78 "(OOO)",
79 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
80 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
81 tstate->exc_traceback != NULL ?
82 tstate->exc_traceback : Py_None);
85 static char exc_info_doc[] =
86 "exc_info() -> (type, value, traceback)\n\
87 \n\
88 Return information about the exception that is currently being handled.\n\
89 This should be called from inside an except clause only.";
91 static PyObject *
92 sys_exit(PyObject *self, PyObject *args)
94 /* Raise SystemExit so callers may catch it or clean up. */
95 PyErr_SetObject(PyExc_SystemExit, args);
96 return NULL;
99 static char exit_doc[] =
100 "exit([status])\n\
102 Exit the interpreter by raising SystemExit(status).\n\
103 If the status is omitted or None, it defaults to zero (i.e., success).\n\
104 If the status numeric, it will be used as the system exit status.\n\
105 If it is another kind of object, it will be printed and the system\n\
106 exit status will be one (i.e., failure).";
108 static PyObject *
109 sys_getdefaultencoding(PyObject *self, PyObject *args)
111 if (!PyArg_ParseTuple(args, ":getdefaultencoding"))
112 return NULL;
113 return PyString_FromString(PyUnicode_GetDefaultEncoding());
116 static char getdefaultencoding_doc[] =
117 "getdefaultencoding() -> string\n\
119 Return the current default string encoding used by the Unicode \n\
120 implementation.";
122 static PyObject *
123 sys_setdefaultencoding(PyObject *self, PyObject *args)
125 char *encoding;
126 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
127 return NULL;
128 if (PyUnicode_SetDefaultEncoding(encoding))
129 return NULL;
130 Py_INCREF(Py_None);
131 return Py_None;
134 static char setdefaultencoding_doc[] =
135 "setdefaultencoding(encoding)\n\
137 Set the current default string encoding used by the Unicode implementation.";
139 static PyObject *
140 sys_settrace(PyObject *self, PyObject *args)
142 PyThreadState *tstate = PyThreadState_Get();
143 if (args == Py_None)
144 args = NULL;
145 else
146 Py_XINCREF(args);
147 Py_XDECREF(tstate->sys_tracefunc);
148 tstate->sys_tracefunc = args;
149 Py_INCREF(Py_None);
150 return Py_None;
153 static char settrace_doc[] =
154 "settrace(function)\n\
156 Set the global debug tracing function. It will be called on each\n\
157 function call. See the debugger chapter in the library manual.";
159 static PyObject *
160 sys_setprofile(PyObject *self, PyObject *args)
162 PyThreadState *tstate = PyThreadState_Get();
163 if (args == Py_None)
164 args = NULL;
165 else
166 Py_XINCREF(args);
167 Py_XDECREF(tstate->sys_profilefunc);
168 tstate->sys_profilefunc = args;
169 Py_INCREF(Py_None);
170 return Py_None;
173 static char setprofile_doc[] =
174 "setprofile(function)\n\
176 Set the profiling function. It will be called on each function call\n\
177 and return. See the profiler chapter in the library manual.";
179 static PyObject *
180 sys_setcheckinterval(PyObject *self, PyObject *args)
182 PyThreadState *tstate = PyThreadState_Get();
183 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval))
184 return NULL;
185 Py_INCREF(Py_None);
186 return Py_None;
189 static char setcheckinterval_doc[] =
190 "setcheckinterval(n)\n\
192 Tell the Python interpreter to check for asynchronous events every\n\
193 n instructions. This also affects how often thread switches occur.";
195 static PyObject *
196 sys_setrecursionlimit(PyObject *self, PyObject *args)
198 int new_limit;
199 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
200 return NULL;
201 if (new_limit <= 0) {
202 PyErr_SetString(PyExc_ValueError,
203 "recursion limit must be positive");
204 return NULL;
206 Py_SetRecursionLimit(new_limit);
207 Py_INCREF(Py_None);
208 return Py_None;
211 static char setrecursionlimit_doc[] =
212 "setrecursionlimit(n)\n\
214 Set the maximum depth of the Python interpreter stack to n. This\n\
215 limit prevents infinite recursion from causing an overflow of the C\n\
216 stack and crashing Python. The highest possible limit is platform-\n\
217 dependent.";
219 static PyObject *
220 sys_getrecursionlimit(PyObject *self, PyObject *args)
222 if (!PyArg_ParseTuple(args, ":getrecursionlimit"))
223 return NULL;
224 return PyInt_FromLong(Py_GetRecursionLimit());
227 static char getrecursionlimit_doc[] =
228 "getrecursionlimit()\n\
230 Return the current value of the recursion limit, the maximum depth\n\
231 of the Python interpreter stack. This limit prevents infinite\n\
232 recursion from causing an overflow of the C stack and crashing Python.";
234 #ifdef USE_MALLOPT
235 /* Link with -lmalloc (or -lmpc) on an SGI */
236 #include <malloc.h>
238 static PyObject *
239 sys_mdebug(PyObject *self, PyObject *args)
241 int flag;
242 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
243 return NULL;
244 mallopt(M_DEBUG, flag);
245 Py_INCREF(Py_None);
246 return Py_None;
248 #endif /* USE_MALLOPT */
250 static PyObject *
251 sys_getrefcount(PyObject *self, PyObject *args)
253 PyObject *arg;
254 if (!PyArg_ParseTuple(args, "O:getrefcount", &arg))
255 return NULL;
256 return PyInt_FromLong(arg->ob_refcnt);
259 #ifdef Py_TRACE_REFS
260 static PyObject *
261 sys_gettotalrefcount(PyObject *self, PyObject *args)
263 extern long _Py_RefTotal;
264 if (!PyArg_ParseTuple(args, ":gettotalrefcount"))
265 return NULL;
266 return PyInt_FromLong(_Py_RefTotal);
269 #endif /* Py_TRACE_REFS */
271 static char getrefcount_doc[] =
272 "getrefcount(object) -> integer\n\
274 Return the current reference count for the object. This includes the\n\
275 temporary reference in the argument list, so it is at least 2.";
277 #ifdef COUNT_ALLOCS
278 static PyObject *
279 sys_getcounts(PyObject *self, PyObject *args)
281 extern PyObject *get_counts(void);
283 if (!PyArg_ParseTuple(args, ":getcounts"))
284 return NULL;
285 return get_counts();
287 #endif
289 static char getframe_doc[] =
290 "_getframe([depth]) -> frameobject\n\
292 Return a frame object from the call stack. If optional integer depth is\n\
293 given, return the frame object that many calls below the top of the stack.\n\
294 If that is deeper than the call stack, ValueError is raised. The default\n\
295 for depth is zero, returning the frame at the top of the call stack.\n\
297 This function should be used for internal and specialized\n\
298 purposes only.";
300 static PyObject *
301 sys_getframe(PyObject *self, PyObject *args)
303 PyFrameObject *f = PyThreadState_Get()->frame;
304 int depth = -1;
306 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
307 return NULL;
309 while (depth > 0 && f != NULL) {
310 f = f->f_back;
311 --depth;
313 if (f == NULL) {
314 PyErr_SetString(PyExc_ValueError,
315 "call stack is not deep enough");
316 return NULL;
318 Py_INCREF(f);
319 return (PyObject*)f;
323 #ifdef Py_TRACE_REFS
324 /* Defined in objects.c because it uses static globals if that file */
325 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
326 #endif
328 #ifdef DYNAMIC_EXECUTION_PROFILE
329 /* Defined in ceval.c because it uses static globals if that file */
330 extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
331 #endif
333 static PyMethodDef sys_methods[] = {
334 /* Might as well keep this in alphabetic order */
335 {"exc_info", sys_exc_info, 1, exc_info_doc},
336 {"exit", sys_exit, 0, exit_doc},
337 {"getdefaultencoding", sys_getdefaultencoding, 1,
338 getdefaultencoding_doc},
339 #ifdef COUNT_ALLOCS
340 {"getcounts", sys_getcounts, 1},
341 #endif
342 #ifdef DYNAMIC_EXECUTION_PROFILE
343 {"getdxp", _Py_GetDXProfile, 1},
344 #endif
345 #ifdef Py_TRACE_REFS
346 {"getobjects", _Py_GetObjects, 1},
347 {"gettotalrefcount", sys_gettotalrefcount, 1},
348 #endif
349 {"getrefcount", sys_getrefcount, 1, getrefcount_doc},
350 {"getrecursionlimit", sys_getrecursionlimit, 1,
351 getrecursionlimit_doc},
352 {"_getframe", sys_getframe, 1, getframe_doc},
353 #ifdef USE_MALLOPT
354 {"mdebug", sys_mdebug, 1},
355 #endif
356 {"setdefaultencoding", sys_setdefaultencoding, 1,
357 setdefaultencoding_doc},
358 {"setcheckinterval", sys_setcheckinterval, 1,
359 setcheckinterval_doc},
360 {"setprofile", sys_setprofile, 0, setprofile_doc},
361 {"setrecursionlimit", sys_setrecursionlimit, 1,
362 setrecursionlimit_doc},
363 {"settrace", sys_settrace, 0, settrace_doc},
364 {NULL, NULL} /* sentinel */
367 static PyObject *
368 list_builtin_module_names(void)
370 PyObject *list = PyList_New(0);
371 int i;
372 if (list == NULL)
373 return NULL;
374 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
375 PyObject *name = PyString_FromString(
376 PyImport_Inittab[i].name);
377 if (name == NULL)
378 break;
379 PyList_Append(list, name);
380 Py_DECREF(name);
382 if (PyList_Sort(list) != 0) {
383 Py_DECREF(list);
384 list = NULL;
386 if (list) {
387 PyObject *v = PyList_AsTuple(list);
388 Py_DECREF(list);
389 list = v;
391 return list;
394 static PyObject *warnoptions = NULL;
396 void
397 PySys_ResetWarnOptions(void)
399 if (warnoptions == NULL || !PyList_Check(warnoptions))
400 return;
401 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
404 void
405 PySys_AddWarnOption(char *s)
407 PyObject *str;
409 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
410 Py_XDECREF(warnoptions);
411 warnoptions = PyList_New(0);
412 if (warnoptions == NULL)
413 return;
415 str = PyString_FromString(s);
416 if (str != NULL) {
417 PyList_Append(warnoptions, str);
418 Py_DECREF(str);
422 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
423 Two literals concatenated works just fine. If you have a K&R compiler
424 or other abomination that however *does* understand longer strings,
425 get rid of the !!! comment in the middle and the quotes that surround it. */
426 static char sys_doc[] =
427 "This module provides access to some objects used or maintained by the\n\
428 interpreter and to functions that interact strongly with the interpreter.\n\
430 Dynamic objects:\n\
432 argv -- command line arguments; argv[0] is the script pathname if known\n\
433 path -- module search path; path[0] is the script directory, else ''\n\
434 modules -- dictionary of loaded modules\n\
435 exitfunc -- you may set this to a function to be called when Python exits\n\
437 stdin -- standard input file object; used by raw_input() and input()\n\
438 stdout -- standard output file object; used by the print statement\n\
439 stderr -- standard error object; used for error messages\n\
440 By assigning another file object (or an object that behaves like a file)\n\
441 to one of these, it is possible to redirect all of the interpreter's I/O.\n\
443 last_type -- type of last uncaught exception\n\
444 last_value -- value of last uncaught exception\n\
445 last_traceback -- traceback of last uncaught exception\n\
446 These three are only available in an interactive session after a\n\
447 traceback has been printed.\n\
449 exc_type -- type of exception currently being handled\n\
450 exc_value -- value of exception currently being handled\n\
451 exc_traceback -- traceback of exception currently being handled\n\
452 The function exc_info() should be used instead of these three,\n\
453 because it is thread-safe.\n\
455 #ifndef MS_WIN16
456 /* Concatenating string here */
457 "\n\
458 Static objects:\n\
460 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
461 builtin_module_names -- tuple of module names built into this intepreter\n\
462 version -- the version of this interpreter as a string\n\
463 version_info -- version information as a tuple\n\
464 hexversion -- version information encoded as a single integer\n\
465 copyright -- copyright notice pertaining to this interpreter\n\
466 platform -- platform identifier\n\
467 executable -- pathname of this Python interpreter\n\
468 prefix -- prefix used to find the Python library\n\
469 exec_prefix -- prefix used to find the machine-specific Python library\n\
470 dllhandle -- [Windows only] integer handle of the Python DLL\n\
471 winver -- [Windows only] version number of the Python DLL\n\
472 __stdin__ -- the original stdin; don't use!\n\
473 __stdout__ -- the original stdout; don't use!\n\
474 __stderr__ -- the original stderr; don't use!\n\
476 Functions:\n\
478 exc_info() -- return thread-safe information about the current exception\n\
479 exit() -- exit the interpreter by raising SystemExit\n\
480 getrefcount() -- return the reference count for an object (plus one :-)\n\
481 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
482 setcheckinterval() -- control how often the interpreter checks for events\n\
483 setprofile() -- set the global profiling function\n\
484 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
485 settrace() -- set the global debug tracing function\n\
487 #endif
488 /* end of sys_doc */ ;
490 PyObject *
491 _PySys_Init(void)
493 PyObject *m, *v, *sysdict;
494 PyObject *sysin, *sysout, *syserr;
495 char *s;
497 m = Py_InitModule3("sys", sys_methods, sys_doc);
498 sysdict = PyModule_GetDict(m);
500 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
501 sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
502 syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
503 if (PyErr_Occurred())
504 return NULL;
505 PyDict_SetItemString(sysdict, "stdin", sysin);
506 PyDict_SetItemString(sysdict, "stdout", sysout);
507 PyDict_SetItemString(sysdict, "stderr", syserr);
508 /* Make backup copies for cleanup */
509 PyDict_SetItemString(sysdict, "__stdin__", sysin);
510 PyDict_SetItemString(sysdict, "__stdout__", sysout);
511 PyDict_SetItemString(sysdict, "__stderr__", syserr);
512 Py_XDECREF(sysin);
513 Py_XDECREF(sysout);
514 Py_XDECREF(syserr);
515 PyDict_SetItemString(sysdict, "version",
516 v = PyString_FromString(Py_GetVersion()));
517 Py_XDECREF(v);
518 PyDict_SetItemString(sysdict, "hexversion",
519 v = PyInt_FromLong(PY_VERSION_HEX));
520 Py_XDECREF(v);
522 * These release level checks are mutually exclusive and cover
523 * the field, so don't get too fancy with the pre-processor!
525 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
526 s = "alpha";
527 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
528 s = "beta";
529 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
530 s = "candidate";
531 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
532 s = "final";
533 #endif
534 PyDict_SetItemString(sysdict, "version_info",
535 v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
536 PY_MINOR_VERSION,
537 PY_MICRO_VERSION, s,
538 PY_RELEASE_SERIAL));
539 Py_XDECREF(v);
540 PyDict_SetItemString(sysdict, "copyright",
541 v = PyString_FromString(Py_GetCopyright()));
542 Py_XDECREF(v);
543 PyDict_SetItemString(sysdict, "platform",
544 v = PyString_FromString(Py_GetPlatform()));
545 Py_XDECREF(v);
546 PyDict_SetItemString(sysdict, "executable",
547 v = PyString_FromString(Py_GetProgramFullPath()));
548 Py_XDECREF(v);
549 PyDict_SetItemString(sysdict, "prefix",
550 v = PyString_FromString(Py_GetPrefix()));
551 Py_XDECREF(v);
552 PyDict_SetItemString(sysdict, "exec_prefix",
553 v = PyString_FromString(Py_GetExecPrefix()));
554 Py_XDECREF(v);
555 PyDict_SetItemString(sysdict, "maxint",
556 v = PyInt_FromLong(PyInt_GetMax()));
557 Py_XDECREF(v);
558 PyDict_SetItemString(sysdict, "builtin_module_names",
559 v = list_builtin_module_names());
560 Py_XDECREF(v);
562 /* Assumes that longs are at least 2 bytes long.
563 Should be safe! */
564 unsigned long number = 1;
565 char *value;
567 s = (char *) &number;
568 if (s[0] == 0)
569 value = "big";
570 else
571 value = "little";
572 PyDict_SetItemString(sysdict, "byteorder",
573 v = PyString_FromString(value));
574 Py_XDECREF(v);
576 #ifdef MS_COREDLL
577 PyDict_SetItemString(sysdict, "dllhandle",
578 v = PyLong_FromVoidPtr(PyWin_DLLhModule));
579 Py_XDECREF(v);
580 PyDict_SetItemString(sysdict, "winver",
581 v = PyString_FromString(PyWin_DLLVersionString));
582 Py_XDECREF(v);
583 #endif
584 if (warnoptions == NULL) {
585 warnoptions = PyList_New(0);
587 else {
588 Py_INCREF(warnoptions);
590 if (warnoptions != NULL) {
591 PyDict_SetItemString(sysdict, "warnoptions", v = warnoptions);
592 Py_DECREF(v);
595 if (PyErr_Occurred())
596 return NULL;
597 return m;
600 static PyObject *
601 makepathobject(char *path, int delim)
603 int i, n;
604 char *p;
605 PyObject *v, *w;
607 n = 1;
608 p = path;
609 while ((p = strchr(p, delim)) != NULL) {
610 n++;
611 p++;
613 v = PyList_New(n);
614 if (v == NULL)
615 return NULL;
616 for (i = 0; ; i++) {
617 p = strchr(path, delim);
618 if (p == NULL)
619 p = strchr(path, '\0'); /* End of string */
620 w = PyString_FromStringAndSize(path, (int) (p - path));
621 if (w == NULL) {
622 Py_DECREF(v);
623 return NULL;
625 PyList_SetItem(v, i, w);
626 if (*p == '\0')
627 break;
628 path = p+1;
630 return v;
633 void
634 PySys_SetPath(char *path)
636 PyObject *v;
637 if ((v = makepathobject(path, DELIM)) == NULL)
638 Py_FatalError("can't create sys.path");
639 if (PySys_SetObject("path", v) != 0)
640 Py_FatalError("can't assign sys.path");
641 Py_DECREF(v);
644 static PyObject *
645 makeargvobject(int argc, char **argv)
647 PyObject *av;
648 if (argc <= 0 || argv == NULL) {
649 /* Ensure at least one (empty) argument is seen */
650 static char *empty_argv[1] = {""};
651 argv = empty_argv;
652 argc = 1;
654 av = PyList_New(argc);
655 if (av != NULL) {
656 int i;
657 for (i = 0; i < argc; i++) {
658 PyObject *v = PyString_FromString(argv[i]);
659 if (v == NULL) {
660 Py_DECREF(av);
661 av = NULL;
662 break;
664 PyList_SetItem(av, i, v);
667 return av;
670 void
671 PySys_SetArgv(int argc, char **argv)
673 PyObject *av = makeargvobject(argc, argv);
674 PyObject *path = PySys_GetObject("path");
675 if (av == NULL)
676 Py_FatalError("no mem for sys.argv");
677 if (PySys_SetObject("argv", av) != 0)
678 Py_FatalError("can't assign sys.argv");
679 if (path != NULL) {
680 char *argv0 = argv[0];
681 char *p = NULL;
682 int n = 0;
683 PyObject *a;
684 #ifdef HAVE_READLINK
685 char link[MAXPATHLEN+1];
686 char argv0copy[2*MAXPATHLEN+1];
687 int nr = 0;
688 if (argc > 0 && argv0 != NULL)
689 nr = readlink(argv0, link, MAXPATHLEN);
690 if (nr > 0) {
691 /* It's a symlink */
692 link[nr] = '\0';
693 if (link[0] == SEP)
694 argv0 = link; /* Link to absolute path */
695 else if (strchr(link, SEP) == NULL)
696 ; /* Link without path */
697 else {
698 /* Must join(dirname(argv0), link) */
699 char *q = strrchr(argv0, SEP);
700 if (q == NULL)
701 argv0 = link; /* argv0 without path */
702 else {
703 /* Must make a copy */
704 strcpy(argv0copy, argv0);
705 q = strrchr(argv0copy, SEP);
706 strcpy(q+1, link);
707 argv0 = argv0copy;
711 #endif /* HAVE_READLINK */
712 #if SEP == '\\' /* Special case for MS filename syntax */
713 if (argc > 0 && argv0 != NULL) {
714 char *q;
715 p = strrchr(argv0, SEP);
716 /* Test for alternate separator */
717 q = strrchr(p ? p : argv0, '/');
718 if (q != NULL)
719 p = q;
720 if (p != NULL) {
721 n = p + 1 - argv0;
722 if (n > 1 && p[-1] != ':')
723 n--; /* Drop trailing separator */
726 #else /* All other filename syntaxes */
727 if (argc > 0 && argv0 != NULL)
728 p = strrchr(argv0, SEP);
729 if (p != NULL) {
730 n = p + 1 - argv0;
731 #if SEP == '/' /* Special case for Unix filename syntax */
732 if (n > 1)
733 n--; /* Drop trailing separator */
734 #endif /* Unix */
736 #endif /* All others */
737 a = PyString_FromStringAndSize(argv0, n);
738 if (a == NULL)
739 Py_FatalError("no mem for sys.path insertion");
740 if (PyList_Insert(path, 0, a) < 0)
741 Py_FatalError("sys.path.insert(0) failed");
742 Py_DECREF(a);
744 Py_DECREF(av);
748 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
749 Adapted from code submitted by Just van Rossum.
751 PySys_WriteStdout(format, ...)
752 PySys_WriteStderr(format, ...)
754 The first function writes to sys.stdout; the second to sys.stderr. When
755 there is a problem, they write to the real (C level) stdout or stderr;
756 no exceptions are raised.
758 Both take a printf-style format string as their first argument followed
759 by a variable length argument list determined by the format string.
761 *** WARNING ***
763 The format should limit the total size of the formatted output string to
764 1000 bytes. In particular, this means that no unrestricted "%s" formats
765 should occur; these should be limited using "%.<N>s where <N> is a
766 decimal number calculated so that <N> plus the maximum size of other
767 formatted text does not exceed 1000 bytes. Also watch out for "%f",
768 which can print hundreds of digits for very large numbers.
772 static void
773 mywrite(char *name, FILE *fp, const char *format, va_list va)
775 PyObject *file;
776 PyObject *error_type, *error_value, *error_traceback;
778 PyErr_Fetch(&error_type, &error_value, &error_traceback);
779 file = PySys_GetObject(name);
780 if (file == NULL || PyFile_AsFile(file) == fp)
781 vfprintf(fp, format, va);
782 else {
783 char buffer[1001];
784 if (vsprintf(buffer, format, va) >= sizeof(buffer))
785 Py_FatalError("PySys_WriteStdout/err: buffer overrun");
786 if (PyFile_WriteString(buffer, file) != 0) {
787 PyErr_Clear();
788 fputs(buffer, fp);
791 PyErr_Restore(error_type, error_value, error_traceback);
794 void
795 PySys_WriteStdout(const char *format, ...)
797 va_list va;
799 va_start(va, format);
800 mywrite("stdout", stdout, format, va);
801 va_end(va);
804 void
805 PySys_WriteStderr(const char *format, ...)
807 va_list va;
809 va_start(va, format);
810 mywrite("stderr", stderr, format, va);
811 va_end(va);