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)
19 #include "frameobject.h"
24 #define WIN32_LEAN_AND_MEAN
26 #endif /* MS_WINDOWS */
29 extern void *PyWin_DLLhModule
;
30 /* A string loaded from the DLL at startup: */
31 extern const char *PyWin_DLLVersionString
;
35 PySys_GetObject(char *name
)
37 PyThreadState
*tstate
= PyThreadState_Get();
38 PyObject
*sd
= tstate
->interp
->sysdict
;
41 return PyDict_GetItemString(sd
, name
);
45 PySys_GetFile(char *name
, FILE *def
)
48 PyObject
*v
= PySys_GetObject(name
);
49 if (v
!= NULL
&& PyFile_Check(v
))
50 fp
= PyFile_AsFile(v
);
57 PySys_SetObject(char *name
, PyObject
*v
)
59 PyThreadState
*tstate
= PyThreadState_Get();
60 PyObject
*sd
= tstate
->interp
->sysdict
;
62 if (PyDict_GetItemString(sd
, name
) == NULL
)
65 return PyDict_DelItemString(sd
, name
);
68 return PyDict_SetItemString(sd
, name
, v
);
72 sys_displayhook(PyObject
*self
, PyObject
*o
)
75 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
76 PyObject
*modules
= interp
->modules
;
77 PyObject
*builtins
= PyDict_GetItemString(modules
, "__builtin__");
79 if (builtins
== NULL
) {
80 PyErr_SetString(PyExc_RuntimeError
, "lost __builtin__");
84 /* Print value except if None */
85 /* After printing, also assign to '_' */
86 /* Before, set '_' to None to avoid recursion */
91 if (PyObject_SetAttrString(builtins
, "_", Py_None
) != 0)
93 if (Py_FlushLine() != 0)
95 outf
= PySys_GetObject("stdout");
97 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
100 if (PyFile_WriteObject(o
, outf
, 0) != 0)
102 PyFile_SoftSpace(outf
, 1);
103 if (Py_FlushLine() != 0)
105 if (PyObject_SetAttrString(builtins
, "_", o
) != 0)
111 PyDoc_STRVAR(displayhook_doc
,
112 "displayhook(object) -> None\n"
114 "Print an object to sys.stdout and also save it in __builtin__._\n"
118 sys_excepthook(PyObject
* self
, PyObject
* args
)
120 PyObject
*exc
, *value
, *tb
;
121 if (!PyArg_UnpackTuple(args
, "excepthook", 3, 3, &exc
, &value
, &tb
))
123 PyErr_Display(exc
, value
, tb
);
128 PyDoc_STRVAR(excepthook_doc
,
129 "excepthook(exctype, value, traceback) -> None\n"
131 "Handle an exception by displaying it with a traceback on sys.stderr.\n"
135 sys_exc_info(PyObject
*self
, PyObject
*noargs
)
137 PyThreadState
*tstate
;
138 tstate
= PyThreadState_Get();
139 return Py_BuildValue(
141 tstate
->exc_type
!= NULL
? tstate
->exc_type
: Py_None
,
142 tstate
->exc_value
!= NULL
? tstate
->exc_value
: Py_None
,
143 tstate
->exc_traceback
!= NULL
?
144 tstate
->exc_traceback
: Py_None
);
147 PyDoc_STRVAR(exc_info_doc
,
148 "exc_info() -> (type, value, traceback)\n\
150 Return information about the most recent exception caught by an except\n\
151 clause in the current stack frame or in an older stack frame."
155 sys_exc_clear(PyObject
*self
, PyObject
*noargs
)
157 PyThreadState
*tstate
= PyThreadState_Get();
158 PyObject
*tmp_type
, *tmp_value
, *tmp_tb
;
159 tmp_type
= tstate
->exc_type
;
160 tmp_value
= tstate
->exc_value
;
161 tmp_tb
= tstate
->exc_traceback
;
162 tstate
->exc_type
= NULL
;
163 tstate
->exc_value
= NULL
;
164 tstate
->exc_traceback
= NULL
;
165 Py_XDECREF(tmp_type
);
166 Py_XDECREF(tmp_value
);
168 /* For b/w compatibility */
169 PySys_SetObject("exc_type", Py_None
);
170 PySys_SetObject("exc_value", Py_None
);
171 PySys_SetObject("exc_traceback", Py_None
);
176 PyDoc_STRVAR(exc_clear_doc
,
177 "exc_clear() -> None\n\
179 Clear global information on the current exception. Subsequent calls to\n\
180 exc_info() will return (None,None,None) until another exception is raised\n\
181 in the current thread or the execution stack returns to a frame where\n\
182 another exception is being handled."
186 sys_exit(PyObject
*self
, PyObject
*args
)
188 PyObject
*exit_code
= 0;
189 if (!PyArg_ParseTuple(args
, "|O:exit", &exit_code
))
191 /* Raise SystemExit so callers may catch it or clean up. */
192 PyErr_SetObject(PyExc_SystemExit
, exit_code
);
196 PyDoc_STRVAR(exit_doc
,
199 Exit the interpreter by raising SystemExit(status).\n\
200 If the status is omitted or None, it defaults to zero (i.e., success).\n\
201 If the status is numeric, it will be used as the system exit status.\n\
202 If it is another kind of object, it will be printed and the system\n\
203 exit status will be one (i.e., failure)."
206 #ifdef Py_USING_UNICODE
209 sys_getdefaultencoding(PyObject
*self
)
211 return PyString_FromString(PyUnicode_GetDefaultEncoding());
214 PyDoc_STRVAR(getdefaultencoding_doc
,
215 "getdefaultencoding() -> string\n\
217 Return the current default string encoding used by the Unicode \n\
222 sys_setdefaultencoding(PyObject
*self
, PyObject
*args
)
225 if (!PyArg_ParseTuple(args
, "s:setdefaultencoding", &encoding
))
227 if (PyUnicode_SetDefaultEncoding(encoding
))
233 PyDoc_STRVAR(setdefaultencoding_doc
,
234 "setdefaultencoding(encoding)\n\
236 Set the current default string encoding used by the Unicode implementation."
240 sys_getfilesystemencoding(PyObject
*self
)
242 if (Py_FileSystemDefaultEncoding
)
243 return PyString_FromString(Py_FileSystemDefaultEncoding
);
248 PyDoc_STRVAR(getfilesystemencoding_doc
,
249 "getfilesystemencoding() -> string\n\
251 Return the encoding used to convert Unicode filenames in\n\
252 operating system filenames."
258 * Cached interned string objects used for calling the profile and
259 * trace functions. Initialized by trace_init().
261 static PyObject
*whatstrings
[4] = {NULL
, NULL
, NULL
, NULL
};
266 static char *whatnames
[4] = {"call", "exception", "line", "return"};
269 for (i
= 0; i
< 4; ++i
) {
270 if (whatstrings
[i
] == NULL
) {
271 name
= PyString_InternFromString(whatnames
[i
]);
274 whatstrings
[i
] = name
;
282 call_trampoline(PyThreadState
*tstate
, PyObject
* callback
,
283 PyFrameObject
*frame
, int what
, PyObject
*arg
)
285 PyObject
*args
= PyTuple_New(3);
292 whatstr
= whatstrings
[what
];
297 PyTuple_SET_ITEM(args
, 0, (PyObject
*)frame
);
298 PyTuple_SET_ITEM(args
, 1, whatstr
);
299 PyTuple_SET_ITEM(args
, 2, arg
);
301 /* call the Python-level function */
302 PyFrame_FastToLocals(frame
);
303 result
= PyEval_CallObject(callback
, args
);
304 PyFrame_LocalsToFast(frame
, 1);
306 PyTraceBack_Here(frame
);
314 profile_trampoline(PyObject
*self
, PyFrameObject
*frame
,
315 int what
, PyObject
*arg
)
317 PyThreadState
*tstate
= frame
->f_tstate
;
322 result
= call_trampoline(tstate
, self
, frame
, what
, arg
);
323 if (result
== NULL
) {
324 PyEval_SetProfile(NULL
, NULL
);
332 trace_trampoline(PyObject
*self
, PyFrameObject
*frame
,
333 int what
, PyObject
*arg
)
335 PyThreadState
*tstate
= frame
->f_tstate
;
339 if (what
== PyTrace_CALL
)
342 callback
= frame
->f_trace
;
343 if (callback
== NULL
)
345 result
= call_trampoline(tstate
, callback
, frame
, what
, arg
);
346 if (result
== NULL
) {
347 PyEval_SetTrace(NULL
, NULL
);
348 Py_XDECREF(frame
->f_trace
);
349 frame
->f_trace
= NULL
;
352 if (result
!= Py_None
) {
353 PyObject
*temp
= frame
->f_trace
;
354 frame
->f_trace
= NULL
;
356 frame
->f_trace
= result
;
365 sys_settrace(PyObject
*self
, PyObject
*args
)
367 if (trace_init() == -1)
370 PyEval_SetTrace(NULL
, NULL
);
372 PyEval_SetTrace(trace_trampoline
, args
);
377 PyDoc_STRVAR(settrace_doc
,
378 "settrace(function)\n\
380 Set the global debug tracing function. It will be called on each\n\
381 function call. See the debugger chapter in the library manual."
385 sys_setprofile(PyObject
*self
, PyObject
*args
)
387 if (trace_init() == -1)
390 PyEval_SetProfile(NULL
, NULL
);
392 PyEval_SetProfile(profile_trampoline
, args
);
397 PyDoc_STRVAR(setprofile_doc
,
398 "setprofile(function)\n\
400 Set the profiling function. It will be called on each function call\n\
401 and return. See the profiler chapter in the library manual."
405 sys_setcheckinterval(PyObject
*self
, PyObject
*args
)
407 if (!PyArg_ParseTuple(args
, "i:setcheckinterval", &_Py_CheckInterval
))
413 PyDoc_STRVAR(setcheckinterval_doc
,
414 "setcheckinterval(n)\n\
416 Tell the Python interpreter to check for asynchronous events every\n\
417 n instructions. This also affects how often thread switches occur."
421 sys_setrecursionlimit(PyObject
*self
, PyObject
*args
)
424 if (!PyArg_ParseTuple(args
, "i:setrecursionlimit", &new_limit
))
426 if (new_limit
<= 0) {
427 PyErr_SetString(PyExc_ValueError
,
428 "recursion limit must be positive");
431 Py_SetRecursionLimit(new_limit
);
436 PyDoc_STRVAR(setrecursionlimit_doc
,
437 "setrecursionlimit(n)\n\
439 Set the maximum depth of the Python interpreter stack to n. This\n\
440 limit prevents infinite recursion from causing an overflow of the C\n\
441 stack and crashing Python. The highest possible limit is platform-\n\
446 sys_getrecursionlimit(PyObject
*self
)
448 return PyInt_FromLong(Py_GetRecursionLimit());
451 PyDoc_STRVAR(getrecursionlimit_doc
,
452 "getrecursionlimit()\n\
454 Return the current value of the recursion limit, the maximum depth\n\
455 of the Python interpreter stack. This limit prevents infinite\n\
456 recursion from causing an overflow of the C stack and crashing Python."
460 PyDoc_STRVAR(getwindowsversion_doc
,
461 "getwindowsversion()\n\
463 Return information about the running version of Windows.\n\
464 The result is a tuple of (major, minor, build, platform, text)\n\
465 All elements are numbers, except text which is a string.\n\
466 Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
471 sys_getwindowsversion(PyObject
*self
)
474 ver
.dwOSVersionInfoSize
= sizeof(ver
);
475 if (!GetVersionEx(&ver
))
476 return PyErr_SetFromWindowsErr(0);
477 return Py_BuildValue("HHHHs",
485 #endif /* MS_WINDOWS */
489 sys_setdlopenflags(PyObject
*self
, PyObject
*args
)
492 PyThreadState
*tstate
= PyThreadState_Get();
493 if (!PyArg_ParseTuple(args
, "i:setdlopenflags", &new_val
))
497 tstate
->interp
->dlopenflags
= new_val
;
502 PyDoc_STRVAR(setdlopenflags_doc
,
503 "setdlopenflags(n) -> None\n\
505 Set the flags that will be used for dlopen() calls. Among other\n\
506 things, this will enable a lazy resolving of symbols when importing\n\
507 a module, if called as sys.setdlopenflags(0)\n\
508 To share symbols across extension modules, call as\n\
509 sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
513 sys_getdlopenflags(PyObject
*self
, PyObject
*args
)
515 PyThreadState
*tstate
= PyThreadState_Get();
518 return PyInt_FromLong(tstate
->interp
->dlopenflags
);
521 PyDoc_STRVAR(getdlopenflags_doc
,
522 "getdlopenflags() -> int\n\
524 Return the current value of the flags that are used for dlopen()\n\
525 calls. The flag constants are defined in the dl module."
530 /* Link with -lmalloc (or -lmpc) on an SGI */
534 sys_mdebug(PyObject
*self
, PyObject
*args
)
537 if (!PyArg_ParseTuple(args
, "i:mdebug", &flag
))
539 mallopt(M_DEBUG
, flag
);
543 #endif /* USE_MALLOPT */
546 sys_getrefcount(PyObject
*self
, PyObject
*arg
)
548 return PyInt_FromLong(arg
->ob_refcnt
);
553 sys_gettotalrefcount(PyObject
*self
)
555 return PyInt_FromLong(_Py_RefTotal
);
558 #endif /* Py_TRACE_REFS */
560 PyDoc_STRVAR(getrefcount_doc
,
561 "getrefcount(object) -> integer\n\
563 Return the reference count of object. The count returned is generally\n\
564 one higher than you might expect, because it includes the (temporary)\n\
565 reference as an argument to getrefcount()."
570 sys_getcounts(PyObject
*self
)
572 extern PyObject
*get_counts(void);
578 PyDoc_STRVAR(getframe_doc
,
579 "_getframe([depth]) -> frameobject\n\
581 Return a frame object from the call stack. If optional integer depth is\n\
582 given, return the frame object that many calls below the top of the stack.\n\
583 If that is deeper than the call stack, ValueError is raised. The default\n\
584 for depth is zero, returning the frame at the top of the call stack.\n\
586 This function should be used for internal and specialized\n\
591 sys_getframe(PyObject
*self
, PyObject
*args
)
593 PyFrameObject
*f
= PyThreadState_Get()->frame
;
596 if (!PyArg_ParseTuple(args
, "|i:_getframe", &depth
))
599 while (depth
> 0 && f
!= NULL
) {
604 PyErr_SetString(PyExc_ValueError
,
605 "call stack is not deep enough");
612 PyDoc_STRVAR(callstats_doc
,
613 "callstats() -> tuple of integers\n\
615 Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
616 when Python was built. Otherwise, return None.\n\
618 When enabled, this function returns detailed, implementation-specific\n\
619 details about the number of function calls executed. The return value is\n\
620 a 11-tuple where the entries in the tuple are counts of:\n\
621 0. all function calls\n\
622 1. calls to PyFunction_Type objects\n\
623 2. PyFunction calls that do not create an argument tuple\n\
624 3. PyFunction calls that do not create an argument tuple\n\
625 and bypass PyEval_EvalCodeEx()\n\
627 5. PyMethod calls on bound methods\n\
629 7. PyCFunction calls\n\
630 8. generator calls\n\
631 9. All other calls\n\
632 10. Number of stack pops performed by call_function()"
636 /* Defined in objects.c because it uses static globals if that file */
637 extern PyObject
*_Py_GetObjects(PyObject
*, PyObject
*);
640 #ifdef DYNAMIC_EXECUTION_PROFILE
641 /* Defined in ceval.c because it uses static globals if that file */
642 extern PyObject
*_Py_GetDXProfile(PyObject
*, PyObject
*);
645 static PyMethodDef sys_methods
[] = {
646 /* Might as well keep this in alphabetic order */
647 {"callstats", (PyCFunction
)PyEval_GetCallStats
, METH_NOARGS
,
649 {"displayhook", sys_displayhook
, METH_O
, displayhook_doc
},
650 {"exc_info", sys_exc_info
, METH_NOARGS
, exc_info_doc
},
651 {"exc_clear", sys_exc_clear
, METH_NOARGS
, exc_clear_doc
},
652 {"excepthook", sys_excepthook
, METH_VARARGS
, excepthook_doc
},
653 {"exit", sys_exit
, METH_VARARGS
, exit_doc
},
654 #ifdef Py_USING_UNICODE
655 {"getdefaultencoding", (PyCFunction
)sys_getdefaultencoding
,
656 METH_NOARGS
, getdefaultencoding_doc
},
659 {"getdlopenflags", (PyCFunction
)sys_getdlopenflags
, METH_NOARGS
,
663 {"getcounts", (PyCFunction
)sys_getcounts
, METH_NOARGS
},
665 #ifdef DYNAMIC_EXECUTION_PROFILE
666 {"getdxp", _Py_GetDXProfile
, METH_VARARGS
},
668 #ifdef Py_USING_UNICODE
669 {"getfilesystemencoding", (PyCFunction
)sys_getfilesystemencoding
,
670 METH_NOARGS
, getfilesystemencoding_doc
},
673 {"getobjects", _Py_GetObjects
, METH_VARARGS
},
676 {"gettotalrefcount", (PyCFunction
)sys_gettotalrefcount
, METH_NOARGS
},
678 {"getrefcount", (PyCFunction
)sys_getrefcount
, METH_O
, getrefcount_doc
},
679 {"getrecursionlimit", (PyCFunction
)sys_getrecursionlimit
, METH_NOARGS
,
680 getrecursionlimit_doc
},
681 {"_getframe", sys_getframe
, METH_VARARGS
, getframe_doc
},
683 {"getwindowsversion", (PyCFunction
)sys_getwindowsversion
, METH_NOARGS
,
684 getwindowsversion_doc
},
685 #endif /* MS_WINDOWS */
687 {"mdebug", sys_mdebug
, METH_VARARGS
},
689 #ifdef Py_USING_UNICODE
690 {"setdefaultencoding", sys_setdefaultencoding
, METH_VARARGS
,
691 setdefaultencoding_doc
},
693 {"setcheckinterval", sys_setcheckinterval
, METH_VARARGS
,
694 setcheckinterval_doc
},
696 {"setdlopenflags", sys_setdlopenflags
, METH_VARARGS
,
699 {"setprofile", sys_setprofile
, METH_O
, setprofile_doc
},
700 {"setrecursionlimit", sys_setrecursionlimit
, METH_VARARGS
,
701 setrecursionlimit_doc
},
702 {"settrace", sys_settrace
, METH_O
, settrace_doc
},
703 {NULL
, NULL
} /* sentinel */
707 list_builtin_module_names(void)
709 PyObject
*list
= PyList_New(0);
713 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
714 PyObject
*name
= PyString_FromString(
715 PyImport_Inittab
[i
].name
);
718 PyList_Append(list
, name
);
721 if (PyList_Sort(list
) != 0) {
726 PyObject
*v
= PyList_AsTuple(list
);
733 static PyObject
*warnoptions
= NULL
;
736 PySys_ResetWarnOptions(void)
738 if (warnoptions
== NULL
|| !PyList_Check(warnoptions
))
740 PyList_SetSlice(warnoptions
, 0, PyList_GET_SIZE(warnoptions
), NULL
);
744 PySys_AddWarnOption(char *s
)
748 if (warnoptions
== NULL
|| !PyList_Check(warnoptions
)) {
749 Py_XDECREF(warnoptions
);
750 warnoptions
= PyList_New(0);
751 if (warnoptions
== NULL
)
754 str
= PyString_FromString(s
);
756 PyList_Append(warnoptions
, str
);
761 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
762 Two literals concatenated works just fine. If you have a K&R compiler
763 or other abomination that however *does* understand longer strings,
764 get rid of the !!! comment in the middle and the quotes that surround it. */
767 "This module provides access to some objects used or maintained by the\n\
768 interpreter and to functions that interact strongly with the interpreter.\n\
772 argv -- command line arguments; argv[0] is the script pathname if known\n\
773 path -- module search path; path[0] is the script directory, else ''\n\
774 modules -- dictionary of loaded modules\n\
776 displayhook -- called to show results in an interactive session\n\
777 excepthook -- called to handle any uncaught exception other than SystemExit\n\
778 To customize printing in an interactive session or to install a custom\n\
779 top-level exception handler, assign other functions to replace these.\n\
781 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
782 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
784 stdin -- standard input file object; used by raw_input() and input()\n\
785 stdout -- standard output file object; used by the print statement\n\
786 stderr -- standard error object; used for error messages\n\
787 By assigning other file objects (or objects that behave like files)\n\
788 to these, it is possible to redirect all of the interpreter's I/O.\n\
790 last_type -- type of last uncaught exception\n\
791 last_value -- value of last uncaught exception\n\
792 last_traceback -- traceback of last uncaught exception\n\
793 These three are only available in an interactive session after a\n\
794 traceback has been printed.\n\
796 exc_type -- type of exception currently being handled\n\
797 exc_value -- value of exception currently being handled\n\
798 exc_traceback -- traceback of exception currently being handled\n\
799 The function exc_info() should be used instead of these three,\n\
800 because it is thread-safe.\n\
803 /* concatenating string here */
808 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
809 maxunicode -- the largest supported character\n\
810 builtin_module_names -- tuple of module names built into this interpreter\n\
811 version -- the version of this interpreter as a string\n\
812 version_info -- version information as a tuple\n\
813 hexversion -- version information encoded as a single integer\n\
814 copyright -- copyright notice pertaining to this interpreter\n\
815 platform -- platform identifier\n\
816 executable -- pathname of this Python interpreter\n\
817 prefix -- prefix used to find the Python library\n\
818 exec_prefix -- prefix used to find the machine-specific Python library\n\
822 /* concatenating string here */
824 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
825 winver -- [Windows only] version number of the Python DLL\n\
828 #endif /* MS_WINDOWS */
830 "__stdin__ -- the original stdin; don't touch!\n\
831 __stdout__ -- the original stdout; don't touch!\n\
832 __stderr__ -- the original stderr; don't touch!\n\
833 __displayhook__ -- the original displayhook; don't touch!\n\
834 __excepthook__ -- the original excepthook; don't touch!\n\
838 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
839 excepthook() -- print an exception and its traceback to sys.stderr\n\
840 exc_info() -- return thread-safe information about the current exception\n\
841 exc_clear() -- clear the exception state for the current thread\n\
842 exit() -- exit the interpreter by raising SystemExit\n\
843 getdlopenflags() -- returns flags to be used for dlopen() calls\n\
844 getrefcount() -- return the reference count for an object (plus one :-)\n\
845 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
846 setcheckinterval() -- control how often the interpreter checks for events\n\
847 setdlopenflags() -- set the flags to be used for dlopen() calls\n\
848 setprofile() -- set the global profiling function\n\
849 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
850 settrace() -- set the global debug tracing function\n\
853 /* end of sys_doc */ ;
858 PyObject
*m
, *v
, *sysdict
;
859 PyObject
*sysin
, *sysout
, *syserr
;
862 m
= Py_InitModule3("sys", sys_methods
, sys_doc
);
863 sysdict
= PyModule_GetDict(m
);
865 sysin
= PyFile_FromFile(stdin
, "<stdin>", "r", NULL
);
866 sysout
= PyFile_FromFile(stdout
, "<stdout>", "w", NULL
);
867 syserr
= PyFile_FromFile(stderr
, "<stderr>", "w", NULL
);
868 if (PyErr_Occurred())
870 PyDict_SetItemString(sysdict
, "stdin", sysin
);
871 PyDict_SetItemString(sysdict
, "stdout", sysout
);
872 PyDict_SetItemString(sysdict
, "stderr", syserr
);
873 /* Make backup copies for cleanup */
874 PyDict_SetItemString(sysdict
, "__stdin__", sysin
);
875 PyDict_SetItemString(sysdict
, "__stdout__", sysout
);
876 PyDict_SetItemString(sysdict
, "__stderr__", syserr
);
877 PyDict_SetItemString(sysdict
, "__displayhook__",
878 PyDict_GetItemString(sysdict
, "displayhook"));
879 PyDict_SetItemString(sysdict
, "__excepthook__",
880 PyDict_GetItemString(sysdict
, "excepthook"));
884 PyDict_SetItemString(sysdict
, "version",
885 v
= PyString_FromString(Py_GetVersion()));
887 PyDict_SetItemString(sysdict
, "hexversion",
888 v
= PyInt_FromLong(PY_VERSION_HEX
));
891 * These release level checks are mutually exclusive and cover
892 * the field, so don't get too fancy with the pre-processor!
894 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
896 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
898 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
900 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
903 PyDict_SetItemString(sysdict
, "version_info",
904 v
= Py_BuildValue("iiisi", PY_MAJOR_VERSION
,
909 PyDict_SetItemString(sysdict
, "api_version",
910 v
= PyInt_FromLong(PYTHON_API_VERSION
));
912 PyDict_SetItemString(sysdict
, "copyright",
913 v
= PyString_FromString(Py_GetCopyright()));
915 PyDict_SetItemString(sysdict
, "platform",
916 v
= PyString_FromString(Py_GetPlatform()));
918 PyDict_SetItemString(sysdict
, "executable",
919 v
= PyString_FromString(Py_GetProgramFullPath()));
921 PyDict_SetItemString(sysdict
, "prefix",
922 v
= PyString_FromString(Py_GetPrefix()));
924 PyDict_SetItemString(sysdict
, "exec_prefix",
925 v
= PyString_FromString(Py_GetExecPrefix()));
927 PyDict_SetItemString(sysdict
, "maxint",
928 v
= PyInt_FromLong(PyInt_GetMax()));
930 #ifdef Py_USING_UNICODE
931 PyDict_SetItemString(sysdict
, "maxunicode",
932 v
= PyInt_FromLong(PyUnicode_GetMax()));
935 PyDict_SetItemString(sysdict
, "builtin_module_names",
936 v
= list_builtin_module_names());
939 /* Assumes that longs are at least 2 bytes long.
941 unsigned long number
= 1;
944 s
= (char *) &number
;
949 PyDict_SetItemString(sysdict
, "byteorder",
950 v
= PyString_FromString(value
));
954 PyDict_SetItemString(sysdict
, "dllhandle",
955 v
= PyLong_FromVoidPtr(PyWin_DLLhModule
));
957 PyDict_SetItemString(sysdict
, "winver",
958 v
= PyString_FromString(PyWin_DLLVersionString
));
961 if (warnoptions
== NULL
) {
962 warnoptions
= PyList_New(0);
965 Py_INCREF(warnoptions
);
967 if (warnoptions
!= NULL
) {
968 PyDict_SetItemString(sysdict
, "warnoptions", warnoptions
);
971 if (PyErr_Occurred())
977 makepathobject(char *path
, int delim
)
985 while ((p
= strchr(p
, delim
)) != NULL
) {
993 p
= strchr(path
, delim
);
995 p
= strchr(path
, '\0'); /* End of string */
996 w
= PyString_FromStringAndSize(path
, (int) (p
- path
));
1001 PyList_SetItem(v
, i
, w
);
1010 PySys_SetPath(char *path
)
1013 if ((v
= makepathobject(path
, DELIM
)) == NULL
)
1014 Py_FatalError("can't create sys.path");
1015 if (PySys_SetObject("path", v
) != 0)
1016 Py_FatalError("can't assign sys.path");
1021 makeargvobject(int argc
, char **argv
)
1024 if (argc
<= 0 || argv
== NULL
) {
1025 /* Ensure at least one (empty) argument is seen */
1026 static char *empty_argv
[1] = {""};
1030 av
= PyList_New(argc
);
1033 for (i
= 0; i
< argc
; i
++) {
1034 PyObject
*v
= PyString_FromString(argv
[i
]);
1040 PyList_SetItem(av
, i
, v
);
1047 PySys_SetArgv(int argc
, char **argv
)
1049 #if defined(HAVE_REALPATH)
1050 char fullpath
[MAXPATHLEN
];
1051 #elif defined(MS_WINDOWS)
1052 char fullpath
[MAX_PATH
];
1054 PyObject
*av
= makeargvobject(argc
, argv
);
1055 PyObject
*path
= PySys_GetObject("path");
1057 Py_FatalError("no mem for sys.argv");
1058 if (PySys_SetObject("argv", av
) != 0)
1059 Py_FatalError("can't assign sys.argv");
1061 char *argv0
= argv
[0];
1065 #ifdef HAVE_READLINK
1066 char link
[MAXPATHLEN
+1];
1067 char argv0copy
[2*MAXPATHLEN
+1];
1069 if (argc
> 0 && argv0
!= NULL
)
1070 nr
= readlink(argv0
, link
, MAXPATHLEN
);
1072 /* It's a symlink */
1075 argv0
= link
; /* Link to absolute path */
1076 else if (strchr(link
, SEP
) == NULL
)
1077 ; /* Link without path */
1079 /* Must join(dirname(argv0), link) */
1080 char *q
= strrchr(argv0
, SEP
);
1082 argv0
= link
; /* argv0 without path */
1084 /* Must make a copy */
1085 strcpy(argv0copy
, argv0
);
1086 q
= strrchr(argv0copy
, SEP
);
1092 #endif /* HAVE_READLINK */
1093 #if SEP == '\\' /* Special case for MS filename syntax */
1094 if (argc
> 0 && argv0
!= NULL
) {
1098 if (GetFullPathName(argv0
,
1105 p
= strrchr(argv0
, SEP
);
1106 /* Test for alternate separator */
1107 q
= strrchr(p
? p
: argv0
, '/');
1112 if (n
> 1 && p
[-1] != ':')
1113 n
--; /* Drop trailing separator */
1116 #else /* All other filename syntaxes */
1117 if (argc
> 0 && argv0
!= NULL
) {
1118 #if defined(HAVE_REALPATH)
1119 if (realpath(argv0
, fullpath
)) {
1123 p
= strrchr(argv0
, SEP
);
1128 #else /* don't include trailing separator */
1131 #if SEP == '/' /* Special case for Unix filename syntax */
1133 n
--; /* Drop trailing separator */
1136 #endif /* All others */
1137 a
= PyString_FromStringAndSize(argv0
, n
);
1139 Py_FatalError("no mem for sys.path insertion");
1140 if (PyList_Insert(path
, 0, a
) < 0)
1141 Py_FatalError("sys.path.insert(0) failed");
1148 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1149 Adapted from code submitted by Just van Rossum.
1151 PySys_WriteStdout(format, ...)
1152 PySys_WriteStderr(format, ...)
1154 The first function writes to sys.stdout; the second to sys.stderr. When
1155 there is a problem, they write to the real (C level) stdout or stderr;
1156 no exceptions are raised.
1158 Both take a printf-style format string as their first argument followed
1159 by a variable length argument list determined by the format string.
1163 The format should limit the total size of the formatted output string to
1164 1000 bytes. In particular, this means that no unrestricted "%s" formats
1165 should occur; these should be limited using "%.<N>s where <N> is a
1166 decimal number calculated so that <N> plus the maximum size of other
1167 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1168 which can print hundreds of digits for very large numbers.
1173 mywrite(char *name
, FILE *fp
, const char *format
, va_list va
)
1176 PyObject
*error_type
, *error_value
, *error_traceback
;
1178 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
1179 file
= PySys_GetObject(name
);
1180 if (file
== NULL
|| PyFile_AsFile(file
) == fp
)
1181 vfprintf(fp
, format
, va
);
1184 const int written
= PyOS_vsnprintf(buffer
, sizeof(buffer
),
1186 if (PyFile_WriteString(buffer
, file
) != 0) {
1190 if (written
< 0 || written
>= sizeof(buffer
)) {
1191 const char *truncated
= "... truncated";
1192 if (PyFile_WriteString(truncated
, file
) != 0) {
1194 fputs(truncated
, fp
);
1198 PyErr_Restore(error_type
, error_value
, error_traceback
);
1202 PySys_WriteStdout(const char *format
, ...)
1206 va_start(va
, format
);
1207 mywrite("stdout", stdout
, format
, va
);
1212 PySys_WriteStderr(const char *format
, ...)
1216 va_start(va
, format
);
1217 mywrite("stderr", stderr
, format
, va
);