py-cvs-rel2_1 (Rev 1.2) merge
[python/dscho.git] / Python / sysmodule.c
blob76d40bfd0badcd293f919960996014babb986a5a
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_displayhook(PyObject *self, PyObject *args)
73 PyObject *o, *outf;
74 PyInterpreterState *interp = PyThreadState_Get()->interp;
75 PyObject *modules = interp->modules;
76 PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
78 /* parse arguments */
79 if (!PyArg_ParseTuple(args, "O:displayhook", &o))
80 return NULL;
82 /* Print value except if None */
83 /* After printing, also assign to '_' */
84 /* Before, set '_' to None to avoid recursion */
85 if (o == Py_None) {
86 Py_INCREF(Py_None);
87 return Py_None;
89 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
90 return NULL;
91 if (Py_FlushLine() != 0)
92 return NULL;
93 outf = PySys_GetObject("stdout");
94 if (outf == NULL) {
95 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
96 return NULL;
98 if (PyFile_WriteObject(o, outf, 0) != 0)
99 return NULL;
100 PyFile_SoftSpace(outf, 1);
101 if (Py_FlushLine() != 0)
102 return NULL;
103 if (PyObject_SetAttrString(builtins, "_", o) != 0)
104 return NULL;
105 Py_INCREF(Py_None);
106 return Py_None;
109 static char displayhook_doc[] =
110 "displayhook(object) -> None\n"
111 "\n"
112 "Print an object to sys.stdout and also save it in __builtin__._\n";
114 static PyObject *
115 sys_excepthook(PyObject* self, PyObject* args)
117 PyObject *exc, *value, *tb;
118 if (!PyArg_ParseTuple(args, "OOO:excepthook", &exc, &value, &tb))
119 return NULL;
120 PyErr_Display(exc, value, tb);
121 Py_INCREF(Py_None);
122 return Py_None;
125 static char excepthook_doc[] =
126 "excepthook(exctype, value, traceback) -> None\n"
127 "\n"
128 "Handle an exception by displaying it with a traceback on sys.stderr.\n";
130 static PyObject *
131 sys_exc_info(PyObject *self, PyObject *args)
133 PyThreadState *tstate;
134 if (!PyArg_ParseTuple(args, ":exc_info"))
135 return NULL;
136 tstate = PyThreadState_Get();
137 return Py_BuildValue(
138 "(OOO)",
139 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
140 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
141 tstate->exc_traceback != NULL ?
142 tstate->exc_traceback : Py_None);
145 static char exc_info_doc[] =
146 "exc_info() -> (type, value, traceback)\n\
148 Return information about the exception that is currently being handled.\n\
149 This should be called from inside an except clause only.";
151 static PyObject *
152 sys_exit(PyObject *self, PyObject *args)
154 /* Raise SystemExit so callers may catch it or clean up. */
155 PyErr_SetObject(PyExc_SystemExit, args);
156 return NULL;
159 static char exit_doc[] =
160 "exit([status])\n\
162 Exit the interpreter by raising SystemExit(status).\n\
163 If the status is omitted or None, it defaults to zero (i.e., success).\n\
164 If the status numeric, it will be used as the system exit status.\n\
165 If it is another kind of object, it will be printed and the system\n\
166 exit status will be one (i.e., failure).";
168 static PyObject *
169 sys_getdefaultencoding(PyObject *self, PyObject *args)
171 if (!PyArg_ParseTuple(args, ":getdefaultencoding"))
172 return NULL;
173 return PyString_FromString(PyUnicode_GetDefaultEncoding());
176 static char getdefaultencoding_doc[] =
177 "getdefaultencoding() -> string\n\
179 Return the current default string encoding used by the Unicode \n\
180 implementation.";
182 static PyObject *
183 sys_setdefaultencoding(PyObject *self, PyObject *args)
185 char *encoding;
186 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
187 return NULL;
188 if (PyUnicode_SetDefaultEncoding(encoding))
189 return NULL;
190 Py_INCREF(Py_None);
191 return Py_None;
194 static char setdefaultencoding_doc[] =
195 "setdefaultencoding(encoding)\n\
197 Set the current default string encoding used by the Unicode implementation.";
200 * Cached interned string objects used for calling the profile and
201 * trace functions. Initialized by trace_init().
203 static PyObject *whatstrings[4] = {NULL, NULL, NULL, NULL};
205 static int
206 trace_init(void)
208 static char *whatnames[4] = {"call", "exception", "line", "return"};
209 PyObject *name;
210 int i;
211 for (i = 0; i < 4; ++i) {
212 if (whatstrings[i] == NULL) {
213 name = PyString_InternFromString(whatnames[i]);
214 if (name == NULL)
215 return -1;
216 whatstrings[i] = name;
219 return 0;
223 static PyObject *
224 call_trampoline(PyThreadState *tstate, PyObject* callback,
225 PyFrameObject *frame, int what, PyObject *arg)
227 PyObject *args = PyTuple_New(3);
228 PyObject *whatstr;
229 PyObject *result;
231 if (args == NULL)
232 return NULL;
233 Py_INCREF(frame);
234 whatstr = whatstrings[what];
235 Py_INCREF(whatstr);
236 if (arg == NULL)
237 arg = Py_None;
238 Py_INCREF(arg);
239 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
240 PyTuple_SET_ITEM(args, 1, whatstr);
241 PyTuple_SET_ITEM(args, 2, arg);
243 /* call the Python-level function */
244 PyFrame_FastToLocals(frame);
245 result = PyEval_CallObject(callback, args);
246 PyFrame_LocalsToFast(frame, 1);
247 if (result == NULL)
248 PyTraceBack_Here(frame);
250 /* cleanup */
251 Py_DECREF(args);
252 return result;
255 static int
256 profile_trampoline(PyObject *self, PyFrameObject *frame,
257 int what, PyObject *arg)
259 PyThreadState *tstate = frame->f_tstate;
260 PyObject *result;
262 result = call_trampoline(tstate, self, frame, what, arg);
263 if (result == NULL) {
264 PyEval_SetProfile(NULL, NULL);
265 return -1;
267 Py_DECREF(result);
268 return 0;
271 static int
272 trace_trampoline(PyObject *self, PyFrameObject *frame,
273 int what, PyObject *arg)
275 PyThreadState *tstate = frame->f_tstate;
276 PyObject *callback;
277 PyObject *result;
279 if (what == PyTrace_CALL)
280 callback = self;
281 else
282 callback = frame->f_trace;
283 if (callback == NULL)
284 return 0;
285 result = call_trampoline(tstate, callback, frame, what, arg);
286 if (result == NULL) {
287 PyEval_SetTrace(NULL, NULL);
288 Py_XDECREF(frame->f_trace);
289 frame->f_trace = NULL;
290 return -1;
292 if (result != Py_None) {
293 PyObject *temp = frame->f_trace;
294 frame->f_trace = NULL;
295 Py_XDECREF(temp);
296 frame->f_trace = result;
298 else {
299 Py_DECREF(result);
301 return 0;
304 static PyObject *
305 sys_settrace(PyObject *self, PyObject *args)
307 if (trace_init() == -1)
308 return NULL;
309 if (args == Py_None)
310 PyEval_SetTrace(NULL, NULL);
311 else
312 PyEval_SetTrace(trace_trampoline, args);
313 Py_INCREF(Py_None);
314 return Py_None;
317 static char settrace_doc[] =
318 "settrace(function)\n\
320 Set the global debug tracing function. It will be called on each\n\
321 function call. See the debugger chapter in the library manual.";
323 static PyObject *
324 sys_setprofile(PyObject *self, PyObject *args)
326 if (trace_init() == -1)
327 return NULL;
328 if (args == Py_None)
329 PyEval_SetProfile(NULL, NULL);
330 else
331 PyEval_SetProfile(profile_trampoline, args);
332 Py_INCREF(Py_None);
333 return Py_None;
336 static char setprofile_doc[] =
337 "setprofile(function)\n\
339 Set the profiling function. It will be called on each function call\n\
340 and return. See the profiler chapter in the library manual.";
342 static PyObject *
343 sys_setcheckinterval(PyObject *self, PyObject *args)
345 PyThreadState *tstate = PyThreadState_Get();
346 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval))
347 return NULL;
348 Py_INCREF(Py_None);
349 return Py_None;
352 static char setcheckinterval_doc[] =
353 "setcheckinterval(n)\n\
355 Tell the Python interpreter to check for asynchronous events every\n\
356 n instructions. This also affects how often thread switches occur.";
358 static PyObject *
359 sys_setrecursionlimit(PyObject *self, PyObject *args)
361 int new_limit;
362 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
363 return NULL;
364 if (new_limit <= 0) {
365 PyErr_SetString(PyExc_ValueError,
366 "recursion limit must be positive");
367 return NULL;
369 Py_SetRecursionLimit(new_limit);
370 Py_INCREF(Py_None);
371 return Py_None;
374 static char setrecursionlimit_doc[] =
375 "setrecursionlimit(n)\n\
377 Set the maximum depth of the Python interpreter stack to n. This\n\
378 limit prevents infinite recursion from causing an overflow of the C\n\
379 stack and crashing Python. The highest possible limit is platform-\n\
380 dependent.";
382 static PyObject *
383 sys_getrecursionlimit(PyObject *self, PyObject *args)
385 if (!PyArg_ParseTuple(args, ":getrecursionlimit"))
386 return NULL;
387 return PyInt_FromLong(Py_GetRecursionLimit());
390 static char getrecursionlimit_doc[] =
391 "getrecursionlimit()\n\
393 Return the current value of the recursion limit, the maximum depth\n\
394 of the Python interpreter stack. This limit prevents infinite\n\
395 recursion from causing an overflow of the C stack and crashing Python.";
397 #ifdef USE_MALLOPT
398 /* Link with -lmalloc (or -lmpc) on an SGI */
399 #include <malloc.h>
401 static PyObject *
402 sys_mdebug(PyObject *self, PyObject *args)
404 int flag;
405 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
406 return NULL;
407 mallopt(M_DEBUG, flag);
408 Py_INCREF(Py_None);
409 return Py_None;
411 #endif /* USE_MALLOPT */
413 static PyObject *
414 sys_getrefcount(PyObject *self, PyObject *args)
416 PyObject *arg;
417 if (!PyArg_ParseTuple(args, "O:getrefcount", &arg))
418 return NULL;
419 return PyInt_FromLong(arg->ob_refcnt);
422 #ifdef Py_TRACE_REFS
423 static PyObject *
424 sys_gettotalrefcount(PyObject *self, PyObject *args)
426 extern long _Py_RefTotal;
427 if (!PyArg_ParseTuple(args, ":gettotalrefcount"))
428 return NULL;
429 return PyInt_FromLong(_Py_RefTotal);
432 #endif /* Py_TRACE_REFS */
434 static char getrefcount_doc[] =
435 "getrefcount(object) -> integer\n\
437 Return the current reference count for the object. This includes the\n\
438 temporary reference in the argument list, so it is at least 2.";
440 #ifdef COUNT_ALLOCS
441 static PyObject *
442 sys_getcounts(PyObject *self, PyObject *args)
444 extern PyObject *get_counts(void);
446 if (!PyArg_ParseTuple(args, ":getcounts"))
447 return NULL;
448 return get_counts();
450 #endif
452 static char getframe_doc[] =
453 "_getframe([depth]) -> frameobject\n\
455 Return a frame object from the call stack. If optional integer depth is\n\
456 given, return the frame object that many calls below the top of the stack.\n\
457 If that is deeper than the call stack, ValueError is raised. The default\n\
458 for depth is zero, returning the frame at the top of the call stack.\n\
460 This function should be used for internal and specialized\n\
461 purposes only.";
463 static PyObject *
464 sys_getframe(PyObject *self, PyObject *args)
466 PyFrameObject *f = PyThreadState_Get()->frame;
467 int depth = -1;
469 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
470 return NULL;
472 while (depth > 0 && f != NULL) {
473 f = f->f_back;
474 --depth;
476 if (f == NULL) {
477 PyErr_SetString(PyExc_ValueError,
478 "call stack is not deep enough");
479 return NULL;
481 Py_INCREF(f);
482 return (PyObject*)f;
486 #ifdef Py_TRACE_REFS
487 /* Defined in objects.c because it uses static globals if that file */
488 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
489 #endif
491 #ifdef DYNAMIC_EXECUTION_PROFILE
492 /* Defined in ceval.c because it uses static globals if that file */
493 extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
494 #endif
496 static PyMethodDef sys_methods[] = {
497 /* Might as well keep this in alphabetic order */
498 {"displayhook", sys_displayhook, 1, displayhook_doc},
499 {"exc_info", sys_exc_info, 1, exc_info_doc},
500 {"excepthook", sys_excepthook, 1, excepthook_doc},
501 {"exit", sys_exit, 0, exit_doc},
502 {"getdefaultencoding", sys_getdefaultencoding, 1,
503 getdefaultencoding_doc},
504 #ifdef COUNT_ALLOCS
505 {"getcounts", sys_getcounts, 1},
506 #endif
507 #ifdef DYNAMIC_EXECUTION_PROFILE
508 {"getdxp", _Py_GetDXProfile, 1},
509 #endif
510 #ifdef Py_TRACE_REFS
511 {"getobjects", _Py_GetObjects, 1},
512 {"gettotalrefcount", sys_gettotalrefcount, 1},
513 #endif
514 {"getrefcount", sys_getrefcount, 1, getrefcount_doc},
515 {"getrecursionlimit", sys_getrecursionlimit, 1,
516 getrecursionlimit_doc},
517 {"_getframe", sys_getframe, 1, getframe_doc},
518 #ifdef USE_MALLOPT
519 {"mdebug", sys_mdebug, 1},
520 #endif
521 {"setdefaultencoding", sys_setdefaultencoding, 1,
522 setdefaultencoding_doc},
523 {"setcheckinterval", sys_setcheckinterval, 1,
524 setcheckinterval_doc},
525 {"setprofile", sys_setprofile, 0, setprofile_doc},
526 {"setrecursionlimit", sys_setrecursionlimit, 1,
527 setrecursionlimit_doc},
528 {"settrace", sys_settrace, 0, settrace_doc},
529 {NULL, NULL} /* sentinel */
532 static PyObject *
533 list_builtin_module_names(void)
535 PyObject *list = PyList_New(0);
536 int i;
537 if (list == NULL)
538 return NULL;
539 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
540 PyObject *name = PyString_FromString(
541 PyImport_Inittab[i].name);
542 if (name == NULL)
543 break;
544 PyList_Append(list, name);
545 Py_DECREF(name);
547 if (PyList_Sort(list) != 0) {
548 Py_DECREF(list);
549 list = NULL;
551 if (list) {
552 PyObject *v = PyList_AsTuple(list);
553 Py_DECREF(list);
554 list = v;
556 return list;
559 static PyObject *warnoptions = NULL;
561 void
562 PySys_ResetWarnOptions(void)
564 if (warnoptions == NULL || !PyList_Check(warnoptions))
565 return;
566 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
569 void
570 PySys_AddWarnOption(char *s)
572 PyObject *str;
574 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
575 Py_XDECREF(warnoptions);
576 warnoptions = PyList_New(0);
577 if (warnoptions == NULL)
578 return;
580 str = PyString_FromString(s);
581 if (str != NULL) {
582 PyList_Append(warnoptions, str);
583 Py_DECREF(str);
587 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
588 Two literals concatenated works just fine. If you have a K&R compiler
589 or other abomination that however *does* understand longer strings,
590 get rid of the !!! comment in the middle and the quotes that surround it. */
591 static char sys_doc[] =
592 "This module provides access to some objects used or maintained by the\n\
593 interpreter and to functions that interact strongly with the interpreter.\n\
595 Dynamic objects:\n\
597 argv -- command line arguments; argv[0] is the script pathname if known\n\
598 path -- module search path; path[0] is the script directory, else ''\n\
599 modules -- dictionary of loaded modules\n\
601 displayhook -- called to show results in an interactive session\n\
602 excepthook -- called to handle any uncaught exception other than SystemExit\n\
603 To customize printing in an interactive session or to install a custom\n\
604 top-level exception handler, assign other functions to replace these.\n\
606 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
607 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
609 stdin -- standard input file object; used by raw_input() and input()\n\
610 stdout -- standard output file object; used by the print statement\n\
611 stderr -- standard error object; used for error messages\n\
612 By assigning other file objects (or objects that behave like files)\n\
613 to these, it is possible to redirect all of the interpreter's I/O.\n\
615 last_type -- type of last uncaught exception\n\
616 last_value -- value of last uncaught exception\n\
617 last_traceback -- traceback of last uncaught exception\n\
618 These three are only available in an interactive session after a\n\
619 traceback has been printed.\n\
621 exc_type -- type of exception currently being handled\n\
622 exc_value -- value of exception currently being handled\n\
623 exc_traceback -- traceback of exception currently being handled\n\
624 The function exc_info() should be used instead of these three,\n\
625 because it is thread-safe.\n\
627 #ifndef MS_WIN16
628 /* concatenating string here */
629 "\n\
630 Static objects:\n\
632 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
633 maxunicode -- the largest supported character\n\
634 builtin_module_names -- tuple of module names built into this intepreter\n\
635 version -- the version of this interpreter as a string\n\
636 version_info -- version information as a tuple\n\
637 hexversion -- version information encoded as a single integer\n\
638 copyright -- copyright notice pertaining to this interpreter\n\
639 platform -- platform identifier\n\
640 executable -- pathname of this Python interpreter\n\
641 prefix -- prefix used to find the Python library\n\
642 exec_prefix -- prefix used to find the machine-specific Python library\n\
644 #ifdef MS_WINDOWS
645 /* concatenating string here */
646 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
647 winver -- [Windows only] version number of the Python DLL\n\
649 #endif /* MS_WINDOWS */
650 "__stdin__ -- the original stdin; don't touch!\n\
651 __stdout__ -- the original stdout; don't touch!\n\
652 __stderr__ -- the original stderr; don't touch!\n\
653 __displayhook__ -- the original displayhook; don't touch!\n\
654 __excepthook__ -- the original excepthook; don't touch!\n\
656 Functions:\n\
658 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
659 excepthook() -- print an exception and its traceback to sys.stderr\n\
660 exc_info() -- return thread-safe information about the current exception\n\
661 exit() -- exit the interpreter by raising SystemExit\n\
662 getrefcount() -- return the reference count for an object (plus one :-)\n\
663 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
664 setcheckinterval() -- control how often the interpreter checks for events\n\
665 setprofile() -- set the global profiling function\n\
666 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
667 settrace() -- set the global debug tracing function\n\
669 #endif /* MS_WIN16 */
670 /* end of sys_doc */ ;
672 PyObject *
673 _PySys_Init(void)
675 PyObject *m, *v, *sysdict;
676 PyObject *sysin, *sysout, *syserr;
677 char *s;
679 m = Py_InitModule3("sys", sys_methods, sys_doc);
680 sysdict = PyModule_GetDict(m);
682 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
683 sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
684 syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
685 if (PyErr_Occurred())
686 return NULL;
687 PyDict_SetItemString(sysdict, "stdin", sysin);
688 PyDict_SetItemString(sysdict, "stdout", sysout);
689 PyDict_SetItemString(sysdict, "stderr", syserr);
690 /* Make backup copies for cleanup */
691 PyDict_SetItemString(sysdict, "__stdin__", sysin);
692 PyDict_SetItemString(sysdict, "__stdout__", sysout);
693 PyDict_SetItemString(sysdict, "__stderr__", syserr);
694 PyDict_SetItemString(sysdict, "__displayhook__",
695 PyDict_GetItemString(sysdict, "displayhook"));
696 PyDict_SetItemString(sysdict, "__excepthook__",
697 PyDict_GetItemString(sysdict, "excepthook"));
698 Py_XDECREF(sysin);
699 Py_XDECREF(sysout);
700 Py_XDECREF(syserr);
701 PyDict_SetItemString(sysdict, "version",
702 v = PyString_FromString(Py_GetVersion()));
703 Py_XDECREF(v);
704 PyDict_SetItemString(sysdict, "hexversion",
705 v = PyInt_FromLong(PY_VERSION_HEX));
706 Py_XDECREF(v);
708 * These release level checks are mutually exclusive and cover
709 * the field, so don't get too fancy with the pre-processor!
711 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
712 s = "alpha";
713 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
714 s = "beta";
715 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
716 s = "candidate";
717 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
718 s = "final";
719 #endif
720 PyDict_SetItemString(sysdict, "version_info",
721 v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
722 PY_MINOR_VERSION,
723 PY_MICRO_VERSION, s,
724 PY_RELEASE_SERIAL));
725 Py_XDECREF(v);
726 PyDict_SetItemString(sysdict, "copyright",
727 v = PyString_FromString(Py_GetCopyright()));
728 Py_XDECREF(v);
729 PyDict_SetItemString(sysdict, "platform",
730 v = PyString_FromString(Py_GetPlatform()));
731 Py_XDECREF(v);
732 PyDict_SetItemString(sysdict, "executable",
733 v = PyString_FromString(Py_GetProgramFullPath()));
734 Py_XDECREF(v);
735 PyDict_SetItemString(sysdict, "prefix",
736 v = PyString_FromString(Py_GetPrefix()));
737 Py_XDECREF(v);
738 PyDict_SetItemString(sysdict, "exec_prefix",
739 v = PyString_FromString(Py_GetExecPrefix()));
740 Py_XDECREF(v);
741 PyDict_SetItemString(sysdict, "maxint",
742 v = PyInt_FromLong(PyInt_GetMax()));
743 Py_XDECREF(v);
744 PyDict_SetItemString(sysdict, "maxunicode",
745 v = PyInt_FromLong(PyUnicode_GetMax()));
746 Py_XDECREF(v);
747 PyDict_SetItemString(sysdict, "builtin_module_names",
748 v = list_builtin_module_names());
749 Py_XDECREF(v);
751 /* Assumes that longs are at least 2 bytes long.
752 Should be safe! */
753 unsigned long number = 1;
754 char *value;
756 s = (char *) &number;
757 if (s[0] == 0)
758 value = "big";
759 else
760 value = "little";
761 PyDict_SetItemString(sysdict, "byteorder",
762 v = PyString_FromString(value));
763 Py_XDECREF(v);
765 #ifdef MS_COREDLL
766 PyDict_SetItemString(sysdict, "dllhandle",
767 v = PyLong_FromVoidPtr(PyWin_DLLhModule));
768 Py_XDECREF(v);
769 PyDict_SetItemString(sysdict, "winver",
770 v = PyString_FromString(PyWin_DLLVersionString));
771 Py_XDECREF(v);
772 #endif
773 if (warnoptions == NULL) {
774 warnoptions = PyList_New(0);
776 else {
777 Py_INCREF(warnoptions);
779 if (warnoptions != NULL) {
780 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
783 if (PyErr_Occurred())
784 return NULL;
785 return m;
788 static PyObject *
789 makepathobject(char *path, int delim)
791 int i, n;
792 char *p;
793 PyObject *v, *w;
795 n = 1;
796 p = path;
797 while ((p = strchr(p, delim)) != NULL) {
798 n++;
799 p++;
801 v = PyList_New(n);
802 if (v == NULL)
803 return NULL;
804 for (i = 0; ; i++) {
805 p = strchr(path, delim);
806 if (p == NULL)
807 p = strchr(path, '\0'); /* End of string */
808 w = PyString_FromStringAndSize(path, (int) (p - path));
809 if (w == NULL) {
810 Py_DECREF(v);
811 return NULL;
813 PyList_SetItem(v, i, w);
814 if (*p == '\0')
815 break;
816 path = p+1;
818 return v;
821 void
822 PySys_SetPath(char *path)
824 PyObject *v;
825 if ((v = makepathobject(path, DELIM)) == NULL)
826 Py_FatalError("can't create sys.path");
827 if (PySys_SetObject("path", v) != 0)
828 Py_FatalError("can't assign sys.path");
829 Py_DECREF(v);
832 static PyObject *
833 makeargvobject(int argc, char **argv)
835 PyObject *av;
836 if (argc <= 0 || argv == NULL) {
837 /* Ensure at least one (empty) argument is seen */
838 static char *empty_argv[1] = {""};
839 argv = empty_argv;
840 argc = 1;
842 av = PyList_New(argc);
843 if (av != NULL) {
844 int i;
845 for (i = 0; i < argc; i++) {
846 PyObject *v = PyString_FromString(argv[i]);
847 if (v == NULL) {
848 Py_DECREF(av);
849 av = NULL;
850 break;
852 PyList_SetItem(av, i, v);
855 return av;
858 void
859 PySys_SetArgv(int argc, char **argv)
861 PyObject *av = makeargvobject(argc, argv);
862 PyObject *path = PySys_GetObject("path");
863 if (av == NULL)
864 Py_FatalError("no mem for sys.argv");
865 if (PySys_SetObject("argv", av) != 0)
866 Py_FatalError("can't assign sys.argv");
867 if (path != NULL) {
868 char *argv0 = argv[0];
869 char *p = NULL;
870 int n = 0;
871 PyObject *a;
872 #ifdef HAVE_READLINK
873 char link[MAXPATHLEN+1];
874 char argv0copy[2*MAXPATHLEN+1];
875 int nr = 0;
876 if (argc > 0 && argv0 != NULL)
877 nr = readlink(argv0, link, MAXPATHLEN);
878 if (nr > 0) {
879 /* It's a symlink */
880 link[nr] = '\0';
881 if (link[0] == SEP)
882 argv0 = link; /* Link to absolute path */
883 else if (strchr(link, SEP) == NULL)
884 ; /* Link without path */
885 else {
886 /* Must join(dirname(argv0), link) */
887 char *q = strrchr(argv0, SEP);
888 if (q == NULL)
889 argv0 = link; /* argv0 without path */
890 else {
891 /* Must make a copy */
892 strcpy(argv0copy, argv0);
893 q = strrchr(argv0copy, SEP);
894 strcpy(q+1, link);
895 argv0 = argv0copy;
899 #endif /* HAVE_READLINK */
900 #if SEP == '\\' /* Special case for MS filename syntax */
901 if (argc > 0 && argv0 != NULL) {
902 char *q;
903 p = strrchr(argv0, SEP);
904 /* Test for alternate separator */
905 q = strrchr(p ? p : argv0, '/');
906 if (q != NULL)
907 p = q;
908 if (p != NULL) {
909 n = p + 1 - argv0;
910 if (n > 1 && p[-1] != ':')
911 n--; /* Drop trailing separator */
914 #else /* All other filename syntaxes */
915 if (argc > 0 && argv0 != NULL)
916 p = strrchr(argv0, SEP);
917 if (p != NULL) {
918 #ifndef RISCOS
919 n = p + 1 - argv0;
920 #else /* don't include trailing separator */
921 n = p - argv0;
922 #endif /* RISCOS */
923 #if SEP == '/' /* Special case for Unix filename syntax */
924 if (n > 1)
925 n--; /* Drop trailing separator */
926 #endif /* Unix */
928 #endif /* All others */
929 a = PyString_FromStringAndSize(argv0, n);
930 if (a == NULL)
931 Py_FatalError("no mem for sys.path insertion");
932 if (PyList_Insert(path, 0, a) < 0)
933 Py_FatalError("sys.path.insert(0) failed");
934 Py_DECREF(a);
936 Py_DECREF(av);
940 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
941 Adapted from code submitted by Just van Rossum.
943 PySys_WriteStdout(format, ...)
944 PySys_WriteStderr(format, ...)
946 The first function writes to sys.stdout; the second to sys.stderr. When
947 there is a problem, they write to the real (C level) stdout or stderr;
948 no exceptions are raised.
950 Both take a printf-style format string as their first argument followed
951 by a variable length argument list determined by the format string.
953 *** WARNING ***
955 The format should limit the total size of the formatted output string to
956 1000 bytes. In particular, this means that no unrestricted "%s" formats
957 should occur; these should be limited using "%.<N>s where <N> is a
958 decimal number calculated so that <N> plus the maximum size of other
959 formatted text does not exceed 1000 bytes. Also watch out for "%f",
960 which can print hundreds of digits for very large numbers.
964 static void
965 mywrite(char *name, FILE *fp, const char *format, va_list va)
967 PyObject *file;
968 PyObject *error_type, *error_value, *error_traceback;
970 PyErr_Fetch(&error_type, &error_value, &error_traceback);
971 file = PySys_GetObject(name);
972 if (file == NULL || PyFile_AsFile(file) == fp)
973 vfprintf(fp, format, va);
974 else {
975 char buffer[1001];
976 if (vsprintf(buffer, format, va) >= sizeof(buffer))
977 Py_FatalError("PySys_WriteStdout/err: buffer overrun");
978 if (PyFile_WriteString(buffer, file) != 0) {
979 PyErr_Clear();
980 fputs(buffer, fp);
983 PyErr_Restore(error_type, error_value, error_traceback);
986 void
987 PySys_WriteStdout(const char *format, ...)
989 va_list va;
991 va_start(va, format);
992 mywrite("stdout", stdout, format, va);
993 va_end(va);
996 void
997 PySys_WriteStderr(const char *format, ...)
999 va_list va;
1001 va_start(va, format);
1002 mywrite("stderr", stderr, format, va);
1003 va_end(va);