Adds a profile-opt target for easy compilation of a python binary using
[python.git] / Python / sysmodule.c
blobd6ccd17b5a4b7f69e9bd5ddbfb2dc87b8c5855c4
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 "structseq.h"
19 #include "code.h"
20 #include "frameobject.h"
21 #include "eval.h"
23 #include "osdefs.h"
25 #ifdef MS_WINDOWS
26 #define WIN32_LEAN_AND_MEAN
27 #include "windows.h"
28 #endif /* MS_WINDOWS */
30 #ifdef MS_COREDLL
31 extern void *PyWin_DLLhModule;
32 /* A string loaded from the DLL at startup: */
33 extern const char *PyWin_DLLVersionString;
34 #endif
36 #ifdef __VMS
37 #include <unixlib.h>
38 #endif
40 #ifdef MS_WINDOWS
41 #include <windows.h>
42 #endif
44 #ifdef HAVE_LANGINFO_H
45 #include <locale.h>
46 #include <langinfo.h>
47 #endif
49 PyObject *
50 PySys_GetObject(char *name)
52 PyThreadState *tstate = PyThreadState_GET();
53 PyObject *sd = tstate->interp->sysdict;
54 if (sd == NULL)
55 return NULL;
56 return PyDict_GetItemString(sd, name);
59 FILE *
60 PySys_GetFile(char *name, FILE *def)
62 FILE *fp = NULL;
63 PyObject *v = PySys_GetObject(name);
64 if (v != NULL && PyFile_Check(v))
65 fp = PyFile_AsFile(v);
66 if (fp == NULL)
67 fp = def;
68 return fp;
71 int
72 PySys_SetObject(char *name, PyObject *v)
74 PyThreadState *tstate = PyThreadState_GET();
75 PyObject *sd = tstate->interp->sysdict;
76 if (v == NULL) {
77 if (PyDict_GetItemString(sd, name) == NULL)
78 return 0;
79 else
80 return PyDict_DelItemString(sd, name);
82 else
83 return PyDict_SetItemString(sd, name, v);
86 static PyObject *
87 sys_displayhook(PyObject *self, PyObject *o)
89 PyObject *outf;
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__");
96 return NULL;
99 /* Print value except if None */
100 /* After printing, also assign to '_' */
101 /* Before, set '_' to None to avoid recursion */
102 if (o == Py_None) {
103 Py_INCREF(Py_None);
104 return Py_None;
106 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
107 return NULL;
108 if (Py_FlushLine() != 0)
109 return NULL;
110 outf = PySys_GetObject("stdout");
111 if (outf == NULL) {
112 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
113 return NULL;
115 if (PyFile_WriteObject(o, outf, 0) != 0)
116 return NULL;
117 PyFile_SoftSpace(outf, 1);
118 if (Py_FlushLine() != 0)
119 return NULL;
120 if (PyObject_SetAttrString(builtins, "_", o) != 0)
121 return NULL;
122 Py_INCREF(Py_None);
123 return Py_None;
126 PyDoc_STRVAR(displayhook_doc,
127 "displayhook(object) -> None\n"
128 "\n"
129 "Print an object to sys.stdout and also save it in __builtin__.\n"
132 static PyObject *
133 sys_excepthook(PyObject* self, PyObject* args)
135 PyObject *exc, *value, *tb;
136 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
137 return NULL;
138 PyErr_Display(exc, value, tb);
139 Py_INCREF(Py_None);
140 return Py_None;
143 PyDoc_STRVAR(excepthook_doc,
144 "excepthook(exctype, value, traceback) -> None\n"
145 "\n"
146 "Handle an exception by displaying it with a traceback on sys.stderr.\n"
149 static PyObject *
150 sys_exc_info(PyObject *self, PyObject *noargs)
152 PyThreadState *tstate;
153 tstate = PyThreadState_GET();
154 return Py_BuildValue(
155 "(OOO)",
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."
169 static PyObject *
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)
179 return NULL;
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);
190 Py_XDECREF(tmp_tb);
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);
195 Py_INCREF(Py_None);
196 return 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."
208 static PyObject *
209 sys_exit(PyObject *self, PyObject *args)
211 PyObject *exit_code = 0;
212 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
213 return NULL;
214 /* Raise SystemExit so callers may catch it or clean up. */
215 PyErr_SetObject(PyExc_SystemExit, exit_code);
216 return NULL;
219 PyDoc_STRVAR(exit_doc,
220 "exit([status])\n\
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
231 static PyObject *
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\
241 implementation."
244 static PyObject *
245 sys_setdefaultencoding(PyObject *self, PyObject *args)
247 char *encoding;
248 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
249 return NULL;
250 if (PyUnicode_SetDefaultEncoding(encoding))
251 return NULL;
252 Py_INCREF(Py_None);
253 return Py_None;
256 PyDoc_STRVAR(setdefaultencoding_doc,
257 "setdefaultencoding(encoding)\n\
259 Set the current default string encoding used by the Unicode implementation."
262 static PyObject *
263 sys_getfilesystemencoding(PyObject *self)
265 if (Py_FileSystemDefaultEncoding)
266 return PyString_FromString(Py_FileSystemDefaultEncoding);
267 Py_INCREF(Py_None);
268 return Py_None;
271 PyDoc_STRVAR(getfilesystemencoding_doc,
272 "getfilesystemencoding() -> string\n\
274 Return the encoding used to convert Unicode filenames in\n\
275 operating system filenames."
278 #endif
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};
286 static int
287 trace_init(void)
289 static char *whatnames[7] = {"call", "exception", "line", "return",
290 "c_call", "c_exception", "c_return"};
291 PyObject *name;
292 int i;
293 for (i = 0; i < 7; ++i) {
294 if (whatstrings[i] == NULL) {
295 name = PyString_InternFromString(whatnames[i]);
296 if (name == NULL)
297 return -1;
298 whatstrings[i] = name;
301 return 0;
305 static PyObject *
306 call_trampoline(PyThreadState *tstate, PyObject* callback,
307 PyFrameObject *frame, int what, PyObject *arg)
309 PyObject *args = PyTuple_New(3);
310 PyObject *whatstr;
311 PyObject *result;
313 if (args == NULL)
314 return NULL;
315 Py_INCREF(frame);
316 whatstr = whatstrings[what];
317 Py_INCREF(whatstr);
318 if (arg == NULL)
319 arg = Py_None;
320 Py_INCREF(arg);
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);
329 if (result == NULL)
330 PyTraceBack_Here(frame);
332 /* cleanup */
333 Py_DECREF(args);
334 return result;
337 static int
338 profile_trampoline(PyObject *self, PyFrameObject *frame,
339 int what, PyObject *arg)
341 PyThreadState *tstate = frame->f_tstate;
342 PyObject *result;
344 if (arg == NULL)
345 arg = Py_None;
346 result = call_trampoline(tstate, self, frame, what, arg);
347 if (result == NULL) {
348 PyEval_SetProfile(NULL, NULL);
349 return -1;
351 Py_DECREF(result);
352 return 0;
355 static int
356 trace_trampoline(PyObject *self, PyFrameObject *frame,
357 int what, PyObject *arg)
359 PyThreadState *tstate = frame->f_tstate;
360 PyObject *callback;
361 PyObject *result;
363 if (what == PyTrace_CALL)
364 callback = self;
365 else
366 callback = frame->f_trace;
367 if (callback == NULL)
368 return 0;
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;
374 return -1;
376 if (result != Py_None) {
377 PyObject *temp = frame->f_trace;
378 frame->f_trace = NULL;
379 Py_XDECREF(temp);
380 frame->f_trace = result;
382 else {
383 Py_DECREF(result);
385 return 0;
388 static PyObject *
389 sys_settrace(PyObject *self, PyObject *args)
391 if (trace_init() == -1)
392 return NULL;
393 if (args == Py_None)
394 PyEval_SetTrace(NULL, NULL);
395 else
396 PyEval_SetTrace(trace_trampoline, args);
397 Py_INCREF(Py_None);
398 return Py_None;
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."
408 static PyObject *
409 sys_gettrace(PyObject *self, PyObject *args)
411 PyThreadState *tstate = PyThreadState_GET();
412 PyObject *temp = tstate->c_traceobj;
414 if (temp == NULL)
415 temp = Py_None;
416 Py_INCREF(temp);
417 return temp;
420 PyDoc_STRVAR(gettrace_doc,
421 "gettrace()\n\
423 Return the global debug tracing function set with sys.settrace.\n\
424 See the debugger chapter in the library manual."
427 static PyObject *
428 sys_setprofile(PyObject *self, PyObject *args)
430 if (trace_init() == -1)
431 return NULL;
432 if (args == Py_None)
433 PyEval_SetProfile(NULL, NULL);
434 else
435 PyEval_SetProfile(profile_trampoline, args);
436 Py_INCREF(Py_None);
437 return Py_None;
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."
447 static PyObject *
448 sys_getprofile(PyObject *self, PyObject *args)
450 PyThreadState *tstate = PyThreadState_GET();
451 PyObject *temp = tstate->c_profileobj;
453 if (temp == NULL)
454 temp = Py_None;
455 Py_INCREF(temp);
456 return temp;
459 PyDoc_STRVAR(getprofile_doc,
460 "getprofile()\n\
462 Return the profiling function set with sys.setprofile.\n\
463 See the profiler chapter in the library manual."
466 static PyObject *
467 sys_setcheckinterval(PyObject *self, PyObject *args)
469 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
470 return NULL;
471 Py_INCREF(Py_None);
472 return Py_None;
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."
482 static PyObject *
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()."
492 #ifdef WITH_TSC
493 static PyObject *
494 sys_settscdump(PyObject *self, PyObject *args)
496 int bool;
497 PyThreadState *tstate = PyThreadState_Get();
499 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
500 return NULL;
501 if (bool)
502 tstate->interp->tscdump = 1;
503 else
504 tstate->interp->tscdump = 0;
505 Py_INCREF(Py_None);
506 return Py_None;
510 PyDoc_STRVAR(settscdump_doc,
511 "settscdump(bool)\n\
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."
517 #endif /* TSC */
519 static PyObject *
520 sys_setrecursionlimit(PyObject *self, PyObject *args)
522 int new_limit;
523 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
524 return NULL;
525 if (new_limit <= 0) {
526 PyErr_SetString(PyExc_ValueError,
527 "recursion limit must be positive");
528 return NULL;
530 Py_SetRecursionLimit(new_limit);
531 Py_INCREF(Py_None);
532 return Py_None;
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\
541 dependent."
544 static PyObject *
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."
558 #ifdef MS_WINDOWS
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\
569 static PyObject *
570 sys_getwindowsversion(PyObject *self)
572 OSVERSIONINFO ver;
573 ver.dwOSVersionInfoSize = sizeof(ver);
574 if (!GetVersionEx(&ver))
575 return PyErr_SetFromWindowsErr(0);
576 return Py_BuildValue("HHHHs",
577 ver.dwMajorVersion,
578 ver.dwMinorVersion,
579 ver.dwBuildNumber,
580 ver.dwPlatformId,
581 ver.szCSDVersion);
584 #endif /* MS_WINDOWS */
586 #ifdef HAVE_DLOPEN
587 static PyObject *
588 sys_setdlopenflags(PyObject *self, PyObject *args)
590 int new_val;
591 PyThreadState *tstate = PyThreadState_GET();
592 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
593 return NULL;
594 if (!tstate)
595 return NULL;
596 tstate->interp->dlopenflags = new_val;
597 Py_INCREF(Py_None);
598 return Py_None;
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)"
611 static PyObject *
612 sys_getdlopenflags(PyObject *self, PyObject *args)
614 PyThreadState *tstate = PyThreadState_GET();
615 if (!tstate)
616 return NULL;
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."
626 #endif
628 #ifdef USE_MALLOPT
629 /* Link with -lmalloc (or -lmpc) on an SGI */
630 #include <malloc.h>
632 static PyObject *
633 sys_mdebug(PyObject *self, PyObject *args)
635 int flag;
636 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
637 return NULL;
638 mallopt(M_DEBUG, flag);
639 Py_INCREF(Py_None);
640 return Py_None;
642 #endif /* USE_MALLOPT */
644 static PyObject *
645 sys_getrefcount(PyObject *self, PyObject *arg)
647 return PyInt_FromSsize_t(arg->ob_refcnt);
650 #ifdef Py_REF_DEBUG
651 static PyObject *
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()."
666 #ifdef COUNT_ALLOCS
667 static PyObject *
668 sys_getcounts(PyObject *self)
670 extern PyObject *get_counts(void);
672 return get_counts();
674 #endif
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\
685 purposes only."
688 static PyObject *
689 sys_getframe(PyObject *self, PyObject *args)
691 PyFrameObject *f = PyThreadState_GET()->frame;
692 int depth = -1;
694 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
695 return NULL;
697 while (depth > 0 && f != NULL) {
698 f = f->f_back;
699 --depth;
701 if (f == NULL) {
702 PyErr_SetString(PyExc_ValueError,
703 "call stack is not deep enough");
704 return NULL;
706 Py_INCREF(f);
707 return (PyObject*)f;
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."
719 static PyObject *
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."
733 static PyObject *
734 sys_call_tracing(PyObject *self, PyObject *args)
736 PyObject *func, *funcargs;
737 if (!PyArg_UnpackTuple(args, "call_tracing", 2, 2, &func, &funcargs))
738 return NULL;
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\
756 4. PyMethod calls\n\
757 5. PyMethod calls on bound methods\n\
758 6. PyType calls\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()"
765 #ifdef __cplusplus
766 extern "C" {
767 #endif
769 #ifdef Py_TRACE_REFS
770 /* Defined in objects.c because it uses static globals if that file */
771 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
772 #endif
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 *);
777 #endif
779 #ifdef __cplusplus
781 #endif
783 static PyObject *
784 sys_clear_type_cache(PyObject* self, PyObject* args)
786 PyType_ClearCache();
787 Py_RETURN_NONE;
790 PyDoc_STRVAR(sys_clear_type_cache__doc__,
791 "_clear_type_cache() -> None\n\
792 Clear the internal type lookup cache.");
795 static PyObject *
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,
805 fsum, fbc, fbf);
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,
816 callstats_doc},
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,
822 current_frames_doc},
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},
831 #endif
832 #ifdef HAVE_DLOPEN
833 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
834 getdlopenflags_doc},
835 #endif
836 #ifdef COUNT_ALLOCS
837 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
838 #endif
839 #ifdef DYNAMIC_EXECUTION_PROFILE
840 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
841 #endif
842 #ifdef Py_USING_UNICODE
843 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
844 METH_NOARGS, getfilesystemencoding_doc},
845 #endif
846 #ifdef Py_TRACE_REFS
847 {"getobjects", _Py_GetObjects, METH_VARARGS},
848 #endif
849 #ifdef Py_REF_DEBUG
850 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
851 #endif
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},
856 #ifdef MS_WINDOWS
857 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
858 getwindowsversion_doc},
859 #endif /* MS_WINDOWS */
860 #ifdef USE_MALLOPT
861 {"mdebug", sys_mdebug, METH_VARARGS},
862 #endif
863 #ifdef Py_USING_UNICODE
864 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
865 setdefaultencoding_doc},
866 #endif
867 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
868 setcheckinterval_doc},
869 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
870 getcheckinterval_doc},
871 #ifdef HAVE_DLOPEN
872 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
873 setdlopenflags_doc},
874 #endif
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},
879 #ifdef WITH_TSC
880 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
881 #endif
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 */
888 static PyObject *
889 list_builtin_module_names(void)
891 PyObject *list = PyList_New(0);
892 int i;
893 if (list == NULL)
894 return NULL;
895 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
896 PyObject *name = PyString_FromString(
897 PyImport_Inittab[i].name);
898 if (name == NULL)
899 break;
900 PyList_Append(list, name);
901 Py_DECREF(name);
903 if (PyList_Sort(list) != 0) {
904 Py_DECREF(list);
905 list = NULL;
907 if (list) {
908 PyObject *v = PyList_AsTuple(list);
909 Py_DECREF(list);
910 list = v;
912 return list;
915 static PyObject *warnoptions = NULL;
917 void
918 PySys_ResetWarnOptions(void)
920 if (warnoptions == NULL || !PyList_Check(warnoptions))
921 return;
922 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
925 void
926 PySys_AddWarnOption(char *s)
928 PyObject *str;
930 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
931 Py_XDECREF(warnoptions);
932 warnoptions = PyList_New(0);
933 if (warnoptions == NULL)
934 return;
936 str = PyString_FromString(s);
937 if (str != NULL) {
938 PyList_Append(warnoptions, str);
939 Py_DECREF(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. */
953 PyDoc_VAR(sys_doc) =
954 PyDoc_STR(
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\
958 Dynamic objects:\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 */
992 PyDoc_STR(
993 "\n\
994 Static objects:\n\
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\
1009 #ifdef MS_WINDOWS
1010 /* concatenating string here */
1011 PyDoc_STR(
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 */
1017 PyDoc_STR(
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\
1024 Functions:\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 */ ;
1045 static int
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;
1061 static void
1062 svnversion_init(void)
1064 const char *python, *br_start, *br_end, *br_end2, *svnversion;
1065 Py_ssize_t len;
1066 int istag;
1068 if (svn_initialized)
1069 return;
1071 python = strstr(headurl, "/python/");
1072 if (!python) {
1073 /* XXX quick hack to get bzr working */
1074 *patchlevel_revision = '\0';
1075 strcpy(branch, "");
1076 strcpy(shortbranch, "unknown");
1077 svn_revision = "";
1078 return;
1079 /* Py_FatalError("subversion keywords missing"); */
1082 br_start = python + 8;
1083 br_end = strchr(br_start, '/');
1084 assert(br_end);
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);
1099 branch[len] = '\0';
1101 len = br_end2 - (br_end + 1);
1102 strncpy(shortbranch, br_end + 1, len);
1103 shortbranch[len] = '\0';
1105 else {
1106 Py_FatalError("bad HeadURL");
1107 return;
1111 svnversion = _Py_svnversion();
1112 if (strcmp(svnversion, "exported") != 0)
1113 svn_revision = svnversion;
1114 else if (istag) {
1115 len = strlen(_patchlevel_revision);
1116 assert(len >= 13);
1117 assert(len < (sizeof(patchlevel_revision) + 13));
1118 strncpy(patchlevel_revision, _patchlevel_revision + 11,
1119 len - 13);
1120 patchlevel_revision[len - 13] = '\0';
1121 svn_revision = patchlevel_revision;
1123 else
1124 svn_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 */
1132 const char*
1133 Py_SubversionRevision()
1135 svnversion_init();
1136 return svn_revision;
1139 const char*
1140 Py_SubversionShortBranch()
1142 svnversion_init();
1143 return shortbranch;
1147 PyDoc_STRVAR(flags__doc__,
1148 "sys.flags\n\
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[] = {
1155 {"debug", "-d"},
1156 {"py3k_warning", "-3"},
1157 {"division_warning", "-Q"},
1158 {"division_new", "-Qnew"},
1159 {"inspect", "-i"},
1160 {"interactive", "-i"},
1161 {"optimize", "-O or -OO"},
1162 {"dont_write_bytecode", "-B"},
1163 /* {"no_user_site", "-s"}, */
1164 {"no_site", "-S"},
1165 {"ignore_environment", "-E"},
1166 {"tabcheck", "-t or -tt"},
1167 {"verbose", "-v"},
1168 #ifdef RISCOS
1169 {"riscos_wimp", "???"},
1170 #endif
1171 /* {"unbuffered", "-u"}, */
1172 {"unicode", "-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 */
1182 #ifdef RISCOS
1184 #else
1186 #endif
1189 static PyObject*
1190 make_flags(void)
1192 int pos = 0;
1193 PyObject *seq;
1195 seq = PyStructSequence_New(&FlagsType);
1196 if (seq == NULL)
1197 return NULL;
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);
1215 #ifdef RISCOS
1216 SetFlag(Py_RISCOSWimpFlag);
1217 #endif
1218 /* SetFlag(saw_unbuffered_flag); */
1219 SetFlag(Py_UnicodeFlag);
1220 /* SetFlag(skipfirstline); */
1221 SetFlag(Py_BytesWarningFlag);
1222 #undef SetFlag
1224 if (PyErr_Occurred()) {
1225 return NULL;
1227 return seq;
1230 PyObject *
1231 _PySys_Init(void)
1233 PyObject *m, *v, *sysdict;
1234 PyObject *sysin, *sysout, *syserr;
1235 char *s;
1236 #ifdef MS_WINDOWS
1237 char buf[128];
1238 #endif
1240 m = Py_InitModule3("sys", sys_methods, sys_doc);
1241 if (m == NULL)
1242 return NULL;
1243 sysdict = PyModule_GetDict(m);
1244 #define SET_SYS_FROM_STRING(key, value) \
1245 v = value; \
1246 if (v != NULL) \
1247 PyDict_SetItemString(sysdict, key, v); \
1248 Py_XDECREF(v)
1251 /* XXX: does this work on Win/Win64? (see posix_fstat) */
1252 struct stat sb;
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");
1258 exit(EXIT_FAILURE);
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())
1275 return NULL;
1276 #ifdef MS_WINDOWS
1277 if(isatty(_fileno(stdin)) && PyFile_Check(sysin)) {
1278 sprintf(buf, "cp%d", GetConsoleCP());
1279 if (!PyFile_SetEncoding(sysin, buf))
1280 return NULL;
1282 if(isatty(_fileno(stdout)) && PyFile_Check(sysout)) {
1283 sprintf(buf, "cp%d", GetConsoleOutputCP());
1284 if (!PyFile_SetEncoding(sysout, buf))
1285 return NULL;
1287 if(isatty(_fileno(stderr)) && PyFile_Check(syserr)) {
1288 sprintf(buf, "cp%d", GetConsoleOutputCP());
1289 if (!PyFile_SetEncoding(syserr, buf))
1290 return NULL;
1292 #endif
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"));
1305 Py_XDECREF(sysin);
1306 Py_XDECREF(sysout);
1307 Py_XDECREF(syserr);
1309 SET_SYS_FROM_STRING("version",
1310 PyString_FromString(Py_GetVersion()));
1311 SET_SYS_FROM_STRING("hexversion",
1312 PyInt_FromLong(PY_VERSION_HEX));
1313 svnversion_init();
1314 SET_SYS_FROM_STRING("subversion",
1315 Py_BuildValue("(ssz)", "CPython", branch,
1316 svn_revision));
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
1324 s = "alpha";
1325 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
1326 s = "beta";
1327 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
1328 s = "candidate";
1329 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
1330 s = "final";
1331 #endif
1333 SET_SYS_FROM_STRING("version_info",
1334 Py_BuildValue("iiisi", PY_MAJOR_VERSION,
1335 PY_MINOR_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",
1355 PyFloat_GetInfo());
1356 #ifdef Py_USING_UNICODE
1357 SET_SYS_FROM_STRING("maxunicode",
1358 PyInt_FromLong(PyUnicode_GetMax()));
1359 #endif
1360 SET_SYS_FROM_STRING("builtin_module_names",
1361 list_builtin_module_names());
1363 /* Assumes that longs are at least 2 bytes long.
1364 Should be safe! */
1365 unsigned long number = 1;
1366 char *value;
1368 s = (char *) &number;
1369 if (s[0] == 0)
1370 value = "big";
1371 else
1372 value = "little";
1373 SET_SYS_FROM_STRING("byteorder",
1374 PyString_FromString(value));
1376 #ifdef MS_COREDLL
1377 SET_SYS_FROM_STRING("dllhandle",
1378 PyLong_FromVoidPtr(PyWin_DLLhModule));
1379 SET_SYS_FROM_STRING("winver",
1380 PyString_FromString(PyWin_DLLVersionString));
1381 #endif
1382 if (warnoptions == NULL) {
1383 warnoptions = PyList_New(0);
1385 else {
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())
1401 return NULL;
1402 return m;
1405 static PyObject *
1406 makepathobject(char *path, int delim)
1408 int i, n;
1409 char *p;
1410 PyObject *v, *w;
1412 n = 1;
1413 p = path;
1414 while ((p = strchr(p, delim)) != NULL) {
1415 n++;
1416 p++;
1418 v = PyList_New(n);
1419 if (v == NULL)
1420 return NULL;
1421 for (i = 0; ; i++) {
1422 p = strchr(path, delim);
1423 if (p == NULL)
1424 p = strchr(path, '\0'); /* End of string */
1425 w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));
1426 if (w == NULL) {
1427 Py_DECREF(v);
1428 return NULL;
1430 PyList_SetItem(v, i, w);
1431 if (*p == '\0')
1432 break;
1433 path = p+1;
1435 return v;
1438 void
1439 PySys_SetPath(char *path)
1441 PyObject *v;
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");
1446 Py_DECREF(v);
1449 static PyObject *
1450 makeargvobject(int argc, char **argv)
1452 PyObject *av;
1453 if (argc <= 0 || argv == NULL) {
1454 /* Ensure at least one (empty) argument is seen */
1455 static char *empty_argv[1] = {""};
1456 argv = empty_argv;
1457 argc = 1;
1459 av = PyList_New(argc);
1460 if (av != NULL) {
1461 int i;
1462 for (i = 0; i < argc; i++) {
1463 #ifdef __VMS
1464 PyObject *v;
1466 /* argv[0] is the script pathname if known */
1467 if (i == 0) {
1468 char* fn = decc$translate_vms(argv[0]);
1469 if ((fn == (char *)0) || fn == (char *)-1)
1470 v = PyString_FromString(argv[0]);
1471 else
1472 v = PyString_FromString(
1473 decc$translate_vms(argv[0]));
1474 } else
1475 v = PyString_FromString(argv[i]);
1476 #else
1477 PyObject *v = PyString_FromString(argv[i]);
1478 #endif
1479 if (v == NULL) {
1480 Py_DECREF(av);
1481 av = NULL;
1482 break;
1484 PyList_SetItem(av, i, v);
1487 return av;
1490 void
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];
1497 #endif
1498 PyObject *av = makeargvobject(argc, argv);
1499 PyObject *path = PySys_GetObject("path");
1500 if (av == NULL)
1501 Py_FatalError("no mem for sys.argv");
1502 if (PySys_SetObject("argv", av) != 0)
1503 Py_FatalError("can't assign sys.argv");
1504 if (path != NULL) {
1505 char *argv0 = argv[0];
1506 char *p = NULL;
1507 Py_ssize_t n = 0;
1508 PyObject *a;
1509 #ifdef HAVE_READLINK
1510 char link[MAXPATHLEN+1];
1511 char argv0copy[2*MAXPATHLEN+1];
1512 int nr = 0;
1513 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)
1514 nr = readlink(argv0, link, MAXPATHLEN);
1515 if (nr > 0) {
1516 /* It's a symlink */
1517 link[nr] = '\0';
1518 if (link[0] == SEP)
1519 argv0 = link; /* Link to absolute path */
1520 else if (strchr(link, SEP) == NULL)
1521 ; /* Link without path */
1522 else {
1523 /* Must join(dirname(argv0), link) */
1524 char *q = strrchr(argv0, SEP);
1525 if (q == NULL)
1526 argv0 = link; /* argv0 without path */
1527 else {
1528 /* Must make a copy */
1529 strcpy(argv0copy, argv0);
1530 q = strrchr(argv0copy, SEP);
1531 strcpy(q+1, link);
1532 argv0 = argv0copy;
1536 #endif /* HAVE_READLINK */
1537 #if SEP == '\\' /* Special case for MS filename syntax */
1538 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
1539 char *q;
1540 #ifdef MS_WINDOWS
1541 char *ptemp;
1542 if (GetFullPathName(argv0,
1543 sizeof(fullpath),
1544 fullpath,
1545 &ptemp)) {
1546 argv0 = fullpath;
1548 #endif
1549 p = strrchr(argv0, SEP);
1550 /* Test for alternate separator */
1551 q = strrchr(p ? p : argv0, '/');
1552 if (q != NULL)
1553 p = q;
1554 if (p != NULL) {
1555 n = p + 1 - 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)) {
1564 argv0 = fullpath;
1566 #endif
1567 p = strrchr(argv0, SEP);
1569 if (p != NULL) {
1570 #ifndef RISCOS
1571 n = p + 1 - argv0;
1572 #else /* don't include trailing separator */
1573 n = p - argv0;
1574 #endif /* RISCOS */
1575 #if SEP == '/' /* Special case for Unix filename syntax */
1576 if (n > 1)
1577 n--; /* Drop trailing separator */
1578 #endif /* Unix */
1580 #endif /* All others */
1581 a = PyString_FromStringAndSize(argv0, n);
1582 if (a == NULL)
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");
1586 Py_DECREF(a);
1588 Py_DECREF(av);
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.
1605 *** WARNING ***
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.
1616 static void
1617 mywrite(char *name, FILE *fp, const char *format, va_list va)
1619 PyObject *file;
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);
1626 else {
1627 char buffer[1001];
1628 const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
1629 format, va);
1630 if (PyFile_WriteString(buffer, file) != 0) {
1631 PyErr_Clear();
1632 fputs(buffer, fp);
1634 if (written < 0 || (size_t)written >= sizeof(buffer)) {
1635 const char *truncated = "... truncated";
1636 if (PyFile_WriteString(truncated, file) != 0) {
1637 PyErr_Clear();
1638 fputs(truncated, fp);
1642 PyErr_Restore(error_type, error_value, error_traceback);
1645 void
1646 PySys_WriteStdout(const char *format, ...)
1648 va_list va;
1650 va_start(va, format);
1651 mywrite("stdout", stdout, format, va);
1652 va_end(va);
1655 void
1656 PySys_WriteStderr(const char *format, ...)
1658 va_list va;
1660 va_start(va, format);
1661 mywrite("stderr", stderr, format, va);
1662 va_end(va);