AddressList.__str__(): Get rid of useless, and broken method. Closes
[python/dscho.git] / Python / sysmodule.c
blobedbc2bf5805b2d40dd79922cc785bf25ce4da645
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"
20 #include "eval.h"
22 #include "osdefs.h"
24 #ifdef MS_WINDOWS
25 #define WIN32_LEAN_AND_MEAN
26 #include "windows.h"
27 #endif /* MS_WINDOWS */
29 #ifdef MS_COREDLL
30 extern void *PyWin_DLLhModule;
31 /* A string loaded from the DLL at startup: */
32 extern const char *PyWin_DLLVersionString;
33 #endif
35 #ifdef __VMS
36 #include <unixlib.h>
37 #endif
39 #ifdef MS_WINDOWS
40 #include <windows.h>
41 #endif
43 #ifdef HAVE_LANGINFO_H
44 #include <locale.h>
45 #include <langinfo.h>
46 #endif
48 PyObject *
49 PySys_GetObject(char *name)
51 PyThreadState *tstate = PyThreadState_Get();
52 PyObject *sd = tstate->interp->sysdict;
53 if (sd == NULL)
54 return NULL;
55 return PyDict_GetItemString(sd, name);
58 FILE *
59 PySys_GetFile(char *name, FILE *def)
61 FILE *fp = NULL;
62 PyObject *v = PySys_GetObject(name);
63 if (v != NULL && PyFile_Check(v))
64 fp = PyFile_AsFile(v);
65 if (fp == NULL)
66 fp = def;
67 return fp;
70 int
71 PySys_SetObject(char *name, PyObject *v)
73 PyThreadState *tstate = PyThreadState_Get();
74 PyObject *sd = tstate->interp->sysdict;
75 if (v == NULL) {
76 if (PyDict_GetItemString(sd, name) == NULL)
77 return 0;
78 else
79 return PyDict_DelItemString(sd, name);
81 else
82 return PyDict_SetItemString(sd, name, v);
85 static PyObject *
86 sys_displayhook(PyObject *self, PyObject *o)
88 PyObject *outf;
89 PyInterpreterState *interp = PyThreadState_Get()->interp;
90 PyObject *modules = interp->modules;
91 PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
93 if (builtins == NULL) {
94 PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
95 return NULL;
98 /* Print value except if None */
99 /* After printing, also assign to '_' */
100 /* Before, set '_' to None to avoid recursion */
101 if (o == Py_None) {
102 Py_INCREF(Py_None);
103 return Py_None;
105 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
106 return NULL;
107 if (Py_FlushLine() != 0)
108 return NULL;
109 outf = PySys_GetObject("stdout");
110 if (outf == NULL) {
111 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
112 return NULL;
114 if (PyFile_WriteObject(o, outf, 0) != 0)
115 return NULL;
116 PyFile_SoftSpace(outf, 1);
117 if (Py_FlushLine() != 0)
118 return NULL;
119 if (PyObject_SetAttrString(builtins, "_", o) != 0)
120 return NULL;
121 Py_INCREF(Py_None);
122 return Py_None;
125 PyDoc_STRVAR(displayhook_doc,
126 "displayhook(object) -> None\n"
127 "\n"
128 "Print an object to sys.stdout and also save it in __builtin__._\n"
131 static PyObject *
132 sys_excepthook(PyObject* self, PyObject* args)
134 PyObject *exc, *value, *tb;
135 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
136 return NULL;
137 PyErr_Display(exc, value, tb);
138 Py_INCREF(Py_None);
139 return Py_None;
142 PyDoc_STRVAR(excepthook_doc,
143 "excepthook(exctype, value, traceback) -> None\n"
144 "\n"
145 "Handle an exception by displaying it with a traceback on sys.stderr.\n"
148 static PyObject *
149 sys_exc_info(PyObject *self, PyObject *noargs)
151 PyThreadState *tstate;
152 tstate = PyThreadState_Get();
153 return Py_BuildValue(
154 "(OOO)",
155 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
156 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
157 tstate->exc_traceback != NULL ?
158 tstate->exc_traceback : Py_None);
161 PyDoc_STRVAR(exc_info_doc,
162 "exc_info() -> (type, value, traceback)\n\
164 Return information about the most recent exception caught by an except\n\
165 clause in the current stack frame or in an older stack frame."
168 static PyObject *
169 sys_exc_clear(PyObject *self, PyObject *noargs)
171 PyThreadState *tstate = PyThreadState_Get();
172 PyObject *tmp_type, *tmp_value, *tmp_tb;
173 tmp_type = tstate->exc_type;
174 tmp_value = tstate->exc_value;
175 tmp_tb = tstate->exc_traceback;
176 tstate->exc_type = NULL;
177 tstate->exc_value = NULL;
178 tstate->exc_traceback = NULL;
179 Py_XDECREF(tmp_type);
180 Py_XDECREF(tmp_value);
181 Py_XDECREF(tmp_tb);
182 /* For b/w compatibility */
183 PySys_SetObject("exc_type", Py_None);
184 PySys_SetObject("exc_value", Py_None);
185 PySys_SetObject("exc_traceback", Py_None);
186 Py_INCREF(Py_None);
187 return Py_None;
190 PyDoc_STRVAR(exc_clear_doc,
191 "exc_clear() -> None\n\
193 Clear global information on the current exception. Subsequent calls to\n\
194 exc_info() will return (None,None,None) until another exception is raised\n\
195 in the current thread or the execution stack returns to a frame where\n\
196 another exception is being handled."
199 static PyObject *
200 sys_exit(PyObject *self, PyObject *args)
202 PyObject *exit_code = 0;
203 if (!PyArg_ParseTuple(args, "|O:exit", &exit_code))
204 return NULL;
205 /* Raise SystemExit so callers may catch it or clean up. */
206 PyErr_SetObject(PyExc_SystemExit, exit_code);
207 return NULL;
210 PyDoc_STRVAR(exit_doc,
211 "exit([status])\n\
213 Exit the interpreter by raising SystemExit(status).\n\
214 If the status is omitted or None, it defaults to zero (i.e., success).\n\
215 If the status is numeric, it will be used as the system exit status.\n\
216 If it is another kind of object, it will be printed and the system\n\
217 exit status will be one (i.e., failure)."
220 #ifdef Py_USING_UNICODE
222 static PyObject *
223 sys_getdefaultencoding(PyObject *self)
225 return PyString_FromString(PyUnicode_GetDefaultEncoding());
228 PyDoc_STRVAR(getdefaultencoding_doc,
229 "getdefaultencoding() -> string\n\
231 Return the current default string encoding used by the Unicode \n\
232 implementation."
235 static PyObject *
236 sys_setdefaultencoding(PyObject *self, PyObject *args)
238 char *encoding;
239 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
240 return NULL;
241 if (PyUnicode_SetDefaultEncoding(encoding))
242 return NULL;
243 Py_INCREF(Py_None);
244 return Py_None;
247 PyDoc_STRVAR(setdefaultencoding_doc,
248 "setdefaultencoding(encoding)\n\
250 Set the current default string encoding used by the Unicode implementation."
253 static PyObject *
254 sys_getfilesystemencoding(PyObject *self)
256 if (Py_FileSystemDefaultEncoding)
257 return PyString_FromString(Py_FileSystemDefaultEncoding);
258 Py_INCREF(Py_None);
259 return Py_None;
262 PyDoc_STRVAR(getfilesystemencoding_doc,
263 "getfilesystemencoding() -> string\n\
265 Return the encoding used to convert Unicode filenames in\n\
266 operating system filenames."
269 #endif
272 * Cached interned string objects used for calling the profile and
273 * trace functions. Initialized by trace_init().
275 static PyObject *whatstrings[4] = {NULL, NULL, NULL, NULL};
277 static int
278 trace_init(void)
280 static char *whatnames[4] = {"call", "exception", "line", "return"};
281 PyObject *name;
282 int i;
283 for (i = 0; i < 4; ++i) {
284 if (whatstrings[i] == NULL) {
285 name = PyString_InternFromString(whatnames[i]);
286 if (name == NULL)
287 return -1;
288 whatstrings[i] = name;
291 return 0;
295 static PyObject *
296 call_trampoline(PyThreadState *tstate, PyObject* callback,
297 PyFrameObject *frame, int what, PyObject *arg)
299 PyObject *args = PyTuple_New(3);
300 PyObject *whatstr;
301 PyObject *result;
303 if (args == NULL)
304 return NULL;
305 Py_INCREF(frame);
306 whatstr = whatstrings[what];
307 Py_INCREF(whatstr);
308 if (arg == NULL)
309 arg = Py_None;
310 Py_INCREF(arg);
311 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
312 PyTuple_SET_ITEM(args, 1, whatstr);
313 PyTuple_SET_ITEM(args, 2, arg);
315 /* call the Python-level function */
316 PyFrame_FastToLocals(frame);
317 result = PyEval_CallObject(callback, args);
318 PyFrame_LocalsToFast(frame, 1);
319 if (result == NULL)
320 PyTraceBack_Here(frame);
322 /* cleanup */
323 Py_DECREF(args);
324 return result;
327 static int
328 profile_trampoline(PyObject *self, PyFrameObject *frame,
329 int what, PyObject *arg)
331 PyThreadState *tstate = frame->f_tstate;
332 PyObject *result;
334 if (arg == NULL)
335 arg = Py_None;
336 result = call_trampoline(tstate, self, frame, what, arg);
337 if (result == NULL) {
338 PyEval_SetProfile(NULL, NULL);
339 return -1;
341 Py_DECREF(result);
342 return 0;
345 static int
346 trace_trampoline(PyObject *self, PyFrameObject *frame,
347 int what, PyObject *arg)
349 PyThreadState *tstate = frame->f_tstate;
350 PyObject *callback;
351 PyObject *result;
353 if (what == PyTrace_CALL)
354 callback = self;
355 else
356 callback = frame->f_trace;
357 if (callback == NULL)
358 return 0;
359 result = call_trampoline(tstate, callback, frame, what, arg);
360 if (result == NULL) {
361 PyEval_SetTrace(NULL, NULL);
362 Py_XDECREF(frame->f_trace);
363 frame->f_trace = NULL;
364 return -1;
366 if (result != Py_None) {
367 PyObject *temp = frame->f_trace;
368 frame->f_trace = NULL;
369 Py_XDECREF(temp);
370 frame->f_trace = result;
372 else {
373 Py_DECREF(result);
375 return 0;
378 static PyObject *
379 sys_settrace(PyObject *self, PyObject *args)
381 if (trace_init() == -1)
382 return NULL;
383 if (args == Py_None)
384 PyEval_SetTrace(NULL, NULL);
385 else
386 PyEval_SetTrace(trace_trampoline, args);
387 Py_INCREF(Py_None);
388 return Py_None;
391 PyDoc_STRVAR(settrace_doc,
392 "settrace(function)\n\
394 Set the global debug tracing function. It will be called on each\n\
395 function call. See the debugger chapter in the library manual."
398 static PyObject *
399 sys_setprofile(PyObject *self, PyObject *args)
401 if (trace_init() == -1)
402 return NULL;
403 if (args == Py_None)
404 PyEval_SetProfile(NULL, NULL);
405 else
406 PyEval_SetProfile(profile_trampoline, args);
407 Py_INCREF(Py_None);
408 return Py_None;
411 PyDoc_STRVAR(setprofile_doc,
412 "setprofile(function)\n\
414 Set the profiling function. It will be called on each function call\n\
415 and return. See the profiler chapter in the library manual."
418 static PyObject *
419 sys_setcheckinterval(PyObject *self, PyObject *args)
421 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
422 return NULL;
423 Py_INCREF(Py_None);
424 return Py_None;
427 PyDoc_STRVAR(setcheckinterval_doc,
428 "setcheckinterval(n)\n\
430 Tell the Python interpreter to check for asynchronous events every\n\
431 n instructions. This also affects how often thread switches occur."
434 static PyObject *
435 sys_setrecursionlimit(PyObject *self, PyObject *args)
437 int new_limit;
438 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
439 return NULL;
440 if (new_limit <= 0) {
441 PyErr_SetString(PyExc_ValueError,
442 "recursion limit must be positive");
443 return NULL;
445 Py_SetRecursionLimit(new_limit);
446 Py_INCREF(Py_None);
447 return Py_None;
450 PyDoc_STRVAR(setrecursionlimit_doc,
451 "setrecursionlimit(n)\n\
453 Set the maximum depth of the Python interpreter stack to n. This\n\
454 limit prevents infinite recursion from causing an overflow of the C\n\
455 stack and crashing Python. The highest possible limit is platform-\n\
456 dependent."
459 static PyObject *
460 sys_getrecursionlimit(PyObject *self)
462 return PyInt_FromLong(Py_GetRecursionLimit());
465 PyDoc_STRVAR(getrecursionlimit_doc,
466 "getrecursionlimit()\n\
468 Return the current value of the recursion limit, the maximum depth\n\
469 of the Python interpreter stack. This limit prevents infinite\n\
470 recursion from causing an overflow of the C stack and crashing Python."
473 #ifdef MS_WINDOWS
474 PyDoc_STRVAR(getwindowsversion_doc,
475 "getwindowsversion()\n\
477 Return information about the running version of Windows.\n\
478 The result is a tuple of (major, minor, build, platform, text)\n\
479 All elements are numbers, except text which is a string.\n\
480 Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
484 static PyObject *
485 sys_getwindowsversion(PyObject *self)
487 OSVERSIONINFO ver;
488 ver.dwOSVersionInfoSize = sizeof(ver);
489 if (!GetVersionEx(&ver))
490 return PyErr_SetFromWindowsErr(0);
491 return Py_BuildValue("HHHHs",
492 ver.dwMajorVersion,
493 ver.dwMinorVersion,
494 ver.dwBuildNumber,
495 ver.dwPlatformId,
496 ver.szCSDVersion);
499 #endif /* MS_WINDOWS */
501 #ifdef HAVE_DLOPEN
502 static PyObject *
503 sys_setdlopenflags(PyObject *self, PyObject *args)
505 int new_val;
506 PyThreadState *tstate = PyThreadState_Get();
507 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
508 return NULL;
509 if (!tstate)
510 return NULL;
511 tstate->interp->dlopenflags = new_val;
512 Py_INCREF(Py_None);
513 return Py_None;
516 PyDoc_STRVAR(setdlopenflags_doc,
517 "setdlopenflags(n) -> None\n\
519 Set the flags that will be used for dlopen() calls. Among other\n\
520 things, this will enable a lazy resolving of symbols when importing\n\
521 a module, if called as sys.setdlopenflags(0)\n\
522 To share symbols across extension modules, call as\n\
523 sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
526 static PyObject *
527 sys_getdlopenflags(PyObject *self, PyObject *args)
529 PyThreadState *tstate = PyThreadState_Get();
530 if (!tstate)
531 return NULL;
532 return PyInt_FromLong(tstate->interp->dlopenflags);
535 PyDoc_STRVAR(getdlopenflags_doc,
536 "getdlopenflags() -> int\n\
538 Return the current value of the flags that are used for dlopen()\n\
539 calls. The flag constants are defined in the dl module."
541 #endif
543 #ifdef USE_MALLOPT
544 /* Link with -lmalloc (or -lmpc) on an SGI */
545 #include <malloc.h>
547 static PyObject *
548 sys_mdebug(PyObject *self, PyObject *args)
550 int flag;
551 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
552 return NULL;
553 mallopt(M_DEBUG, flag);
554 Py_INCREF(Py_None);
555 return Py_None;
557 #endif /* USE_MALLOPT */
559 static PyObject *
560 sys_getrefcount(PyObject *self, PyObject *arg)
562 return PyInt_FromLong(arg->ob_refcnt);
565 #ifdef Py_REF_DEBUG
566 static PyObject *
567 sys_gettotalrefcount(PyObject *self)
569 return PyInt_FromLong(_Py_RefTotal);
572 #endif /* Py_TRACE_REFS */
574 PyDoc_STRVAR(getrefcount_doc,
575 "getrefcount(object) -> integer\n\
577 Return the reference count of object. The count returned is generally\n\
578 one higher than you might expect, because it includes the (temporary)\n\
579 reference as an argument to getrefcount()."
582 #ifdef COUNT_ALLOCS
583 static PyObject *
584 sys_getcounts(PyObject *self)
586 extern PyObject *get_counts(void);
588 return get_counts();
590 #endif
592 PyDoc_STRVAR(getframe_doc,
593 "_getframe([depth]) -> frameobject\n\
595 Return a frame object from the call stack. If optional integer depth is\n\
596 given, return the frame object that many calls below the top of the stack.\n\
597 If that is deeper than the call stack, ValueError is raised. The default\n\
598 for depth is zero, returning the frame at the top of the call stack.\n\
600 This function should be used for internal and specialized\n\
601 purposes only."
604 static PyObject *
605 sys_getframe(PyObject *self, PyObject *args)
607 PyFrameObject *f = PyThreadState_Get()->frame;
608 int depth = -1;
610 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
611 return NULL;
613 while (depth > 0 && f != NULL) {
614 f = f->f_back;
615 --depth;
617 if (f == NULL) {
618 PyErr_SetString(PyExc_ValueError,
619 "call stack is not deep enough");
620 return NULL;
622 Py_INCREF(f);
623 return (PyObject*)f;
626 PyDoc_STRVAR(call_tracing_doc,
627 "call_tracing(func, args) -> object\n\
629 Call func(*args), while tracing is enabled. The tracing state is\n\
630 saved, and restored afterwards. This is intended to be called from\n\
631 a debugger from a checkpoint, to recursively debug some other code."
634 static PyObject *
635 sys_call_tracing(PyObject *self, PyObject *args)
637 PyObject *func, *funcargs;
638 if (!PyArg_ParseTuple(args, "OO:call_tracing", &func, &funcargs))
639 return NULL;
640 return _PyEval_CallTracing(func, funcargs);
643 PyDoc_STRVAR(callstats_doc,
644 "callstats() -> tuple of integers\n\
646 Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
647 when Python was built. Otherwise, return None.\n\
649 When enabled, this function returns detailed, implementation-specific\n\
650 details about the number of function calls executed. The return value is\n\
651 a 11-tuple where the entries in the tuple are counts of:\n\
652 0. all function calls\n\
653 1. calls to PyFunction_Type objects\n\
654 2. PyFunction calls that do not create an argument tuple\n\
655 3. PyFunction calls that do not create an argument tuple\n\
656 and bypass PyEval_EvalCodeEx()\n\
657 4. PyMethod calls\n\
658 5. PyMethod calls on bound methods\n\
659 6. PyType calls\n\
660 7. PyCFunction calls\n\
661 8. generator calls\n\
662 9. All other calls\n\
663 10. Number of stack pops performed by call_function()"
666 #ifdef Py_TRACE_REFS
667 /* Defined in objects.c because it uses static globals if that file */
668 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
669 #endif
671 #ifdef DYNAMIC_EXECUTION_PROFILE
672 /* Defined in ceval.c because it uses static globals if that file */
673 extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
674 #endif
676 static PyMethodDef sys_methods[] = {
677 /* Might as well keep this in alphabetic order */
678 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
679 callstats_doc},
680 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
681 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
682 {"exc_clear", sys_exc_clear, METH_NOARGS, exc_clear_doc},
683 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
684 {"exit", sys_exit, METH_VARARGS, exit_doc},
685 #ifdef Py_USING_UNICODE
686 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
687 METH_NOARGS, getdefaultencoding_doc},
688 #endif
689 #ifdef HAVE_DLOPEN
690 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
691 getdlopenflags_doc},
692 #endif
693 #ifdef COUNT_ALLOCS
694 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
695 #endif
696 #ifdef DYNAMIC_EXECUTION_PROFILE
697 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
698 #endif
699 #ifdef Py_USING_UNICODE
700 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
701 METH_NOARGS, getfilesystemencoding_doc},
702 #endif
703 #ifdef Py_TRACE_REFS
704 {"getobjects", _Py_GetObjects, METH_VARARGS},
705 #endif
706 #ifdef Py_REF_DEBUG
707 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
708 #endif
709 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
710 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
711 getrecursionlimit_doc},
712 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
713 #ifdef MS_WINDOWS
714 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
715 getwindowsversion_doc},
716 #endif /* MS_WINDOWS */
717 #ifdef USE_MALLOPT
718 {"mdebug", sys_mdebug, METH_VARARGS},
719 #endif
720 #ifdef Py_USING_UNICODE
721 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
722 setdefaultencoding_doc},
723 #endif
724 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
725 setcheckinterval_doc},
726 #ifdef HAVE_DLOPEN
727 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
728 setdlopenflags_doc},
729 #endif
730 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
731 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
732 setrecursionlimit_doc},
733 {"settrace", sys_settrace, METH_O, settrace_doc},
734 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
735 {NULL, NULL} /* sentinel */
738 static PyObject *
739 list_builtin_module_names(void)
741 PyObject *list = PyList_New(0);
742 int i;
743 if (list == NULL)
744 return NULL;
745 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
746 PyObject *name = PyString_FromString(
747 PyImport_Inittab[i].name);
748 if (name == NULL)
749 break;
750 PyList_Append(list, name);
751 Py_DECREF(name);
753 if (PyList_Sort(list) != 0) {
754 Py_DECREF(list);
755 list = NULL;
757 if (list) {
758 PyObject *v = PyList_AsTuple(list);
759 Py_DECREF(list);
760 list = v;
762 return list;
765 static PyObject *warnoptions = NULL;
767 void
768 PySys_ResetWarnOptions(void)
770 if (warnoptions == NULL || !PyList_Check(warnoptions))
771 return;
772 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
775 void
776 PySys_AddWarnOption(char *s)
778 PyObject *str;
780 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
781 Py_XDECREF(warnoptions);
782 warnoptions = PyList_New(0);
783 if (warnoptions == NULL)
784 return;
786 str = PyString_FromString(s);
787 if (str != NULL) {
788 PyList_Append(warnoptions, str);
789 Py_DECREF(str);
793 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
794 Two literals concatenated works just fine. If you have a K&R compiler
795 or other abomination that however *does* understand longer strings,
796 get rid of the !!! comment in the middle and the quotes that surround it. */
797 PyDoc_VAR(sys_doc) =
798 PyDoc_STR(
799 "This module provides access to some objects used or maintained by the\n\
800 interpreter and to functions that interact strongly with the interpreter.\n\
802 Dynamic objects:\n\
804 argv -- command line arguments; argv[0] is the script pathname if known\n\
805 path -- module search path; path[0] is the script directory, else ''\n\
806 modules -- dictionary of loaded modules\n\
808 displayhook -- called to show results in an interactive session\n\
809 excepthook -- called to handle any uncaught exception other than SystemExit\n\
810 To customize printing in an interactive session or to install a custom\n\
811 top-level exception handler, assign other functions to replace these.\n\
813 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
814 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
816 stdin -- standard input file object; used by raw_input() and input()\n\
817 stdout -- standard output file object; used by the print statement\n\
818 stderr -- standard error object; used for error messages\n\
819 By assigning other file objects (or objects that behave like files)\n\
820 to these, it is possible to redirect all of the interpreter's I/O.\n\
822 last_type -- type of last uncaught exception\n\
823 last_value -- value of last uncaught exception\n\
824 last_traceback -- traceback of last uncaught exception\n\
825 These three are only available in an interactive session after a\n\
826 traceback has been printed.\n\
828 exc_type -- type of exception currently being handled\n\
829 exc_value -- value of exception currently being handled\n\
830 exc_traceback -- traceback of exception currently being handled\n\
831 The function exc_info() should be used instead of these three,\n\
832 because it is thread-safe.\n\
835 /* concatenating string here */
836 PyDoc_STR(
837 "\n\
838 Static objects:\n\
840 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
841 maxunicode -- the largest supported character\n\
842 builtin_module_names -- tuple of module names built into this interpreter\n\
843 version -- the version of this interpreter as a string\n\
844 version_info -- version information as a tuple\n\
845 hexversion -- version information encoded as a single integer\n\
846 copyright -- copyright notice pertaining to this interpreter\n\
847 platform -- platform identifier\n\
848 executable -- pathname of this Python interpreter\n\
849 prefix -- prefix used to find the Python library\n\
850 exec_prefix -- prefix used to find the machine-specific Python library\n\
853 #ifdef MS_WINDOWS
854 /* concatenating string here */
855 PyDoc_STR(
856 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
857 winver -- [Windows only] version number of the Python DLL\n\
860 #endif /* MS_WINDOWS */
861 PyDoc_STR(
862 "__stdin__ -- the original stdin; don't touch!\n\
863 __stdout__ -- the original stdout; don't touch!\n\
864 __stderr__ -- the original stderr; don't touch!\n\
865 __displayhook__ -- the original displayhook; don't touch!\n\
866 __excepthook__ -- the original excepthook; don't touch!\n\
868 Functions:\n\
870 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
871 excepthook() -- print an exception and its traceback to sys.stderr\n\
872 exc_info() -- return thread-safe information about the current exception\n\
873 exc_clear() -- clear the exception state for the current thread\n\
874 exit() -- exit the interpreter by raising SystemExit\n\
875 getdlopenflags() -- returns flags to be used for dlopen() calls\n\
876 getrefcount() -- return the reference count for an object (plus one :-)\n\
877 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
878 setcheckinterval() -- control how often the interpreter checks for events\n\
879 setdlopenflags() -- set the flags to be used for dlopen() calls\n\
880 setprofile() -- set the global profiling function\n\
881 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
882 settrace() -- set the global debug tracing function\n\
885 /* end of sys_doc */ ;
887 PyObject *
888 _PySys_Init(void)
890 PyObject *m, *v, *sysdict;
891 PyObject *sysin, *sysout, *syserr;
892 char *s;
893 #ifdef MS_WINDOWS
894 char buf[10];
895 #endif
896 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
897 char *oldloc, *codeset;
898 #endif
900 m = Py_InitModule3("sys", sys_methods, sys_doc);
901 sysdict = PyModule_GetDict(m);
903 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
904 sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
905 syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
906 if (PyErr_Occurred())
907 return NULL;
908 #ifdef MS_WINDOWS
909 if(isatty(_fileno(stdin))){
910 sprintf(buf, "cp%d", GetConsoleCP());
911 if (!PyFile_SetEncoding(sysin, buf))
912 return NULL;
914 if(isatty(_fileno(stdout))) {
915 sprintf(buf, "cp%d", GetConsoleOutputCP());
916 if (!PyFile_SetEncoding(sysout, buf))
917 return NULL;
919 #endif
921 #if defined(HAVE_LANGINFO_H) && defined(CODESET)
922 oldloc = setlocale(LC_CTYPE, 0);
923 setlocale(LC_CTYPE, "");
924 codeset = nl_langinfo(CODESET);
925 setlocale(LC_CTYPE, oldloc);
926 if(codeset && isatty(fileno(stdin))){
927 if (!PyFile_SetEncoding(sysin, codeset))
928 return NULL;
930 if(codeset && isatty(fileno(stdout))) {
931 if (!PyFile_SetEncoding(sysout, codeset))
932 return NULL;
934 #endif
936 PyDict_SetItemString(sysdict, "stdin", sysin);
937 PyDict_SetItemString(sysdict, "stdout", sysout);
938 PyDict_SetItemString(sysdict, "stderr", syserr);
939 /* Make backup copies for cleanup */
940 PyDict_SetItemString(sysdict, "__stdin__", sysin);
941 PyDict_SetItemString(sysdict, "__stdout__", sysout);
942 PyDict_SetItemString(sysdict, "__stderr__", syserr);
943 PyDict_SetItemString(sysdict, "__displayhook__",
944 PyDict_GetItemString(sysdict, "displayhook"));
945 PyDict_SetItemString(sysdict, "__excepthook__",
946 PyDict_GetItemString(sysdict, "excepthook"));
947 Py_XDECREF(sysin);
948 Py_XDECREF(sysout);
949 Py_XDECREF(syserr);
950 PyDict_SetItemString(sysdict, "version",
951 v = PyString_FromString(Py_GetVersion()));
952 Py_XDECREF(v);
953 PyDict_SetItemString(sysdict, "hexversion",
954 v = PyInt_FromLong(PY_VERSION_HEX));
955 Py_XDECREF(v);
957 * These release level checks are mutually exclusive and cover
958 * the field, so don't get too fancy with the pre-processor!
960 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
961 s = "alpha";
962 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
963 s = "beta";
964 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
965 s = "candidate";
966 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
967 s = "final";
968 #endif
969 PyDict_SetItemString(sysdict, "version_info",
970 v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
971 PY_MINOR_VERSION,
972 PY_MICRO_VERSION, s,
973 PY_RELEASE_SERIAL));
974 Py_XDECREF(v);
975 PyDict_SetItemString(sysdict, "api_version",
976 v = PyInt_FromLong(PYTHON_API_VERSION));
977 Py_XDECREF(v);
978 PyDict_SetItemString(sysdict, "copyright",
979 v = PyString_FromString(Py_GetCopyright()));
980 Py_XDECREF(v);
981 PyDict_SetItemString(sysdict, "platform",
982 v = PyString_FromString(Py_GetPlatform()));
983 Py_XDECREF(v);
984 PyDict_SetItemString(sysdict, "executable",
985 v = PyString_FromString(Py_GetProgramFullPath()));
986 Py_XDECREF(v);
987 PyDict_SetItemString(sysdict, "prefix",
988 v = PyString_FromString(Py_GetPrefix()));
989 Py_XDECREF(v);
990 PyDict_SetItemString(sysdict, "exec_prefix",
991 v = PyString_FromString(Py_GetExecPrefix()));
992 Py_XDECREF(v);
993 PyDict_SetItemString(sysdict, "maxint",
994 v = PyInt_FromLong(PyInt_GetMax()));
995 Py_XDECREF(v);
996 #ifdef Py_USING_UNICODE
997 PyDict_SetItemString(sysdict, "maxunicode",
998 v = PyInt_FromLong(PyUnicode_GetMax()));
999 Py_XDECREF(v);
1000 #endif
1001 PyDict_SetItemString(sysdict, "builtin_module_names",
1002 v = list_builtin_module_names());
1003 Py_XDECREF(v);
1005 /* Assumes that longs are at least 2 bytes long.
1006 Should be safe! */
1007 unsigned long number = 1;
1008 char *value;
1010 s = (char *) &number;
1011 if (s[0] == 0)
1012 value = "big";
1013 else
1014 value = "little";
1015 PyDict_SetItemString(sysdict, "byteorder",
1016 v = PyString_FromString(value));
1017 Py_XDECREF(v);
1019 #ifdef MS_COREDLL
1020 PyDict_SetItemString(sysdict, "dllhandle",
1021 v = PyLong_FromVoidPtr(PyWin_DLLhModule));
1022 Py_XDECREF(v);
1023 PyDict_SetItemString(sysdict, "winver",
1024 v = PyString_FromString(PyWin_DLLVersionString));
1025 Py_XDECREF(v);
1026 #endif
1027 if (warnoptions == NULL) {
1028 warnoptions = PyList_New(0);
1030 else {
1031 Py_INCREF(warnoptions);
1033 if (warnoptions != NULL) {
1034 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1037 if (PyErr_Occurred())
1038 return NULL;
1039 return m;
1042 static PyObject *
1043 makepathobject(char *path, int delim)
1045 int i, n;
1046 char *p;
1047 PyObject *v, *w;
1049 n = 1;
1050 p = path;
1051 while ((p = strchr(p, delim)) != NULL) {
1052 n++;
1053 p++;
1055 v = PyList_New(n);
1056 if (v == NULL)
1057 return NULL;
1058 for (i = 0; ; i++) {
1059 p = strchr(path, delim);
1060 if (p == NULL)
1061 p = strchr(path, '\0'); /* End of string */
1062 w = PyString_FromStringAndSize(path, (int) (p - path));
1063 if (w == NULL) {
1064 Py_DECREF(v);
1065 return NULL;
1067 PyList_SetItem(v, i, w);
1068 if (*p == '\0')
1069 break;
1070 path = p+1;
1072 return v;
1075 void
1076 PySys_SetPath(char *path)
1078 PyObject *v;
1079 if ((v = makepathobject(path, DELIM)) == NULL)
1080 Py_FatalError("can't create sys.path");
1081 if (PySys_SetObject("path", v) != 0)
1082 Py_FatalError("can't assign sys.path");
1083 Py_DECREF(v);
1086 static PyObject *
1087 makeargvobject(int argc, char **argv)
1089 PyObject *av;
1090 if (argc <= 0 || argv == NULL) {
1091 /* Ensure at least one (empty) argument is seen */
1092 static char *empty_argv[1] = {""};
1093 argv = empty_argv;
1094 argc = 1;
1096 av = PyList_New(argc);
1097 if (av != NULL) {
1098 int i;
1099 for (i = 0; i < argc; i++) {
1100 #ifdef __VMS
1101 PyObject *v;
1103 /* argv[0] is the script pathname if known */
1104 if (i == 0) {
1105 char* fn = decc$translate_vms(argv[0]);
1106 if ((fn == (char *)0) || fn == (char *)-1)
1107 v = PyString_FromString(argv[0]);
1108 else
1109 v = PyString_FromString(
1110 decc$translate_vms(argv[0]));
1111 } else
1112 v = PyString_FromString(argv[i]);
1113 #else
1114 PyObject *v = PyString_FromString(argv[i]);
1115 #endif
1116 if (v == NULL) {
1117 Py_DECREF(av);
1118 av = NULL;
1119 break;
1121 PyList_SetItem(av, i, v);
1124 return av;
1127 void
1128 PySys_SetArgv(int argc, char **argv)
1130 #if defined(HAVE_REALPATH)
1131 char fullpath[MAXPATHLEN];
1132 #elif defined(MS_WINDOWS)
1133 char fullpath[MAX_PATH];
1134 #endif
1135 PyObject *av = makeargvobject(argc, argv);
1136 PyObject *path = PySys_GetObject("path");
1137 if (av == NULL)
1138 Py_FatalError("no mem for sys.argv");
1139 if (PySys_SetObject("argv", av) != 0)
1140 Py_FatalError("can't assign sys.argv");
1141 if (path != NULL) {
1142 char *argv0 = argv[0];
1143 char *p = NULL;
1144 int n = 0;
1145 PyObject *a;
1146 #ifdef HAVE_READLINK
1147 char link[MAXPATHLEN+1];
1148 char argv0copy[2*MAXPATHLEN+1];
1149 int nr = 0;
1150 if (argc > 0 && argv0 != NULL)
1151 nr = readlink(argv0, link, MAXPATHLEN);
1152 if (nr > 0) {
1153 /* It's a symlink */
1154 link[nr] = '\0';
1155 if (link[0] == SEP)
1156 argv0 = link; /* Link to absolute path */
1157 else if (strchr(link, SEP) == NULL)
1158 ; /* Link without path */
1159 else {
1160 /* Must join(dirname(argv0), link) */
1161 char *q = strrchr(argv0, SEP);
1162 if (q == NULL)
1163 argv0 = link; /* argv0 without path */
1164 else {
1165 /* Must make a copy */
1166 strcpy(argv0copy, argv0);
1167 q = strrchr(argv0copy, SEP);
1168 strcpy(q+1, link);
1169 argv0 = argv0copy;
1173 #endif /* HAVE_READLINK */
1174 #if SEP == '\\' /* Special case for MS filename syntax */
1175 if (argc > 0 && argv0 != NULL) {
1176 char *q;
1177 #ifdef MS_WINDOWS
1178 char *ptemp;
1179 if (GetFullPathName(argv0,
1180 sizeof(fullpath),
1181 fullpath,
1182 &ptemp)) {
1183 argv0 = fullpath;
1185 #endif
1186 p = strrchr(argv0, SEP);
1187 /* Test for alternate separator */
1188 q = strrchr(p ? p : argv0, '/');
1189 if (q != NULL)
1190 p = q;
1191 if (p != NULL) {
1192 n = p + 1 - argv0;
1193 if (n > 1 && p[-1] != ':')
1194 n--; /* Drop trailing separator */
1197 #else /* All other filename syntaxes */
1198 if (argc > 0 && argv0 != NULL) {
1199 #if defined(HAVE_REALPATH)
1200 if (realpath(argv0, fullpath)) {
1201 argv0 = fullpath;
1203 #endif
1204 p = strrchr(argv0, SEP);
1206 if (p != NULL) {
1207 #ifndef RISCOS
1208 n = p + 1 - argv0;
1209 #else /* don't include trailing separator */
1210 n = p - argv0;
1211 #endif /* RISCOS */
1212 #if SEP == '/' /* Special case for Unix filename syntax */
1213 if (n > 1)
1214 n--; /* Drop trailing separator */
1215 #endif /* Unix */
1217 #endif /* All others */
1218 a = PyString_FromStringAndSize(argv0, n);
1219 if (a == NULL)
1220 Py_FatalError("no mem for sys.path insertion");
1221 if (PyList_Insert(path, 0, a) < 0)
1222 Py_FatalError("sys.path.insert(0) failed");
1223 Py_DECREF(a);
1225 Py_DECREF(av);
1229 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1230 Adapted from code submitted by Just van Rossum.
1232 PySys_WriteStdout(format, ...)
1233 PySys_WriteStderr(format, ...)
1235 The first function writes to sys.stdout; the second to sys.stderr. When
1236 there is a problem, they write to the real (C level) stdout or stderr;
1237 no exceptions are raised.
1239 Both take a printf-style format string as their first argument followed
1240 by a variable length argument list determined by the format string.
1242 *** WARNING ***
1244 The format should limit the total size of the formatted output string to
1245 1000 bytes. In particular, this means that no unrestricted "%s" formats
1246 should occur; these should be limited using "%.<N>s where <N> is a
1247 decimal number calculated so that <N> plus the maximum size of other
1248 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1249 which can print hundreds of digits for very large numbers.
1253 static void
1254 mywrite(char *name, FILE *fp, const char *format, va_list va)
1256 PyObject *file;
1257 PyObject *error_type, *error_value, *error_traceback;
1259 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1260 file = PySys_GetObject(name);
1261 if (file == NULL || PyFile_AsFile(file) == fp)
1262 vfprintf(fp, format, va);
1263 else {
1264 char buffer[1001];
1265 const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
1266 format, va);
1267 if (PyFile_WriteString(buffer, file) != 0) {
1268 PyErr_Clear();
1269 fputs(buffer, fp);
1271 if (written < 0 || written >= sizeof(buffer)) {
1272 const char *truncated = "... truncated";
1273 if (PyFile_WriteString(truncated, file) != 0) {
1274 PyErr_Clear();
1275 fputs(truncated, fp);
1279 PyErr_Restore(error_type, error_value, error_traceback);
1282 void
1283 PySys_WriteStdout(const char *format, ...)
1285 va_list va;
1287 va_start(va, format);
1288 mywrite("stdout", stdout, format, va);
1289 va_end(va);
1292 void
1293 PySys_WriteStderr(const char *format, ...)
1295 va_list va;
1297 va_start(va, format);
1298 mywrite("stderr", stderr, format, va);
1299 va_end(va);