5 Various bits of information used by the interpreter are collected in
8 - exit(sts): raise SystemExit
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)
18 #include "structseq.h"
20 #include "frameobject.h"
26 #define WIN32_LEAN_AND_MEAN
28 #endif /* MS_WINDOWS */
31 extern void *PyWin_DLLhModule
;
32 /* A string loaded from the DLL at startup: */
33 extern const char *PyWin_DLLVersionString
;
44 #ifdef HAVE_LANGINFO_H
50 PySys_GetObject(char *name
)
52 PyThreadState
*tstate
= PyThreadState_GET();
53 PyObject
*sd
= tstate
->interp
->sysdict
;
56 return PyDict_GetItemString(sd
, name
);
60 PySys_GetFile(char *name
, FILE *def
)
63 PyObject
*v
= PySys_GetObject(name
);
64 if (v
!= NULL
&& PyFile_Check(v
))
65 fp
= PyFile_AsFile(v
);
72 PySys_SetObject(char *name
, PyObject
*v
)
74 PyThreadState
*tstate
= PyThreadState_GET();
75 PyObject
*sd
= tstate
->interp
->sysdict
;
77 if (PyDict_GetItemString(sd
, name
) == NULL
)
80 return PyDict_DelItemString(sd
, name
);
83 return PyDict_SetItemString(sd
, name
, v
);
87 sys_displayhook(PyObject
*self
, PyObject
*o
)
90 PyInterpreterState
*interp
= PyThreadState_GET()->interp
;
91 PyObject
*modules
= interp
->modules
;
92 PyObject
*builtins
= PyDict_GetItemString(modules
, "__builtin__");
94 if (builtins
== NULL
) {
95 PyErr_SetString(PyExc_RuntimeError
, "lost __builtin__");
99 /* Print value except if None */
100 /* After printing, also assign to '_' */
101 /* Before, set '_' to None to avoid recursion */
106 if (PyObject_SetAttrString(builtins
, "_", Py_None
) != 0)
108 if (Py_FlushLine() != 0)
110 outf
= PySys_GetObject("stdout");
112 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
115 if (PyFile_WriteObject(o
, outf
, 0) != 0)
117 PyFile_SoftSpace(outf
, 1);
118 if (Py_FlushLine() != 0)
120 if (PyObject_SetAttrString(builtins
, "_", o
) != 0)
126 PyDoc_STRVAR(displayhook_doc
,
127 "displayhook(object) -> None\n"
129 "Print an object to sys.stdout and also save it in __builtin__.\n"
133 sys_excepthook(PyObject
* self
, PyObject
* args
)
135 PyObject
*exc
, *value
, *tb
;
136 if (!PyArg_UnpackTuple(args
, "excepthook", 3, 3, &exc
, &value
, &tb
))
138 PyErr_Display(exc
, value
, tb
);
143 PyDoc_STRVAR(excepthook_doc
,
144 "excepthook(exctype, value, traceback) -> None\n"
146 "Handle an exception by displaying it with a traceback on sys.stderr.\n"
150 sys_exc_info(PyObject
*self
, PyObject
*noargs
)
152 PyThreadState
*tstate
;
153 tstate
= PyThreadState_GET();
154 return Py_BuildValue(
156 tstate
->exc_type
!= NULL
? tstate
->exc_type
: Py_None
,
157 tstate
->exc_value
!= NULL
? tstate
->exc_value
: Py_None
,
158 tstate
->exc_traceback
!= NULL
?
159 tstate
->exc_traceback
: Py_None
);
162 PyDoc_STRVAR(exc_info_doc
,
163 "exc_info() -> (type, value, traceback)\n\
165 Return information about the most recent exception caught by an except\n\
166 clause in the current stack frame or in an older stack frame."
170 sys_exc_clear(PyObject
*self
, PyObject
*noargs
)
172 PyThreadState
*tstate
;
173 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
175 if (Py_Py3kWarningFlag
&&
176 PyErr_Warn(PyExc_DeprecationWarning
,
177 "sys.exc_clear() not supported in 3.x; "
178 "use except clauses") < 0)
181 tstate
= PyThreadState_GET();
182 tmp_type
= tstate
->exc_type
;
183 tmp_value
= tstate
->exc_value
;
184 tmp_tb
= tstate
->exc_traceback
;
185 tstate
->exc_type
= NULL
;
186 tstate
->exc_value
= NULL
;
187 tstate
->exc_traceback
= NULL
;
188 Py_XDECREF(tmp_type
);
189 Py_XDECREF(tmp_value
);
191 /* For b/w compatibility */
192 PySys_SetObject("exc_type", Py_None
);
193 PySys_SetObject("exc_value", Py_None
);
194 PySys_SetObject("exc_traceback", Py_None
);
199 PyDoc_STRVAR(exc_clear_doc
,
200 "exc_clear() -> None\n\
202 Clear global information on the current exception. Subsequent calls to\n\
203 exc_info() will return (None,None,None) until another exception is raised\n\
204 in the current thread or the execution stack returns to a frame where\n\
205 another exception is being handled."
209 sys_exit(PyObject
*self
, PyObject
*args
)
211 PyObject
*exit_code
= 0;
212 if (!PyArg_UnpackTuple(args
, "exit", 0, 1, &exit_code
))
214 /* Raise SystemExit so callers may catch it or clean up. */
215 PyErr_SetObject(PyExc_SystemExit
, exit_code
);
219 PyDoc_STRVAR(exit_doc
,
222 Exit the interpreter by raising SystemExit(status).\n\
223 If the status is omitted or None, it defaults to zero (i.e., success).\n\
224 If the status is numeric, it will be used as the system exit status.\n\
225 If it is another kind of object, it will be printed and the system\n\
226 exit status will be one (i.e., failure)."
229 #ifdef Py_USING_UNICODE
232 sys_getdefaultencoding(PyObject
*self
)
234 return PyString_FromString(PyUnicode_GetDefaultEncoding());
237 PyDoc_STRVAR(getdefaultencoding_doc
,
238 "getdefaultencoding() -> string\n\
240 Return the current default string encoding used by the Unicode \n\
245 sys_setdefaultencoding(PyObject
*self
, PyObject
*args
)
248 if (!PyArg_ParseTuple(args
, "s:setdefaultencoding", &encoding
))
250 if (PyUnicode_SetDefaultEncoding(encoding
))
256 PyDoc_STRVAR(setdefaultencoding_doc
,
257 "setdefaultencoding(encoding)\n\
259 Set the current default string encoding used by the Unicode implementation."
263 sys_getfilesystemencoding(PyObject
*self
)
265 if (Py_FileSystemDefaultEncoding
)
266 return PyString_FromString(Py_FileSystemDefaultEncoding
);
271 PyDoc_STRVAR(getfilesystemencoding_doc
,
272 "getfilesystemencoding() -> string\n\
274 Return the encoding used to convert Unicode filenames in\n\
275 operating system filenames."
281 * Cached interned string objects used for calling the profile and
282 * trace functions. Initialized by trace_init().
284 static PyObject
*whatstrings
[7] = {NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
};
289 static char *whatnames
[7] = {"call", "exception", "line", "return",
290 "c_call", "c_exception", "c_return"};
293 for (i
= 0; i
< 7; ++i
) {
294 if (whatstrings
[i
] == NULL
) {
295 name
= PyString_InternFromString(whatnames
[i
]);
298 whatstrings
[i
] = name
;
306 call_trampoline(PyThreadState
*tstate
, PyObject
* callback
,
307 PyFrameObject
*frame
, int what
, PyObject
*arg
)
309 PyObject
*args
= PyTuple_New(3);
316 whatstr
= whatstrings
[what
];
321 PyTuple_SET_ITEM(args
, 0, (PyObject
*)frame
);
322 PyTuple_SET_ITEM(args
, 1, whatstr
);
323 PyTuple_SET_ITEM(args
, 2, arg
);
325 /* call the Python-level function */
326 PyFrame_FastToLocals(frame
);
327 result
= PyEval_CallObject(callback
, args
);
328 PyFrame_LocalsToFast(frame
, 1);
330 PyTraceBack_Here(frame
);
338 profile_trampoline(PyObject
*self
, PyFrameObject
*frame
,
339 int what
, PyObject
*arg
)
341 PyThreadState
*tstate
= frame
->f_tstate
;
346 result
= call_trampoline(tstate
, self
, frame
, what
, arg
);
347 if (result
== NULL
) {
348 PyEval_SetProfile(NULL
, NULL
);
356 trace_trampoline(PyObject
*self
, PyFrameObject
*frame
,
357 int what
, PyObject
*arg
)
359 PyThreadState
*tstate
= frame
->f_tstate
;
363 if (what
== PyTrace_CALL
)
366 callback
= frame
->f_trace
;
367 if (callback
== NULL
)
369 result
= call_trampoline(tstate
, callback
, frame
, what
, arg
);
370 if (result
== NULL
) {
371 PyEval_SetTrace(NULL
, NULL
);
372 Py_XDECREF(frame
->f_trace
);
373 frame
->f_trace
= NULL
;
376 if (result
!= Py_None
) {
377 PyObject
*temp
= frame
->f_trace
;
378 frame
->f_trace
= NULL
;
380 frame
->f_trace
= result
;
389 sys_settrace(PyObject
*self
, PyObject
*args
)
391 if (trace_init() == -1)
394 PyEval_SetTrace(NULL
, NULL
);
396 PyEval_SetTrace(trace_trampoline
, args
);
401 PyDoc_STRVAR(settrace_doc
,
402 "settrace(function)\n\
404 Set the global debug tracing function. It will be called on each\n\
405 function call. See the debugger chapter in the library manual."
409 sys_gettrace(PyObject
*self
, PyObject
*args
)
411 PyThreadState
*tstate
= PyThreadState_GET();
412 PyObject
*temp
= tstate
->c_traceobj
;
420 PyDoc_STRVAR(gettrace_doc
,
423 Return the global debug tracing function set with sys.settrace.\n\
424 See the debugger chapter in the library manual."
428 sys_setprofile(PyObject
*self
, PyObject
*args
)
430 if (trace_init() == -1)
433 PyEval_SetProfile(NULL
, NULL
);
435 PyEval_SetProfile(profile_trampoline
, args
);
440 PyDoc_STRVAR(setprofile_doc
,
441 "setprofile(function)\n\
443 Set the profiling function. It will be called on each function call\n\
444 and return. See the profiler chapter in the library manual."
448 sys_getprofile(PyObject
*self
, PyObject
*args
)
450 PyThreadState
*tstate
= PyThreadState_GET();
451 PyObject
*temp
= tstate
->c_profileobj
;
459 PyDoc_STRVAR(getprofile_doc
,
462 Return the profiling function set with sys.setprofile.\n\
463 See the profiler chapter in the library manual."
467 sys_setcheckinterval(PyObject
*self
, PyObject
*args
)
469 if (!PyArg_ParseTuple(args
, "i:setcheckinterval", &_Py_CheckInterval
))
475 PyDoc_STRVAR(setcheckinterval_doc
,
476 "setcheckinterval(n)\n\
478 Tell the Python interpreter to check for asynchronous events every\n\
479 n instructions. This also affects how often thread switches occur."
483 sys_getcheckinterval(PyObject
*self
, PyObject
*args
)
485 return PyInt_FromLong(_Py_CheckInterval
);
488 PyDoc_STRVAR(getcheckinterval_doc
,
489 "getcheckinterval() -> current check interval; see setcheckinterval()."
494 sys_settscdump(PyObject
*self
, PyObject
*args
)
497 PyThreadState
*tstate
= PyThreadState_Get();
499 if (!PyArg_ParseTuple(args
, "i:settscdump", &bool))
502 tstate
->interp
->tscdump
= 1;
504 tstate
->interp
->tscdump
= 0;
510 PyDoc_STRVAR(settscdump_doc
,
513 If true, tell the Python interpreter to dump VM measurements to\n\
514 stderr. If false, turn off dump. The measurements are based on the\n\
515 processor's time-stamp counter."
520 sys_setrecursionlimit(PyObject
*self
, PyObject
*args
)
523 if (!PyArg_ParseTuple(args
, "i:setrecursionlimit", &new_limit
))
525 if (new_limit
<= 0) {
526 PyErr_SetString(PyExc_ValueError
,
527 "recursion limit must be positive");
530 Py_SetRecursionLimit(new_limit
);
535 PyDoc_STRVAR(setrecursionlimit_doc
,
536 "setrecursionlimit(n)\n\
538 Set the maximum depth of the Python interpreter stack to n. This\n\
539 limit prevents infinite recursion from causing an overflow of the C\n\
540 stack and crashing Python. The highest possible limit is platform-\n\
545 sys_getrecursionlimit(PyObject
*self
)
547 return PyInt_FromLong(Py_GetRecursionLimit());
550 PyDoc_STRVAR(getrecursionlimit_doc
,
551 "getrecursionlimit()\n\
553 Return the current value of the recursion limit, the maximum depth\n\
554 of the Python interpreter stack. This limit prevents infinite\n\
555 recursion from causing an overflow of the C stack and crashing Python."
559 PyDoc_STRVAR(getwindowsversion_doc
,
560 "getwindowsversion()\n\
562 Return information about the running version of Windows.\n\
563 The result is a tuple of (major, minor, build, platform, text)\n\
564 All elements are numbers, except text which is a string.\n\
565 Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
570 sys_getwindowsversion(PyObject
*self
)
573 ver
.dwOSVersionInfoSize
= sizeof(ver
);
574 if (!GetVersionEx(&ver
))
575 return PyErr_SetFromWindowsErr(0);
576 return Py_BuildValue("HHHHs",
584 #endif /* MS_WINDOWS */
588 sys_setdlopenflags(PyObject
*self
, PyObject
*args
)
591 PyThreadState
*tstate
= PyThreadState_GET();
592 if (!PyArg_ParseTuple(args
, "i:setdlopenflags", &new_val
))
596 tstate
->interp
->dlopenflags
= new_val
;
601 PyDoc_STRVAR(setdlopenflags_doc
,
602 "setdlopenflags(n) -> None\n\
604 Set the flags that will be used for dlopen() calls. Among other\n\
605 things, this will enable a lazy resolving of symbols when importing\n\
606 a module, if called as sys.setdlopenflags(0)\n\
607 To share symbols across extension modules, call as\n\
608 sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
612 sys_getdlopenflags(PyObject
*self
, PyObject
*args
)
614 PyThreadState
*tstate
= PyThreadState_GET();
617 return PyInt_FromLong(tstate
->interp
->dlopenflags
);
620 PyDoc_STRVAR(getdlopenflags_doc
,
621 "getdlopenflags() -> int\n\
623 Return the current value of the flags that are used for dlopen()\n\
624 calls. The flag constants are defined in the dl module."
629 /* Link with -lmalloc (or -lmpc) on an SGI */
633 sys_mdebug(PyObject
*self
, PyObject
*args
)
636 if (!PyArg_ParseTuple(args
, "i:mdebug", &flag
))
638 mallopt(M_DEBUG
, flag
);
642 #endif /* USE_MALLOPT */
645 sys_getrefcount(PyObject
*self
, PyObject
*arg
)
647 return PyInt_FromSsize_t(arg
->ob_refcnt
);
652 sys_gettotalrefcount(PyObject
*self
)
654 return PyInt_FromSsize_t(_Py_GetRefTotal());
656 #endif /* Py_REF_DEBUG */
658 PyDoc_STRVAR(getrefcount_doc
,
659 "getrefcount(object) -> integer\n\
661 Return the reference count of object. The count returned is generally\n\
662 one higher than you might expect, because it includes the (temporary)\n\
663 reference as an argument to getrefcount()."
668 sys_getcounts(PyObject
*self
)
670 extern PyObject
*get_counts(void);
676 PyDoc_STRVAR(getframe_doc
,
677 "_getframe([depth]) -> frameobject\n\
679 Return a frame object from the call stack. If optional integer depth is\n\
680 given, return the frame object that many calls below the top of the stack.\n\
681 If that is deeper than the call stack, ValueError is raised. The default\n\
682 for depth is zero, returning the frame at the top of the call stack.\n\
684 This function should be used for internal and specialized\n\
689 sys_getframe(PyObject
*self
, PyObject
*args
)
691 PyFrameObject
*f
= PyThreadState_GET()->frame
;
694 if (!PyArg_ParseTuple(args
, "|i:_getframe", &depth
))
697 while (depth
> 0 && f
!= NULL
) {
702 PyErr_SetString(PyExc_ValueError
,
703 "call stack is not deep enough");
710 PyDoc_STRVAR(current_frames_doc
,
711 "_current_frames() -> dictionary\n\
713 Return a dictionary mapping each current thread T's thread id to T's\n\
714 current stack frame.\n\
716 This function should be used for specialized purposes only."
720 sys_current_frames(PyObject
*self
, PyObject
*noargs
)
722 return _PyThread_CurrentFrames();
725 PyDoc_STRVAR(call_tracing_doc
,
726 "call_tracing(func, args) -> object\n\
728 Call func(*args), while tracing is enabled. The tracing state is\n\
729 saved, and restored afterwards. This is intended to be called from\n\
730 a debugger from a checkpoint, to recursively debug some other code."
734 sys_call_tracing(PyObject
*self
, PyObject
*args
)
736 PyObject
*func
, *funcargs
;
737 if (!PyArg_UnpackTuple(args
, "call_tracing", 2, 2, &func
, &funcargs
))
739 return _PyEval_CallTracing(func
, funcargs
);
742 PyDoc_STRVAR(callstats_doc
,
743 "callstats() -> tuple of integers\n\
745 Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
746 when Python was built. Otherwise, return None.\n\
748 When enabled, this function returns detailed, implementation-specific\n\
749 details about the number of function calls executed. The return value is\n\
750 a 11-tuple where the entries in the tuple are counts of:\n\
751 0. all function calls\n\
752 1. calls to PyFunction_Type objects\n\
753 2. PyFunction calls that do not create an argument tuple\n\
754 3. PyFunction calls that do not create an argument tuple\n\
755 and bypass PyEval_EvalCodeEx()\n\
757 5. PyMethod calls on bound methods\n\
759 7. PyCFunction calls\n\
760 8. generator calls\n\
761 9. All other calls\n\
762 10. Number of stack pops performed by call_function()"
770 /* Defined in objects.c because it uses static globals if that file */
771 extern PyObject
*_Py_GetObjects(PyObject
*, PyObject
*);
774 #ifdef DYNAMIC_EXECUTION_PROFILE
775 /* Defined in ceval.c because it uses static globals if that file */
776 extern PyObject
*_Py_GetDXProfile(PyObject
*, PyObject
*);
784 sys_clear_type_cache(PyObject
* self
, PyObject
* args
)
790 PyDoc_STRVAR(sys_clear_type_cache__doc__
,
791 "_clear_type_cache() -> None\n\
792 Clear the internal type lookup cache.");
796 sys_compact_freelists(PyObject
* self
, PyObject
* args
)
798 size_t isum
, ibc
, ibf
;
799 size_t fsum
, fbc
, fbf
;
801 PyInt_CompactFreeList(&ibc
, &ibf
, &isum
);
802 PyFloat_CompactFreeList(&fbc
, &fbf
, &fsum
);
804 return Py_BuildValue("(kkk)(kkk)", isum
, ibc
, ibf
,
809 PyDoc_STRVAR(sys_compact_freelists__doc__
,
810 "_compact_freelists() -> ((remaing_objects, total_blocks, freed_blocks), ...)\n\
811 Compact the free lists of ints and floats.");
813 static PyMethodDef sys_methods
[] = {
814 /* Might as well keep this in alphabetic order */
815 {"callstats", (PyCFunction
)PyEval_GetCallStats
, METH_NOARGS
,
817 {"_clear_type_cache", sys_clear_type_cache
, METH_NOARGS
,
818 sys_clear_type_cache__doc__
},
819 {"_compact_freelists", sys_compact_freelists
, METH_NOARGS
,
820 sys_compact_freelists__doc__
},
821 {"_current_frames", sys_current_frames
, METH_NOARGS
,
823 {"displayhook", sys_displayhook
, METH_O
, displayhook_doc
},
824 {"exc_info", sys_exc_info
, METH_NOARGS
, exc_info_doc
},
825 {"exc_clear", sys_exc_clear
, METH_NOARGS
, exc_clear_doc
},
826 {"excepthook", sys_excepthook
, METH_VARARGS
, excepthook_doc
},
827 {"exit", sys_exit
, METH_VARARGS
, exit_doc
},
828 #ifdef Py_USING_UNICODE
829 {"getdefaultencoding", (PyCFunction
)sys_getdefaultencoding
,
830 METH_NOARGS
, getdefaultencoding_doc
},
833 {"getdlopenflags", (PyCFunction
)sys_getdlopenflags
, METH_NOARGS
,
837 {"getcounts", (PyCFunction
)sys_getcounts
, METH_NOARGS
},
839 #ifdef DYNAMIC_EXECUTION_PROFILE
840 {"getdxp", _Py_GetDXProfile
, METH_VARARGS
},
842 #ifdef Py_USING_UNICODE
843 {"getfilesystemencoding", (PyCFunction
)sys_getfilesystemencoding
,
844 METH_NOARGS
, getfilesystemencoding_doc
},
847 {"getobjects", _Py_GetObjects
, METH_VARARGS
},
850 {"gettotalrefcount", (PyCFunction
)sys_gettotalrefcount
, METH_NOARGS
},
852 {"getrefcount", (PyCFunction
)sys_getrefcount
, METH_O
, getrefcount_doc
},
853 {"getrecursionlimit", (PyCFunction
)sys_getrecursionlimit
, METH_NOARGS
,
854 getrecursionlimit_doc
},
855 {"_getframe", sys_getframe
, METH_VARARGS
, getframe_doc
},
857 {"getwindowsversion", (PyCFunction
)sys_getwindowsversion
, METH_NOARGS
,
858 getwindowsversion_doc
},
859 #endif /* MS_WINDOWS */
861 {"mdebug", sys_mdebug
, METH_VARARGS
},
863 #ifdef Py_USING_UNICODE
864 {"setdefaultencoding", sys_setdefaultencoding
, METH_VARARGS
,
865 setdefaultencoding_doc
},
867 {"setcheckinterval", sys_setcheckinterval
, METH_VARARGS
,
868 setcheckinterval_doc
},
869 {"getcheckinterval", sys_getcheckinterval
, METH_NOARGS
,
870 getcheckinterval_doc
},
872 {"setdlopenflags", sys_setdlopenflags
, METH_VARARGS
,
875 {"setprofile", sys_setprofile
, METH_O
, setprofile_doc
},
876 {"getprofile", sys_getprofile
, METH_NOARGS
, getprofile_doc
},
877 {"setrecursionlimit", sys_setrecursionlimit
, METH_VARARGS
,
878 setrecursionlimit_doc
},
880 {"settscdump", sys_settscdump
, METH_VARARGS
, settscdump_doc
},
882 {"settrace", sys_settrace
, METH_O
, settrace_doc
},
883 {"gettrace", sys_gettrace
, METH_NOARGS
, gettrace_doc
},
884 {"call_tracing", sys_call_tracing
, METH_VARARGS
, call_tracing_doc
},
885 {NULL
, NULL
} /* sentinel */
889 list_builtin_module_names(void)
891 PyObject
*list
= PyList_New(0);
895 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
896 PyObject
*name
= PyString_FromString(
897 PyImport_Inittab
[i
].name
);
900 PyList_Append(list
, name
);
903 if (PyList_Sort(list
) != 0) {
908 PyObject
*v
= PyList_AsTuple(list
);
915 static PyObject
*warnoptions
= NULL
;
918 PySys_ResetWarnOptions(void)
920 if (warnoptions
== NULL
|| !PyList_Check(warnoptions
))
922 PyList_SetSlice(warnoptions
, 0, PyList_GET_SIZE(warnoptions
), NULL
);
926 PySys_AddWarnOption(char *s
)
930 if (warnoptions
== NULL
|| !PyList_Check(warnoptions
)) {
931 Py_XDECREF(warnoptions
);
932 warnoptions
= PyList_New(0);
933 if (warnoptions
== NULL
)
936 str
= PyString_FromString(s
);
938 PyList_Append(warnoptions
, str
);
944 PySys_HasWarnOptions(void)
946 return warnoptions
? 1 : 0;
949 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
950 Two literals concatenated works just fine. If you have a K&R compiler
951 or other abomination that however *does* understand longer strings,
952 get rid of the !!! comment in the middle and the quotes that surround it. */
955 "This module provides access to some objects used or maintained by the\n\
956 interpreter and to functions that interact strongly with the interpreter.\n\
960 argv -- command line arguments; argv[0] is the script pathname if known\n\
961 path -- module search path; path[0] is the script directory, else ''\n\
962 modules -- dictionary of loaded modules\n\
964 displayhook -- called to show results in an interactive session\n\
965 excepthook -- called to handle any uncaught exception other than SystemExit\n\
966 To customize printing in an interactive session or to install a custom\n\
967 top-level exception handler, assign other functions to replace these.\n\
969 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
970 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
972 stdin -- standard input file object; used by raw_input() and input()\n\
973 stdout -- standard output file object; used by the print statement\n\
974 stderr -- standard error object; used for error messages\n\
975 By assigning other file objects (or objects that behave like files)\n\
976 to these, it is possible to redirect all of the interpreter's I/O.\n\
978 last_type -- type of last uncaught exception\n\
979 last_value -- value of last uncaught exception\n\
980 last_traceback -- traceback of last uncaught exception\n\
981 These three are only available in an interactive session after a\n\
982 traceback has been printed.\n\
984 exc_type -- type of exception currently being handled\n\
985 exc_value -- value of exception currently being handled\n\
986 exc_traceback -- traceback of exception currently being handled\n\
987 The function exc_info() should be used instead of these three,\n\
988 because it is thread-safe.\n\
991 /* concatenating string here */
996 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
997 maxunicode -- the largest supported character\n\
998 builtin_module_names -- tuple of module names built into this interpreter\n\
999 version -- the version of this interpreter as a string\n\
1000 version_info -- version information as a tuple\n\
1001 hexversion -- version information encoded as a single integer\n\
1002 copyright -- copyright notice pertaining to this interpreter\n\
1003 platform -- platform identifier\n\
1004 executable -- pathname of this Python interpreter\n\
1005 prefix -- prefix used to find the Python library\n\
1006 exec_prefix -- prefix used to find the machine-specific Python library\n\
1010 /* concatenating string here */
1012 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
1013 winver -- [Windows only] version number of the Python DLL\n\
1016 #endif /* MS_WINDOWS */
1018 "__stdin__ -- the original stdin; don't touch!\n\
1019 __stdout__ -- the original stdout; don't touch!\n\
1020 __stderr__ -- the original stderr; don't touch!\n\
1021 __displayhook__ -- the original displayhook; don't touch!\n\
1022 __excepthook__ -- the original excepthook; don't touch!\n\
1026 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
1027 excepthook() -- print an exception and its traceback to sys.stderr\n\
1028 exc_info() -- return thread-safe information about the current exception\n\
1029 exc_clear() -- clear the exception state for the current thread\n\
1030 exit() -- exit the interpreter by raising SystemExit\n\
1031 getdlopenflags() -- returns flags to be used for dlopen() calls\n\
1032 getprofile() -- get the global profiling function\n\
1033 getrefcount() -- return the reference count for an object (plus one :-)\n\
1034 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
1035 gettrace() -- get the global debug tracing function\n\
1036 setcheckinterval() -- control how often the interpreter checks for events\n\
1037 setdlopenflags() -- set the flags to be used for dlopen() calls\n\
1038 setprofile() -- set the global profiling function\n\
1039 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
1040 settrace() -- set the global debug tracing function\n\
1043 /* end of sys_doc */ ;
1046 _check_and_flush (FILE *stream
)
1048 int prev_fail
= ferror (stream
);
1049 return fflush (stream
) || prev_fail
? EOF
: 0;
1052 /* Subversion branch and revision management */
1053 static const char _patchlevel_revision
[] = PY_PATCHLEVEL_REVISION
;
1054 static const char headurl
[] = "$HeadURL$";
1055 static int svn_initialized
;
1056 static char patchlevel_revision
[50]; /* Just the number */
1057 static char branch
[50];
1058 static char shortbranch
[50];
1059 static const char *svn_revision
;
1062 svnversion_init(void)
1064 const char *python
, *br_start
, *br_end
, *br_end2
, *svnversion
;
1068 if (svn_initialized
)
1071 python
= strstr(headurl
, "/python/");
1073 /* XXX quick hack to get bzr working */
1074 *patchlevel_revision
= '\0';
1076 strcpy(shortbranch
, "unknown");
1079 /* Py_FatalError("subversion keywords missing"); */
1082 br_start
= python
+ 8;
1083 br_end
= strchr(br_start
, '/');
1086 /* Works even for trunk,
1087 as we are in trunk/Python/sysmodule.c */
1088 br_end2
= strchr(br_end
+1, '/');
1090 istag
= strncmp(br_start
, "tags", 4) == 0;
1091 if (strncmp(br_start
, "trunk", 5) == 0) {
1092 strcpy(branch
, "trunk");
1093 strcpy(shortbranch
, "trunk");
1096 else if (istag
|| strncmp(br_start
, "branches", 8) == 0) {
1097 len
= br_end2
- br_start
;
1098 strncpy(branch
, br_start
, len
);
1101 len
= br_end2
- (br_end
+ 1);
1102 strncpy(shortbranch
, br_end
+ 1, len
);
1103 shortbranch
[len
] = '\0';
1106 Py_FatalError("bad HeadURL");
1111 svnversion
= _Py_svnversion();
1112 if (strcmp(svnversion
, "exported") != 0)
1113 svn_revision
= svnversion
;
1115 len
= strlen(_patchlevel_revision
);
1117 assert(len
< (sizeof(patchlevel_revision
) + 13));
1118 strncpy(patchlevel_revision
, _patchlevel_revision
+ 11,
1120 patchlevel_revision
[len
- 13] = '\0';
1121 svn_revision
= patchlevel_revision
;
1126 svn_initialized
= 1;
1129 /* Return svnversion output if available.
1130 Else return Revision of patchlevel.h if on branch.
1131 Else return empty string */
1133 Py_SubversionRevision()
1136 return svn_revision
;
1140 Py_SubversionShortBranch()
1147 PyDoc_STRVAR(flags__doc__
,
1150 Flags provided through command line arguments or environment vars.");
1152 static PyTypeObject FlagsType
= {0, 0, 0, 0, 0, 0};
1154 static PyStructSequence_Field flags_fields
[] = {
1156 {"py3k_warning", "-3"},
1157 {"division_warning", "-Q"},
1158 {"division_new", "-Qnew"},
1160 {"interactive", "-i"},
1161 {"optimize", "-O or -OO"},
1162 {"dont_write_bytecode", "-B"},
1163 /* {"no_user_site", "-s"}, */
1165 {"ignore_environment", "-E"},
1166 {"tabcheck", "-t or -tt"},
1169 {"riscos_wimp", "???"},
1171 /* {"unbuffered", "-u"}, */
1173 /* {"skip_first", "-x"}, */
1174 {"bytes_warning", "-b"},
1178 static PyStructSequence_Desc flags_desc
= {
1179 "sys.flags", /* name */
1180 flags__doc__
, /* doc */
1181 flags_fields
, /* fields */
1195 seq
= PyStructSequence_New(&FlagsType
);
1199 #define SetFlag(flag) \
1200 PyStructSequence_SET_ITEM(seq, pos++, PyInt_FromLong(flag))
1202 SetFlag(Py_DebugFlag
);
1203 SetFlag(Py_Py3kWarningFlag
);
1204 SetFlag(Py_DivisionWarningFlag
);
1205 SetFlag(_Py_QnewFlag
);
1206 SetFlag(Py_InspectFlag
);
1207 SetFlag(Py_InteractiveFlag
);
1208 SetFlag(Py_OptimizeFlag
);
1209 SetFlag(Py_DontWriteBytecodeFlag
);
1210 /* SetFlag(Py_NoUserSiteDirectory); */
1211 SetFlag(Py_NoSiteFlag
);
1212 SetFlag(Py_IgnoreEnvironmentFlag
);
1213 SetFlag(Py_TabcheckFlag
);
1214 SetFlag(Py_VerboseFlag
);
1216 SetFlag(Py_RISCOSWimpFlag
);
1218 /* SetFlag(saw_unbuffered_flag); */
1219 SetFlag(Py_UnicodeFlag
);
1220 /* SetFlag(skipfirstline); */
1221 SetFlag(Py_BytesWarningFlag
);
1224 if (PyErr_Occurred()) {
1233 PyObject
*m
, *v
, *sysdict
;
1234 PyObject
*sysin
, *sysout
, *syserr
;
1240 m
= Py_InitModule3("sys", sys_methods
, sys_doc
);
1243 sysdict
= PyModule_GetDict(m
);
1244 #define SET_SYS_FROM_STRING(key, value) \
1247 PyDict_SetItemString(sysdict, key, v); \
1251 /* XXX: does this work on Win/Win64? (see posix_fstat) */
1253 if (fstat(fileno(stdin
), &sb
) == 0 &&
1254 S_ISDIR(sb
.st_mode
)) {
1255 /* There's nothing more we can do. */
1256 /* Py_FatalError() will core dump, so just exit. */
1257 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1262 /* Closing the standard FILE* if sys.std* goes aways causes problems
1263 * for embedded Python usages. Closing them when somebody explicitly
1264 * invokes .close() might be possible, but the FAQ promises they get
1265 * never closed. However, we still need to get write errors when
1266 * writing fails (e.g. because stdout is redirected), so we flush the
1267 * streams and check for errors before the file objects are deleted.
1268 * On OS X, fflush()ing stdin causes an error, so we exempt stdin
1269 * from that procedure.
1271 sysin
= PyFile_FromFile(stdin
, "<stdin>", "r", NULL
);
1272 sysout
= PyFile_FromFile(stdout
, "<stdout>", "w", _check_and_flush
);
1273 syserr
= PyFile_FromFile(stderr
, "<stderr>", "w", _check_and_flush
);
1274 if (PyErr_Occurred())
1277 if(isatty(_fileno(stdin
)) && PyFile_Check(sysin
)) {
1278 sprintf(buf
, "cp%d", GetConsoleCP());
1279 if (!PyFile_SetEncoding(sysin
, buf
))
1282 if(isatty(_fileno(stdout
)) && PyFile_Check(sysout
)) {
1283 sprintf(buf
, "cp%d", GetConsoleOutputCP());
1284 if (!PyFile_SetEncoding(sysout
, buf
))
1287 if(isatty(_fileno(stderr
)) && PyFile_Check(syserr
)) {
1288 sprintf(buf
, "cp%d", GetConsoleOutputCP());
1289 if (!PyFile_SetEncoding(syserr
, buf
))
1294 PyDict_SetItemString(sysdict
, "stdin", sysin
);
1295 PyDict_SetItemString(sysdict
, "stdout", sysout
);
1296 PyDict_SetItemString(sysdict
, "stderr", syserr
);
1297 /* Make backup copies for cleanup */
1298 PyDict_SetItemString(sysdict
, "__stdin__", sysin
);
1299 PyDict_SetItemString(sysdict
, "__stdout__", sysout
);
1300 PyDict_SetItemString(sysdict
, "__stderr__", syserr
);
1301 PyDict_SetItemString(sysdict
, "__displayhook__",
1302 PyDict_GetItemString(sysdict
, "displayhook"));
1303 PyDict_SetItemString(sysdict
, "__excepthook__",
1304 PyDict_GetItemString(sysdict
, "excepthook"));
1309 SET_SYS_FROM_STRING("version",
1310 PyString_FromString(Py_GetVersion()));
1311 SET_SYS_FROM_STRING("hexversion",
1312 PyInt_FromLong(PY_VERSION_HEX
));
1314 SET_SYS_FROM_STRING("subversion",
1315 Py_BuildValue("(ssz)", "CPython", branch
,
1317 SET_SYS_FROM_STRING("dont_write_bytecode",
1318 PyBool_FromLong(Py_DontWriteBytecodeFlag
));
1320 * These release level checks are mutually exclusive and cover
1321 * the field, so don't get too fancy with the pre-processor!
1323 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
1325 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
1327 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
1329 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
1333 SET_SYS_FROM_STRING("version_info",
1334 Py_BuildValue("iiisi", PY_MAJOR_VERSION
,
1336 PY_MICRO_VERSION
, s
,
1337 PY_RELEASE_SERIAL
));
1338 SET_SYS_FROM_STRING("api_version",
1339 PyInt_FromLong(PYTHON_API_VERSION
));
1340 SET_SYS_FROM_STRING("copyright",
1341 PyString_FromString(Py_GetCopyright()));
1342 SET_SYS_FROM_STRING("platform",
1343 PyString_FromString(Py_GetPlatform()));
1344 SET_SYS_FROM_STRING("executable",
1345 PyString_FromString(Py_GetProgramFullPath()));
1346 SET_SYS_FROM_STRING("prefix",
1347 PyString_FromString(Py_GetPrefix()));
1348 SET_SYS_FROM_STRING("exec_prefix",
1349 PyString_FromString(Py_GetExecPrefix()));
1350 SET_SYS_FROM_STRING("maxint",
1351 PyInt_FromLong(PyInt_GetMax()));
1352 SET_SYS_FROM_STRING("py3kwarning",
1353 PyBool_FromLong(Py_Py3kWarningFlag
));
1354 SET_SYS_FROM_STRING("float_info",
1356 #ifdef Py_USING_UNICODE
1357 SET_SYS_FROM_STRING("maxunicode",
1358 PyInt_FromLong(PyUnicode_GetMax()));
1360 SET_SYS_FROM_STRING("builtin_module_names",
1361 list_builtin_module_names());
1363 /* Assumes that longs are at least 2 bytes long.
1365 unsigned long number
= 1;
1368 s
= (char *) &number
;
1373 SET_SYS_FROM_STRING("byteorder",
1374 PyString_FromString(value
));
1377 SET_SYS_FROM_STRING("dllhandle",
1378 PyLong_FromVoidPtr(PyWin_DLLhModule
));
1379 SET_SYS_FROM_STRING("winver",
1380 PyString_FromString(PyWin_DLLVersionString
));
1382 if (warnoptions
== NULL
) {
1383 warnoptions
= PyList_New(0);
1386 Py_INCREF(warnoptions
);
1388 if (warnoptions
!= NULL
) {
1389 PyDict_SetItemString(sysdict
, "warnoptions", warnoptions
);
1392 if (FlagsType
.tp_name
== 0)
1393 PyStructSequence_InitType(&FlagsType
, &flags_desc
);
1394 SET_SYS_FROM_STRING("flags", make_flags());
1395 /* prevent user from creating new instances */
1396 FlagsType
.tp_init
= NULL
;
1397 FlagsType
.tp_new
= NULL
;
1399 #undef SET_SYS_FROM_STRING
1400 if (PyErr_Occurred())
1406 makepathobject(char *path
, int delim
)
1414 while ((p
= strchr(p
, delim
)) != NULL
) {
1421 for (i
= 0; ; i
++) {
1422 p
= strchr(path
, delim
);
1424 p
= strchr(path
, '\0'); /* End of string */
1425 w
= PyString_FromStringAndSize(path
, (Py_ssize_t
) (p
- path
));
1430 PyList_SetItem(v
, i
, w
);
1439 PySys_SetPath(char *path
)
1442 if ((v
= makepathobject(path
, DELIM
)) == NULL
)
1443 Py_FatalError("can't create sys.path");
1444 if (PySys_SetObject("path", v
) != 0)
1445 Py_FatalError("can't assign sys.path");
1450 makeargvobject(int argc
, char **argv
)
1453 if (argc
<= 0 || argv
== NULL
) {
1454 /* Ensure at least one (empty) argument is seen */
1455 static char *empty_argv
[1] = {""};
1459 av
= PyList_New(argc
);
1462 for (i
= 0; i
< argc
; i
++) {
1466 /* argv[0] is the script pathname if known */
1468 char* fn
= decc$
translate_vms(argv
[0]);
1469 if ((fn
== (char *)0) || fn
== (char *)-1)
1470 v
= PyString_FromString(argv
[0]);
1472 v
= PyString_FromString(
1473 decc$
translate_vms(argv
[0]));
1475 v
= PyString_FromString(argv
[i
]);
1477 PyObject
*v
= PyString_FromString(argv
[i
]);
1484 PyList_SetItem(av
, i
, v
);
1491 PySys_SetArgv(int argc
, char **argv
)
1493 #if defined(HAVE_REALPATH)
1494 char fullpath
[MAXPATHLEN
];
1495 #elif defined(MS_WINDOWS)
1496 char fullpath
[MAX_PATH
];
1498 PyObject
*av
= makeargvobject(argc
, argv
);
1499 PyObject
*path
= PySys_GetObject("path");
1501 Py_FatalError("no mem for sys.argv");
1502 if (PySys_SetObject("argv", av
) != 0)
1503 Py_FatalError("can't assign sys.argv");
1505 char *argv0
= argv
[0];
1509 #ifdef HAVE_READLINK
1510 char link
[MAXPATHLEN
+1];
1511 char argv0copy
[2*MAXPATHLEN
+1];
1513 if (argc
> 0 && argv0
!= NULL
&& strcmp(argv0
, "-c") != 0)
1514 nr
= readlink(argv0
, link
, MAXPATHLEN
);
1516 /* It's a symlink */
1519 argv0
= link
; /* Link to absolute path */
1520 else if (strchr(link
, SEP
) == NULL
)
1521 ; /* Link without path */
1523 /* Must join(dirname(argv0), link) */
1524 char *q
= strrchr(argv0
, SEP
);
1526 argv0
= link
; /* argv0 without path */
1528 /* Must make a copy */
1529 strcpy(argv0copy
, argv0
);
1530 q
= strrchr(argv0copy
, SEP
);
1536 #endif /* HAVE_READLINK */
1537 #if SEP == '\\' /* Special case for MS filename syntax */
1538 if (argc
> 0 && argv0
!= NULL
&& strcmp(argv0
, "-c") != 0) {
1542 if (GetFullPathName(argv0
,
1549 p
= strrchr(argv0
, SEP
);
1550 /* Test for alternate separator */
1551 q
= strrchr(p
? p
: argv0
, '/');
1556 if (n
> 1 && p
[-1] != ':')
1557 n
--; /* Drop trailing separator */
1560 #else /* All other filename syntaxes */
1561 if (argc
> 0 && argv0
!= NULL
&& strcmp(argv0
, "-c") != 0) {
1562 #if defined(HAVE_REALPATH)
1563 if (realpath(argv0
, fullpath
)) {
1567 p
= strrchr(argv0
, SEP
);
1572 #else /* don't include trailing separator */
1575 #if SEP == '/' /* Special case for Unix filename syntax */
1577 n
--; /* Drop trailing separator */
1580 #endif /* All others */
1581 a
= PyString_FromStringAndSize(argv0
, n
);
1583 Py_FatalError("no mem for sys.path insertion");
1584 if (PyList_Insert(path
, 0, a
) < 0)
1585 Py_FatalError("sys.path.insert(0) failed");
1592 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1593 Adapted from code submitted by Just van Rossum.
1595 PySys_WriteStdout(format, ...)
1596 PySys_WriteStderr(format, ...)
1598 The first function writes to sys.stdout; the second to sys.stderr. When
1599 there is a problem, they write to the real (C level) stdout or stderr;
1600 no exceptions are raised.
1602 Both take a printf-style format string as their first argument followed
1603 by a variable length argument list determined by the format string.
1607 The format should limit the total size of the formatted output string to
1608 1000 bytes. In particular, this means that no unrestricted "%s" formats
1609 should occur; these should be limited using "%.<N>s where <N> is a
1610 decimal number calculated so that <N> plus the maximum size of other
1611 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1612 which can print hundreds of digits for very large numbers.
1617 mywrite(char *name
, FILE *fp
, const char *format
, va_list va
)
1620 PyObject
*error_type
, *error_value
, *error_traceback
;
1622 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
1623 file
= PySys_GetObject(name
);
1624 if (file
== NULL
|| PyFile_AsFile(file
) == fp
)
1625 vfprintf(fp
, format
, va
);
1628 const int written
= PyOS_vsnprintf(buffer
, sizeof(buffer
),
1630 if (PyFile_WriteString(buffer
, file
) != 0) {
1634 if (written
< 0 || (size_t)written
>= sizeof(buffer
)) {
1635 const char *truncated
= "... truncated";
1636 if (PyFile_WriteString(truncated
, file
) != 0) {
1638 fputs(truncated
, fp
);
1642 PyErr_Restore(error_type
, error_value
, error_traceback
);
1646 PySys_WriteStdout(const char *format
, ...)
1650 va_start(va
, format
);
1651 mywrite("stdout", stdout
, format
, va
);
1656 PySys_WriteStderr(const char *format
, ...)
1660 va_start(va
, format
);
1661 mywrite("stderr", stderr
, format
, va
);