_PySys_Init(): It's rarely a good idea to size a buffer to the
[python.git] / Python / sysmodule.c
blob785653ede0a6fe1bd8c0b70a80ffa765b03b568e
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 "code.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_UnpackTuple(args, "exit", 0, 1, &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[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
277 static int
278 trace_init(void)
280 static char *whatnames[7] = {"call", "exception", "line", "return",
281 "c_call", "c_exception", "c_return"};
282 PyObject *name;
283 int i;
284 for (i = 0; i < 7; ++i) {
285 if (whatstrings[i] == NULL) {
286 name = PyString_InternFromString(whatnames[i]);
287 if (name == NULL)
288 return -1;
289 whatstrings[i] = name;
292 return 0;
296 static PyObject *
297 call_trampoline(PyThreadState *tstate, PyObject* callback,
298 PyFrameObject *frame, int what, PyObject *arg)
300 PyObject *args = PyTuple_New(3);
301 PyObject *whatstr;
302 PyObject *result;
304 if (args == NULL)
305 return NULL;
306 Py_INCREF(frame);
307 whatstr = whatstrings[what];
308 Py_INCREF(whatstr);
309 if (arg == NULL)
310 arg = Py_None;
311 Py_INCREF(arg);
312 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
313 PyTuple_SET_ITEM(args, 1, whatstr);
314 PyTuple_SET_ITEM(args, 2, arg);
316 /* call the Python-level function */
317 PyFrame_FastToLocals(frame);
318 result = PyEval_CallObject(callback, args);
319 PyFrame_LocalsToFast(frame, 1);
320 if (result == NULL)
321 PyTraceBack_Here(frame);
323 /* cleanup */
324 Py_DECREF(args);
325 return result;
328 static int
329 profile_trampoline(PyObject *self, PyFrameObject *frame,
330 int what, PyObject *arg)
332 PyThreadState *tstate = frame->f_tstate;
333 PyObject *result;
335 if (arg == NULL)
336 arg = Py_None;
337 result = call_trampoline(tstate, self, frame, what, arg);
338 if (result == NULL) {
339 PyEval_SetProfile(NULL, NULL);
340 return -1;
342 Py_DECREF(result);
343 return 0;
346 static int
347 trace_trampoline(PyObject *self, PyFrameObject *frame,
348 int what, PyObject *arg)
350 PyThreadState *tstate = frame->f_tstate;
351 PyObject *callback;
352 PyObject *result;
354 if (what == PyTrace_CALL)
355 callback = self;
356 else
357 callback = frame->f_trace;
358 if (callback == NULL)
359 return 0;
360 result = call_trampoline(tstate, callback, frame, what, arg);
361 if (result == NULL) {
362 PyEval_SetTrace(NULL, NULL);
363 Py_XDECREF(frame->f_trace);
364 frame->f_trace = NULL;
365 return -1;
367 if (result != Py_None) {
368 PyObject *temp = frame->f_trace;
369 frame->f_trace = NULL;
370 Py_XDECREF(temp);
371 frame->f_trace = result;
373 else {
374 Py_DECREF(result);
376 return 0;
379 static PyObject *
380 sys_settrace(PyObject *self, PyObject *args)
382 if (trace_init() == -1)
383 return NULL;
384 if (args == Py_None)
385 PyEval_SetTrace(NULL, NULL);
386 else
387 PyEval_SetTrace(trace_trampoline, args);
388 Py_INCREF(Py_None);
389 return Py_None;
392 PyDoc_STRVAR(settrace_doc,
393 "settrace(function)\n\
395 Set the global debug tracing function. It will be called on each\n\
396 function call. See the debugger chapter in the library manual."
399 static PyObject *
400 sys_setprofile(PyObject *self, PyObject *args)
402 if (trace_init() == -1)
403 return NULL;
404 if (args == Py_None)
405 PyEval_SetProfile(NULL, NULL);
406 else
407 PyEval_SetProfile(profile_trampoline, args);
408 Py_INCREF(Py_None);
409 return Py_None;
412 PyDoc_STRVAR(setprofile_doc,
413 "setprofile(function)\n\
415 Set the profiling function. It will be called on each function call\n\
416 and return. See the profiler chapter in the library manual."
419 static PyObject *
420 sys_setcheckinterval(PyObject *self, PyObject *args)
422 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
423 return NULL;
424 Py_INCREF(Py_None);
425 return Py_None;
428 PyDoc_STRVAR(setcheckinterval_doc,
429 "setcheckinterval(n)\n\
431 Tell the Python interpreter to check for asynchronous events every\n\
432 n instructions. This also affects how often thread switches occur."
435 static PyObject *
436 sys_getcheckinterval(PyObject *self, PyObject *args)
438 return PyInt_FromLong(_Py_CheckInterval);
441 PyDoc_STRVAR(getcheckinterval_doc,
442 "getcheckinterval() -> current check interval; see setcheckinterval()."
445 #ifdef WITH_TSC
446 static PyObject *
447 sys_settscdump(PyObject *self, PyObject *args)
449 int bool;
450 PyThreadState *tstate = PyThreadState_Get();
452 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
453 return NULL;
454 if (bool)
455 tstate->interp->tscdump = 1;
456 else
457 tstate->interp->tscdump = 0;
458 Py_INCREF(Py_None);
459 return Py_None;
463 PyDoc_STRVAR(settscdump_doc,
464 "settscdump(bool)\n\
466 If true, tell the Python interpreter to dump VM measurements to\n\
467 stderr. If false, turn off dump. The measurements are based on the\n\
468 processor's time-stamp counter."
470 #endif /* TSC */
472 static PyObject *
473 sys_setrecursionlimit(PyObject *self, PyObject *args)
475 int new_limit;
476 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
477 return NULL;
478 if (new_limit <= 0) {
479 PyErr_SetString(PyExc_ValueError,
480 "recursion limit must be positive");
481 return NULL;
483 Py_SetRecursionLimit(new_limit);
484 Py_INCREF(Py_None);
485 return Py_None;
488 PyDoc_STRVAR(setrecursionlimit_doc,
489 "setrecursionlimit(n)\n\
491 Set the maximum depth of the Python interpreter stack to n. This\n\
492 limit prevents infinite recursion from causing an overflow of the C\n\
493 stack and crashing Python. The highest possible limit is platform-\n\
494 dependent."
497 static PyObject *
498 sys_getrecursionlimit(PyObject *self)
500 return PyInt_FromLong(Py_GetRecursionLimit());
503 PyDoc_STRVAR(getrecursionlimit_doc,
504 "getrecursionlimit()\n\
506 Return the current value of the recursion limit, the maximum depth\n\
507 of the Python interpreter stack. This limit prevents infinite\n\
508 recursion from causing an overflow of the C stack and crashing Python."
511 #ifdef MS_WINDOWS
512 PyDoc_STRVAR(getwindowsversion_doc,
513 "getwindowsversion()\n\
515 Return information about the running version of Windows.\n\
516 The result is a tuple of (major, minor, build, platform, text)\n\
517 All elements are numbers, except text which is a string.\n\
518 Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
522 static PyObject *
523 sys_getwindowsversion(PyObject *self)
525 OSVERSIONINFO ver;
526 ver.dwOSVersionInfoSize = sizeof(ver);
527 if (!GetVersionEx(&ver))
528 return PyErr_SetFromWindowsErr(0);
529 return Py_BuildValue("HHHHs",
530 ver.dwMajorVersion,
531 ver.dwMinorVersion,
532 ver.dwBuildNumber,
533 ver.dwPlatformId,
534 ver.szCSDVersion);
537 #endif /* MS_WINDOWS */
539 #ifdef HAVE_DLOPEN
540 static PyObject *
541 sys_setdlopenflags(PyObject *self, PyObject *args)
543 int new_val;
544 PyThreadState *tstate = PyThreadState_GET();
545 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
546 return NULL;
547 if (!tstate)
548 return NULL;
549 tstate->interp->dlopenflags = new_val;
550 Py_INCREF(Py_None);
551 return Py_None;
554 PyDoc_STRVAR(setdlopenflags_doc,
555 "setdlopenflags(n) -> None\n\
557 Set the flags that will be used for dlopen() calls. Among other\n\
558 things, this will enable a lazy resolving of symbols when importing\n\
559 a module, if called as sys.setdlopenflags(0)\n\
560 To share symbols across extension modules, call as\n\
561 sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
564 static PyObject *
565 sys_getdlopenflags(PyObject *self, PyObject *args)
567 PyThreadState *tstate = PyThreadState_GET();
568 if (!tstate)
569 return NULL;
570 return PyInt_FromLong(tstate->interp->dlopenflags);
573 PyDoc_STRVAR(getdlopenflags_doc,
574 "getdlopenflags() -> int\n\
576 Return the current value of the flags that are used for dlopen()\n\
577 calls. The flag constants are defined in the dl module."
579 #endif
581 #ifdef USE_MALLOPT
582 /* Link with -lmalloc (or -lmpc) on an SGI */
583 #include <malloc.h>
585 static PyObject *
586 sys_mdebug(PyObject *self, PyObject *args)
588 int flag;
589 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
590 return NULL;
591 mallopt(M_DEBUG, flag);
592 Py_INCREF(Py_None);
593 return Py_None;
595 #endif /* USE_MALLOPT */
597 static PyObject *
598 sys_getrefcount(PyObject *self, PyObject *arg)
600 return PyInt_FromSsize_t(arg->ob_refcnt);
603 #ifdef Py_REF_DEBUG
604 static PyObject *
605 sys_gettotalrefcount(PyObject *self)
607 return PyInt_FromSsize_t(_Py_GetRefTotal());
609 #endif /* Py_REF_DEBUG */
611 PyDoc_STRVAR(getrefcount_doc,
612 "getrefcount(object) -> integer\n\
614 Return the reference count of object. The count returned is generally\n\
615 one higher than you might expect, because it includes the (temporary)\n\
616 reference as an argument to getrefcount()."
619 #ifdef COUNT_ALLOCS
620 static PyObject *
621 sys_getcounts(PyObject *self)
623 extern PyObject *get_counts(void);
625 return get_counts();
627 #endif
629 PyDoc_STRVAR(getframe_doc,
630 "_getframe([depth]) -> frameobject\n\
632 Return a frame object from the call stack. If optional integer depth is\n\
633 given, return the frame object that many calls below the top of the stack.\n\
634 If that is deeper than the call stack, ValueError is raised. The default\n\
635 for depth is zero, returning the frame at the top of the call stack.\n\
637 This function should be used for internal and specialized\n\
638 purposes only."
641 static PyObject *
642 sys_getframe(PyObject *self, PyObject *args)
644 PyFrameObject *f = PyThreadState_GET()->frame;
645 int depth = -1;
647 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
648 return NULL;
650 while (depth > 0 && f != NULL) {
651 f = f->f_back;
652 --depth;
654 if (f == NULL) {
655 PyErr_SetString(PyExc_ValueError,
656 "call stack is not deep enough");
657 return NULL;
659 Py_INCREF(f);
660 return (PyObject*)f;
663 PyDoc_STRVAR(call_tracing_doc,
664 "call_tracing(func, args) -> object\n\
666 Call func(*args), while tracing is enabled. The tracing state is\n\
667 saved, and restored afterwards. This is intended to be called from\n\
668 a debugger from a checkpoint, to recursively debug some other code."
671 static PyObject *
672 sys_call_tracing(PyObject *self, PyObject *args)
674 PyObject *func, *funcargs;
675 if (!PyArg_UnpackTuple(args, "call_tracing", 2, 2, &func, &funcargs))
676 return NULL;
677 return _PyEval_CallTracing(func, funcargs);
680 PyDoc_STRVAR(callstats_doc,
681 "callstats() -> tuple of integers\n\
683 Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
684 when Python was built. Otherwise, return None.\n\
686 When enabled, this function returns detailed, implementation-specific\n\
687 details about the number of function calls executed. The return value is\n\
688 a 11-tuple where the entries in the tuple are counts of:\n\
689 0. all function calls\n\
690 1. calls to PyFunction_Type objects\n\
691 2. PyFunction calls that do not create an argument tuple\n\
692 3. PyFunction calls that do not create an argument tuple\n\
693 and bypass PyEval_EvalCodeEx()\n\
694 4. PyMethod calls\n\
695 5. PyMethod calls on bound methods\n\
696 6. PyType calls\n\
697 7. PyCFunction calls\n\
698 8. generator calls\n\
699 9. All other calls\n\
700 10. Number of stack pops performed by call_function()"
703 #ifdef __cplusplus
704 extern "C" {
705 #endif
707 #ifdef Py_TRACE_REFS
708 /* Defined in objects.c because it uses static globals if that file */
709 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
710 #endif
712 #ifdef DYNAMIC_EXECUTION_PROFILE
713 /* Defined in ceval.c because it uses static globals if that file */
714 extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
715 #endif
717 #ifdef __cplusplus
719 #endif
721 static PyMethodDef sys_methods[] = {
722 /* Might as well keep this in alphabetic order */
723 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
724 callstats_doc},
725 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
726 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
727 {"exc_clear", sys_exc_clear, METH_NOARGS, exc_clear_doc},
728 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
729 {"exit", sys_exit, METH_VARARGS, exit_doc},
730 #ifdef Py_USING_UNICODE
731 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
732 METH_NOARGS, getdefaultencoding_doc},
733 #endif
734 #ifdef HAVE_DLOPEN
735 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
736 getdlopenflags_doc},
737 #endif
738 #ifdef COUNT_ALLOCS
739 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
740 #endif
741 #ifdef DYNAMIC_EXECUTION_PROFILE
742 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
743 #endif
744 #ifdef Py_USING_UNICODE
745 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
746 METH_NOARGS, getfilesystemencoding_doc},
747 #endif
748 #ifdef Py_TRACE_REFS
749 {"getobjects", _Py_GetObjects, METH_VARARGS},
750 #endif
751 #ifdef Py_REF_DEBUG
752 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
753 #endif
754 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
755 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
756 getrecursionlimit_doc},
757 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
758 #ifdef MS_WINDOWS
759 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
760 getwindowsversion_doc},
761 #endif /* MS_WINDOWS */
762 #ifdef USE_MALLOPT
763 {"mdebug", sys_mdebug, METH_VARARGS},
764 #endif
765 #ifdef Py_USING_UNICODE
766 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
767 setdefaultencoding_doc},
768 #endif
769 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
770 setcheckinterval_doc},
771 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
772 getcheckinterval_doc},
773 #ifdef HAVE_DLOPEN
774 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
775 setdlopenflags_doc},
776 #endif
777 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
778 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
779 setrecursionlimit_doc},
780 #ifdef WITH_TSC
781 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
782 #endif
783 {"settrace", sys_settrace, METH_O, settrace_doc},
784 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
785 {NULL, NULL} /* sentinel */
788 static PyObject *
789 list_builtin_module_names(void)
791 PyObject *list = PyList_New(0);
792 int i;
793 if (list == NULL)
794 return NULL;
795 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
796 PyObject *name = PyString_FromString(
797 PyImport_Inittab[i].name);
798 if (name == NULL)
799 break;
800 PyList_Append(list, name);
801 Py_DECREF(name);
803 if (PyList_Sort(list) != 0) {
804 Py_DECREF(list);
805 list = NULL;
807 if (list) {
808 PyObject *v = PyList_AsTuple(list);
809 Py_DECREF(list);
810 list = v;
812 return list;
815 static PyObject *warnoptions = NULL;
817 void
818 PySys_ResetWarnOptions(void)
820 if (warnoptions == NULL || !PyList_Check(warnoptions))
821 return;
822 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
825 void
826 PySys_AddWarnOption(char *s)
828 PyObject *str;
830 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
831 Py_XDECREF(warnoptions);
832 warnoptions = PyList_New(0);
833 if (warnoptions == NULL)
834 return;
836 str = PyString_FromString(s);
837 if (str != NULL) {
838 PyList_Append(warnoptions, str);
839 Py_DECREF(str);
843 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
844 Two literals concatenated works just fine. If you have a K&R compiler
845 or other abomination that however *does* understand longer strings,
846 get rid of the !!! comment in the middle and the quotes that surround it. */
847 PyDoc_VAR(sys_doc) =
848 PyDoc_STR(
849 "This module provides access to some objects used or maintained by the\n\
850 interpreter and to functions that interact strongly with the interpreter.\n\
852 Dynamic objects:\n\
854 argv -- command line arguments; argv[0] is the script pathname if known\n\
855 path -- module search path; path[0] is the script directory, else ''\n\
856 modules -- dictionary of loaded modules\n\
858 displayhook -- called to show results in an interactive session\n\
859 excepthook -- called to handle any uncaught exception other than SystemExit\n\
860 To customize printing in an interactive session or to install a custom\n\
861 top-level exception handler, assign other functions to replace these.\n\
863 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
864 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
866 stdin -- standard input file object; used by raw_input() and input()\n\
867 stdout -- standard output file object; used by the print statement\n\
868 stderr -- standard error object; used for error messages\n\
869 By assigning other file objects (or objects that behave like files)\n\
870 to these, it is possible to redirect all of the interpreter's I/O.\n\
872 last_type -- type of last uncaught exception\n\
873 last_value -- value of last uncaught exception\n\
874 last_traceback -- traceback of last uncaught exception\n\
875 These three are only available in an interactive session after a\n\
876 traceback has been printed.\n\
878 exc_type -- type of exception currently being handled\n\
879 exc_value -- value of exception currently being handled\n\
880 exc_traceback -- traceback of exception currently being handled\n\
881 The function exc_info() should be used instead of these three,\n\
882 because it is thread-safe.\n\
885 /* concatenating string here */
886 PyDoc_STR(
887 "\n\
888 Static objects:\n\
890 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
891 maxunicode -- the largest supported character\n\
892 builtin_module_names -- tuple of module names built into this interpreter\n\
893 version -- the version of this interpreter as a string\n\
894 version_info -- version information as a tuple\n\
895 hexversion -- version information encoded as a single integer\n\
896 copyright -- copyright notice pertaining to this interpreter\n\
897 platform -- platform identifier\n\
898 executable -- pathname of this Python interpreter\n\
899 prefix -- prefix used to find the Python library\n\
900 exec_prefix -- prefix used to find the machine-specific Python library\n\
903 #ifdef MS_WINDOWS
904 /* concatenating string here */
905 PyDoc_STR(
906 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
907 winver -- [Windows only] version number of the Python DLL\n\
910 #endif /* MS_WINDOWS */
911 PyDoc_STR(
912 "__stdin__ -- the original stdin; don't touch!\n\
913 __stdout__ -- the original stdout; don't touch!\n\
914 __stderr__ -- the original stderr; don't touch!\n\
915 __displayhook__ -- the original displayhook; don't touch!\n\
916 __excepthook__ -- the original excepthook; don't touch!\n\
918 Functions:\n\
920 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
921 excepthook() -- print an exception and its traceback to sys.stderr\n\
922 exc_info() -- return thread-safe information about the current exception\n\
923 exc_clear() -- clear the exception state for the current thread\n\
924 exit() -- exit the interpreter by raising SystemExit\n\
925 getdlopenflags() -- returns flags to be used for dlopen() calls\n\
926 getrefcount() -- return the reference count for an object (plus one :-)\n\
927 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
928 setcheckinterval() -- control how often the interpreter checks for events\n\
929 setdlopenflags() -- set the flags to be used for dlopen() calls\n\
930 setprofile() -- set the global profiling function\n\
931 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
932 settrace() -- set the global debug tracing function\n\
935 /* end of sys_doc */ ;
937 static int
938 _check_and_flush (FILE *stream)
940 int prev_fail = ferror (stream);
941 return fflush (stream) || prev_fail ? EOF : 0;
944 /* Subversion branch and revision management */
945 static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION;
946 static const char headurl[] = "$HeadURL$";
947 static int svn_initialized;
948 static char patchlevel_revision[50]; /* Just the number */
949 static char branch[50];
950 static char shortbranch[50];
951 static const char *svn_revision;
953 static void
954 svnversion_init(void)
956 const char *python, *br_start, *br_end, *br_end2, *svnversion;
957 Py_ssize_t len;
958 int istag;
960 if (svn_initialized)
961 return;
963 python = strstr(headurl, "/python/");
964 if (!python)
965 Py_FatalError("subversion keywords missing");
967 br_start = python + 8;
968 br_end = strchr(br_start, '/');
969 /* Works even for trunk,
970 as we are in trunk/Python/sysmodule.c */
971 br_end2 = strchr(br_end+1, '/');
973 istag = strncmp(br_start, "tags", 4) == 0;
974 if (strncmp(br_start, "trunk", 5) == 0) {
975 strcpy(branch, "trunk");
976 strcpy(shortbranch, "trunk");
979 else if (istag || strncmp(br_start, "branches", 8) == 0) {
980 len = br_end2 - br_start;
981 strncpy(branch, br_start, len);
982 branch[len] = '\0';
984 len = br_end2 - (br_end + 1);
985 strncpy(shortbranch, br_end + 1, len);
986 shortbranch[len] = '\0';
988 else {
989 Py_FatalError("bad HeadURL");
990 return;
994 svnversion = _Py_svnversion();
995 if (strcmp(svnversion, "exported") != 0)
996 svn_revision = svnversion;
997 else if (istag) {
998 len = strlen(_patchlevel_revision);
999 strncpy(patchlevel_revision, _patchlevel_revision + 11,
1000 len - 13);
1001 patchlevel_revision[len - 13] = '\0';
1002 svn_revision = patchlevel_revision;
1004 else
1005 svn_revision = "";
1007 svn_initialized = 1;
1010 /* Return svnversion output if available.
1011 Else return Revision of patchlevel.h if on branch.
1012 Else return empty string */
1013 const char*
1014 Py_SubversionRevision()
1016 svnversion_init();
1017 return svn_revision;
1020 const char*
1021 Py_SubversionShortBranch()
1023 svnversion_init();
1024 return shortbranch;
1027 PyObject *
1028 _PySys_Init(void)
1030 PyObject *m, *v, *sysdict;
1031 PyObject *sysin, *sysout, *syserr;
1032 char *s;
1033 #ifdef MS_WINDOWS
1034 char buf[128];
1035 #endif
1037 m = Py_InitModule3("sys", sys_methods, sys_doc);
1038 if (m == NULL)
1039 return NULL;
1040 sysdict = PyModule_GetDict(m);
1043 /* XXX: does this work on Win/Win64? (see posix_fstat) */
1044 struct stat sb;
1045 if (fstat(fileno(stdin), &sb) == 0 &&
1046 S_ISDIR(sb.st_mode)) {
1047 /* There's nothing more we can do. */
1048 /* Py_FatalError() will core dump, so just exit. */
1049 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1050 exit(EXIT_FAILURE);
1054 /* Closing the standard FILE* if sys.std* goes aways causes problems
1055 * for embedded Python usages. Closing them when somebody explicitly
1056 * invokes .close() might be possible, but the FAQ promises they get
1057 * never closed. However, we still need to get write errors when
1058 * writing fails (e.g. because stdout is redirected), so we flush the
1059 * streams and check for errors before the file objects are deleted.
1060 * On OS X, fflush()ing stdin causes an error, so we exempt stdin
1061 * from that procedure.
1063 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
1064 sysout = PyFile_FromFile(stdout, "<stdout>", "w", _check_and_flush);
1065 syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);
1066 if (PyErr_Occurred())
1067 return NULL;
1068 #ifdef MS_WINDOWS
1069 if(isatty(_fileno(stdin))){
1070 sprintf(buf, "cp%d", GetConsoleCP());
1071 if (!PyFile_SetEncoding(sysin, buf))
1072 return NULL;
1074 if(isatty(_fileno(stdout))) {
1075 sprintf(buf, "cp%d", GetConsoleOutputCP());
1076 if (!PyFile_SetEncoding(sysout, buf))
1077 return NULL;
1079 if(isatty(_fileno(stderr))) {
1080 sprintf(buf, "cp%d", GetConsoleOutputCP());
1081 if (!PyFile_SetEncoding(syserr, buf))
1082 return NULL;
1084 #endif
1086 PyDict_SetItemString(sysdict, "stdin", sysin);
1087 PyDict_SetItemString(sysdict, "stdout", sysout);
1088 PyDict_SetItemString(sysdict, "stderr", syserr);
1089 /* Make backup copies for cleanup */
1090 PyDict_SetItemString(sysdict, "__stdin__", sysin);
1091 PyDict_SetItemString(sysdict, "__stdout__", sysout);
1092 PyDict_SetItemString(sysdict, "__stderr__", syserr);
1093 PyDict_SetItemString(sysdict, "__displayhook__",
1094 PyDict_GetItemString(sysdict, "displayhook"));
1095 PyDict_SetItemString(sysdict, "__excepthook__",
1096 PyDict_GetItemString(sysdict, "excepthook"));
1097 Py_XDECREF(sysin);
1098 Py_XDECREF(sysout);
1099 Py_XDECREF(syserr);
1100 PyDict_SetItemString(sysdict, "version",
1101 v = PyString_FromString(Py_GetVersion()));
1102 Py_XDECREF(v);
1103 PyDict_SetItemString(sysdict, "hexversion",
1104 v = PyInt_FromLong(PY_VERSION_HEX));
1105 Py_XDECREF(v);
1106 svnversion_init();
1107 v = Py_BuildValue("(ssz)", "CPython", branch, svn_revision);
1108 PyDict_SetItemString(sysdict, "subversion", v);
1109 Py_XDECREF(v);
1111 * These release level checks are mutually exclusive and cover
1112 * the field, so don't get too fancy with the pre-processor!
1114 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
1115 s = "alpha";
1116 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
1117 s = "beta";
1118 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
1119 s = "candidate";
1120 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
1121 s = "final";
1122 #endif
1123 PyDict_SetItemString(sysdict, "version_info",
1124 v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
1125 PY_MINOR_VERSION,
1126 PY_MICRO_VERSION, s,
1127 PY_RELEASE_SERIAL));
1128 Py_XDECREF(v);
1129 PyDict_SetItemString(sysdict, "api_version",
1130 v = PyInt_FromLong(PYTHON_API_VERSION));
1131 Py_XDECREF(v);
1132 PyDict_SetItemString(sysdict, "copyright",
1133 v = PyString_FromString(Py_GetCopyright()));
1134 Py_XDECREF(v);
1135 PyDict_SetItemString(sysdict, "platform",
1136 v = PyString_FromString(Py_GetPlatform()));
1137 Py_XDECREF(v);
1138 PyDict_SetItemString(sysdict, "executable",
1139 v = PyString_FromString(Py_GetProgramFullPath()));
1140 Py_XDECREF(v);
1141 PyDict_SetItemString(sysdict, "prefix",
1142 v = PyString_FromString(Py_GetPrefix()));
1143 Py_XDECREF(v);
1144 PyDict_SetItemString(sysdict, "exec_prefix",
1145 v = PyString_FromString(Py_GetExecPrefix()));
1146 Py_XDECREF(v);
1147 PyDict_SetItemString(sysdict, "maxint",
1148 v = PyInt_FromLong(PyInt_GetMax()));
1149 Py_XDECREF(v);
1150 #ifdef Py_USING_UNICODE
1151 PyDict_SetItemString(sysdict, "maxunicode",
1152 v = PyInt_FromLong(PyUnicode_GetMax()));
1153 Py_XDECREF(v);
1154 #endif
1155 PyDict_SetItemString(sysdict, "builtin_module_names",
1156 v = list_builtin_module_names());
1157 Py_XDECREF(v);
1159 /* Assumes that longs are at least 2 bytes long.
1160 Should be safe! */
1161 unsigned long number = 1;
1162 char *value;
1164 s = (char *) &number;
1165 if (s[0] == 0)
1166 value = "big";
1167 else
1168 value = "little";
1169 PyDict_SetItemString(sysdict, "byteorder",
1170 v = PyString_FromString(value));
1171 Py_XDECREF(v);
1173 #ifdef MS_COREDLL
1174 PyDict_SetItemString(sysdict, "dllhandle",
1175 v = PyLong_FromVoidPtr(PyWin_DLLhModule));
1176 Py_XDECREF(v);
1177 PyDict_SetItemString(sysdict, "winver",
1178 v = PyString_FromString(PyWin_DLLVersionString));
1179 Py_XDECREF(v);
1180 #endif
1181 if (warnoptions == NULL) {
1182 warnoptions = PyList_New(0);
1184 else {
1185 Py_INCREF(warnoptions);
1187 if (warnoptions != NULL) {
1188 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1191 if (PyErr_Occurred())
1192 return NULL;
1193 return m;
1196 static PyObject *
1197 makepathobject(char *path, int delim)
1199 int i, n;
1200 char *p;
1201 PyObject *v, *w;
1203 n = 1;
1204 p = path;
1205 while ((p = strchr(p, delim)) != NULL) {
1206 n++;
1207 p++;
1209 v = PyList_New(n);
1210 if (v == NULL)
1211 return NULL;
1212 for (i = 0; ; i++) {
1213 p = strchr(path, delim);
1214 if (p == NULL)
1215 p = strchr(path, '\0'); /* End of string */
1216 w = PyString_FromStringAndSize(path, (int) (p - path));
1217 if (w == NULL) {
1218 Py_DECREF(v);
1219 return NULL;
1221 PyList_SetItem(v, i, w);
1222 if (*p == '\0')
1223 break;
1224 path = p+1;
1226 return v;
1229 void
1230 PySys_SetPath(char *path)
1232 PyObject *v;
1233 if ((v = makepathobject(path, DELIM)) == NULL)
1234 Py_FatalError("can't create sys.path");
1235 if (PySys_SetObject("path", v) != 0)
1236 Py_FatalError("can't assign sys.path");
1237 Py_DECREF(v);
1240 static PyObject *
1241 makeargvobject(int argc, char **argv)
1243 PyObject *av;
1244 if (argc <= 0 || argv == NULL) {
1245 /* Ensure at least one (empty) argument is seen */
1246 static char *empty_argv[1] = {""};
1247 argv = empty_argv;
1248 argc = 1;
1250 av = PyList_New(argc);
1251 if (av != NULL) {
1252 int i;
1253 for (i = 0; i < argc; i++) {
1254 #ifdef __VMS
1255 PyObject *v;
1257 /* argv[0] is the script pathname if known */
1258 if (i == 0) {
1259 char* fn = decc$translate_vms(argv[0]);
1260 if ((fn == (char *)0) || fn == (char *)-1)
1261 v = PyString_FromString(argv[0]);
1262 else
1263 v = PyString_FromString(
1264 decc$translate_vms(argv[0]));
1265 } else
1266 v = PyString_FromString(argv[i]);
1267 #else
1268 PyObject *v = PyString_FromString(argv[i]);
1269 #endif
1270 if (v == NULL) {
1271 Py_DECREF(av);
1272 av = NULL;
1273 break;
1275 PyList_SetItem(av, i, v);
1278 return av;
1281 void
1282 PySys_SetArgv(int argc, char **argv)
1284 #if defined(HAVE_REALPATH)
1285 char fullpath[MAXPATHLEN];
1286 #elif defined(MS_WINDOWS)
1287 char fullpath[MAX_PATH];
1288 #endif
1289 PyObject *av = makeargvobject(argc, argv);
1290 PyObject *path = PySys_GetObject("path");
1291 if (av == NULL)
1292 Py_FatalError("no mem for sys.argv");
1293 if (PySys_SetObject("argv", av) != 0)
1294 Py_FatalError("can't assign sys.argv");
1295 if (path != NULL) {
1296 char *argv0 = argv[0];
1297 char *p = NULL;
1298 Py_ssize_t n = 0;
1299 PyObject *a;
1300 #ifdef HAVE_READLINK
1301 char link[MAXPATHLEN+1];
1302 char argv0copy[2*MAXPATHLEN+1];
1303 int nr = 0;
1304 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)
1305 nr = readlink(argv0, link, MAXPATHLEN);
1306 if (nr > 0) {
1307 /* It's a symlink */
1308 link[nr] = '\0';
1309 if (link[0] == SEP)
1310 argv0 = link; /* Link to absolute path */
1311 else if (strchr(link, SEP) == NULL)
1312 ; /* Link without path */
1313 else {
1314 /* Must join(dirname(argv0), link) */
1315 char *q = strrchr(argv0, SEP);
1316 if (q == NULL)
1317 argv0 = link; /* argv0 without path */
1318 else {
1319 /* Must make a copy */
1320 strcpy(argv0copy, argv0);
1321 q = strrchr(argv0copy, SEP);
1322 strcpy(q+1, link);
1323 argv0 = argv0copy;
1327 #endif /* HAVE_READLINK */
1328 #if SEP == '\\' /* Special case for MS filename syntax */
1329 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
1330 char *q;
1331 #ifdef MS_WINDOWS
1332 char *ptemp;
1333 if (GetFullPathName(argv0,
1334 sizeof(fullpath),
1335 fullpath,
1336 &ptemp)) {
1337 argv0 = fullpath;
1339 #endif
1340 p = strrchr(argv0, SEP);
1341 /* Test for alternate separator */
1342 q = strrchr(p ? p : argv0, '/');
1343 if (q != NULL)
1344 p = q;
1345 if (p != NULL) {
1346 n = p + 1 - argv0;
1347 if (n > 1 && p[-1] != ':')
1348 n--; /* Drop trailing separator */
1351 #else /* All other filename syntaxes */
1352 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
1353 #if defined(HAVE_REALPATH)
1354 if (realpath(argv0, fullpath)) {
1355 argv0 = fullpath;
1357 #endif
1358 p = strrchr(argv0, SEP);
1360 if (p != NULL) {
1361 #ifndef RISCOS
1362 n = p + 1 - argv0;
1363 #else /* don't include trailing separator */
1364 n = p - argv0;
1365 #endif /* RISCOS */
1366 #if SEP == '/' /* Special case for Unix filename syntax */
1367 if (n > 1)
1368 n--; /* Drop trailing separator */
1369 #endif /* Unix */
1371 #endif /* All others */
1372 a = PyString_FromStringAndSize(argv0, n);
1373 if (a == NULL)
1374 Py_FatalError("no mem for sys.path insertion");
1375 if (PyList_Insert(path, 0, a) < 0)
1376 Py_FatalError("sys.path.insert(0) failed");
1377 Py_DECREF(a);
1379 Py_DECREF(av);
1383 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1384 Adapted from code submitted by Just van Rossum.
1386 PySys_WriteStdout(format, ...)
1387 PySys_WriteStderr(format, ...)
1389 The first function writes to sys.stdout; the second to sys.stderr. When
1390 there is a problem, they write to the real (C level) stdout or stderr;
1391 no exceptions are raised.
1393 Both take a printf-style format string as their first argument followed
1394 by a variable length argument list determined by the format string.
1396 *** WARNING ***
1398 The format should limit the total size of the formatted output string to
1399 1000 bytes. In particular, this means that no unrestricted "%s" formats
1400 should occur; these should be limited using "%.<N>s where <N> is a
1401 decimal number calculated so that <N> plus the maximum size of other
1402 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1403 which can print hundreds of digits for very large numbers.
1407 static void
1408 mywrite(char *name, FILE *fp, const char *format, va_list va)
1410 PyObject *file;
1411 PyObject *error_type, *error_value, *error_traceback;
1413 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1414 file = PySys_GetObject(name);
1415 if (file == NULL || PyFile_AsFile(file) == fp)
1416 vfprintf(fp, format, va);
1417 else {
1418 char buffer[1001];
1419 const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
1420 format, va);
1421 if (PyFile_WriteString(buffer, file) != 0) {
1422 PyErr_Clear();
1423 fputs(buffer, fp);
1425 if (written < 0 || (size_t)written >= sizeof(buffer)) {
1426 const char *truncated = "... truncated";
1427 if (PyFile_WriteString(truncated, file) != 0) {
1428 PyErr_Clear();
1429 fputs(truncated, fp);
1433 PyErr_Restore(error_type, error_value, error_traceback);
1436 void
1437 PySys_WriteStdout(const char *format, ...)
1439 va_list va;
1441 va_start(va, format);
1442 mywrite("stdout", stdout, format, va);
1443 va_end(va);
1446 void
1447 PySys_WriteStderr(const char *format, ...)
1449 va_list va;
1451 va_start(va, format);
1452 mywrite("stderr", stderr, format, va);
1453 va_end(va);