]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.10/Python/sysmodule.c
AppPkg/Applications/Python/Python-2.7.10: Initial Checkin part 1/5.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / Python / sysmodule.c
CommitLineData
c8042e10
DM
1\r
2/* System module */\r
3\r
4/*\r
5Various bits of information used by the interpreter are collected in\r
6module 'sys'.\r
7Function member:\r
8- exit(sts): raise SystemExit\r
9Data members:\r
10- stdin, stdout, stderr: standard file objects\r
11- modules: the table of modules (dictionary)\r
12- path: module search path (list of strings)\r
13- argv: script arguments (list of strings)\r
14- ps1, ps2: optional primary and secondary prompts (strings)\r
15*/\r
16\r
17#include "Python.h"\r
18#include "structseq.h"\r
19#include "code.h"\r
20#include "frameobject.h"\r
21#include "eval.h"\r
22\r
23#include "osdefs.h"\r
24\r
25#ifdef MS_WINDOWS\r
26#define WIN32_LEAN_AND_MEAN\r
27#include "windows.h"\r
28#endif /* MS_WINDOWS */\r
29\r
30#ifdef MS_COREDLL\r
31extern void *PyWin_DLLhModule;\r
32/* A string loaded from the DLL at startup: */\r
33extern const char *PyWin_DLLVersionString;\r
34#endif\r
35\r
36#ifdef __VMS\r
37#include <unixlib.h>\r
38#endif\r
39\r
40#ifdef MS_WINDOWS\r
41#include <windows.h>\r
42#endif\r
43\r
44#ifdef HAVE_LANGINFO_H\r
45#include <locale.h>\r
46#include <langinfo.h>\r
47#endif\r
48\r
49PyObject *\r
50PySys_GetObject(char *name)\r
51{\r
52 PyThreadState *tstate = PyThreadState_GET();\r
53 PyObject *sd = tstate->interp->sysdict;\r
54 if (sd == NULL)\r
55 return NULL;\r
56 return PyDict_GetItemString(sd, name);\r
57}\r
58\r
59FILE *\r
60PySys_GetFile(char *name, FILE *def)\r
61{\r
62 FILE *fp = NULL;\r
63 PyObject *v = PySys_GetObject(name);\r
64 if (v != NULL && PyFile_Check(v))\r
65 fp = PyFile_AsFile(v);\r
66 if (fp == NULL)\r
67 fp = def;\r
68 return fp;\r
69}\r
70\r
71int\r
72PySys_SetObject(char *name, PyObject *v)\r
73{\r
74 PyThreadState *tstate = PyThreadState_GET();\r
75 PyObject *sd = tstate->interp->sysdict;\r
76 if (v == NULL) {\r
77 if (PyDict_GetItemString(sd, name) == NULL)\r
78 return 0;\r
79 else\r
80 return PyDict_DelItemString(sd, name);\r
81 }\r
82 else\r
83 return PyDict_SetItemString(sd, name, v);\r
84}\r
85\r
86static PyObject *\r
87sys_displayhook(PyObject *self, PyObject *o)\r
88{\r
89 PyObject *outf;\r
90 PyInterpreterState *interp = PyThreadState_GET()->interp;\r
91 PyObject *modules = interp->modules;\r
92 PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");\r
93\r
94 if (builtins == NULL) {\r
95 PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");\r
96 return NULL;\r
97 }\r
98\r
99 /* Print value except if None */\r
100 /* After printing, also assign to '_' */\r
101 /* Before, set '_' to None to avoid recursion */\r
102 if (o == Py_None) {\r
103 Py_INCREF(Py_None);\r
104 return Py_None;\r
105 }\r
106 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)\r
107 return NULL;\r
108 if (Py_FlushLine() != 0)\r
109 return NULL;\r
110 outf = PySys_GetObject("stdout");\r
111 if (outf == NULL) {\r
112 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");\r
113 return NULL;\r
114 }\r
115 if (PyFile_WriteObject(o, outf, 0) != 0)\r
116 return NULL;\r
117 PyFile_SoftSpace(outf, 1);\r
118 if (Py_FlushLine() != 0)\r
119 return NULL;\r
120 if (PyObject_SetAttrString(builtins, "_", o) != 0)\r
121 return NULL;\r
122 Py_INCREF(Py_None);\r
123 return Py_None;\r
124}\r
125\r
126PyDoc_STRVAR(displayhook_doc,\r
127"displayhook(object) -> None\n"\r
128"\n"\r
129"Print an object to sys.stdout and also save it in __builtin__._\n"\r
130);\r
131\r
132static PyObject *\r
133sys_excepthook(PyObject* self, PyObject* args)\r
134{\r
135 PyObject *exc, *value, *tb;\r
136 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))\r
137 return NULL;\r
138 PyErr_Display(exc, value, tb);\r
139 Py_INCREF(Py_None);\r
140 return Py_None;\r
141}\r
142\r
143PyDoc_STRVAR(excepthook_doc,\r
144"excepthook(exctype, value, traceback) -> None\n"\r
145"\n"\r
146"Handle an exception by displaying it with a traceback on sys.stderr.\n"\r
147);\r
148\r
149static PyObject *\r
150sys_exc_info(PyObject *self, PyObject *noargs)\r
151{\r
152 PyThreadState *tstate;\r
153 tstate = PyThreadState_GET();\r
154 return Py_BuildValue(\r
155 "(OOO)",\r
156 tstate->exc_type != NULL ? tstate->exc_type : Py_None,\r
157 tstate->exc_value != NULL ? tstate->exc_value : Py_None,\r
158 tstate->exc_traceback != NULL ?\r
159 tstate->exc_traceback : Py_None);\r
160}\r
161\r
162PyDoc_STRVAR(exc_info_doc,\r
163"exc_info() -> (type, value, traceback)\n\\r
164\n\\r
165Return information about the most recent exception caught by an except\n\\r
166clause in the current stack frame or in an older stack frame."\r
167);\r
168\r
169static PyObject *\r
170sys_exc_clear(PyObject *self, PyObject *noargs)\r
171{\r
172 PyThreadState *tstate;\r
173 PyObject *tmp_type, *tmp_value, *tmp_tb;\r
174\r
175 if (PyErr_WarnPy3k("sys.exc_clear() not supported in 3.x; "\r
176 "use except clauses", 1) < 0)\r
177 return NULL;\r
178\r
179 tstate = PyThreadState_GET();\r
180 tmp_type = tstate->exc_type;\r
181 tmp_value = tstate->exc_value;\r
182 tmp_tb = tstate->exc_traceback;\r
183 tstate->exc_type = NULL;\r
184 tstate->exc_value = NULL;\r
185 tstate->exc_traceback = NULL;\r
186 Py_XDECREF(tmp_type);\r
187 Py_XDECREF(tmp_value);\r
188 Py_XDECREF(tmp_tb);\r
189 /* For b/w compatibility */\r
190 PySys_SetObject("exc_type", Py_None);\r
191 PySys_SetObject("exc_value", Py_None);\r
192 PySys_SetObject("exc_traceback", Py_None);\r
193 Py_INCREF(Py_None);\r
194 return Py_None;\r
195}\r
196\r
197PyDoc_STRVAR(exc_clear_doc,\r
198"exc_clear() -> None\n\\r
199\n\\r
200Clear global information on the current exception. Subsequent calls to\n\\r
201exc_info() will return (None,None,None) until another exception is raised\n\\r
202in the current thread or the execution stack returns to a frame where\n\\r
203another exception is being handled."\r
204);\r
205\r
206static PyObject *\r
207sys_exit(PyObject *self, PyObject *args)\r
208{\r
209 PyObject *exit_code = 0;\r
210 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))\r
211 return NULL;\r
212 /* Raise SystemExit so callers may catch it or clean up. */\r
213 PyErr_SetObject(PyExc_SystemExit, exit_code);\r
214 return NULL;\r
215}\r
216\r
217PyDoc_STRVAR(exit_doc,\r
218"exit([status])\n\\r
219\n\\r
220Exit the interpreter by raising SystemExit(status).\n\\r
221If the status is omitted or None, it defaults to zero (i.e., success).\n\\r
222If the status is an integer, it will be used as the system exit status.\n\\r
223If it is another kind of object, it will be printed and the system\n\\r
224exit status will be one (i.e., failure)."\r
225);\r
226\r
227#ifdef Py_USING_UNICODE\r
228\r
229static PyObject *\r
230sys_getdefaultencoding(PyObject *self)\r
231{\r
232 return PyString_FromString(PyUnicode_GetDefaultEncoding());\r
233}\r
234\r
235PyDoc_STRVAR(getdefaultencoding_doc,\r
236"getdefaultencoding() -> string\n\\r
237\n\\r
238Return the current default string encoding used by the Unicode \n\\r
239implementation."\r
240);\r
241\r
242static PyObject *\r
243sys_setdefaultencoding(PyObject *self, PyObject *args)\r
244{\r
245 char *encoding;\r
246 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))\r
247 return NULL;\r
248 if (PyUnicode_SetDefaultEncoding(encoding))\r
249 return NULL;\r
250 Py_INCREF(Py_None);\r
251 return Py_None;\r
252}\r
253\r
254PyDoc_STRVAR(setdefaultencoding_doc,\r
255"setdefaultencoding(encoding)\n\\r
256\n\\r
257Set the current default string encoding used by the Unicode implementation."\r
258);\r
259\r
260static PyObject *\r
261sys_getfilesystemencoding(PyObject *self)\r
262{\r
263 if (Py_FileSystemDefaultEncoding)\r
264 return PyString_FromString(Py_FileSystemDefaultEncoding);\r
265 Py_INCREF(Py_None);\r
266 return Py_None;\r
267}\r
268\r
269PyDoc_STRVAR(getfilesystemencoding_doc,\r
270"getfilesystemencoding() -> string\n\\r
271\n\\r
272Return the encoding used to convert Unicode filenames in\n\\r
273operating system filenames."\r
274);\r
275\r
276#endif\r
277\r
278/*\r
279 * Cached interned string objects used for calling the profile and\r
280 * trace functions. Initialized by trace_init().\r
281 */\r
282static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};\r
283\r
284static int\r
285trace_init(void)\r
286{\r
287 static char *whatnames[7] = {"call", "exception", "line", "return",\r
288 "c_call", "c_exception", "c_return"};\r
289 PyObject *name;\r
290 int i;\r
291 for (i = 0; i < 7; ++i) {\r
292 if (whatstrings[i] == NULL) {\r
293 name = PyString_InternFromString(whatnames[i]);\r
294 if (name == NULL)\r
295 return -1;\r
296 whatstrings[i] = name;\r
297 }\r
298 }\r
299 return 0;\r
300}\r
301\r
302\r
303static PyObject *\r
304call_trampoline(PyThreadState *tstate, PyObject* callback,\r
305 PyFrameObject *frame, int what, PyObject *arg)\r
306{\r
307 PyObject *args = PyTuple_New(3);\r
308 PyObject *whatstr;\r
309 PyObject *result;\r
310\r
311 if (args == NULL)\r
312 return NULL;\r
313 Py_INCREF(frame);\r
314 whatstr = whatstrings[what];\r
315 Py_INCREF(whatstr);\r
316 if (arg == NULL)\r
317 arg = Py_None;\r
318 Py_INCREF(arg);\r
319 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);\r
320 PyTuple_SET_ITEM(args, 1, whatstr);\r
321 PyTuple_SET_ITEM(args, 2, arg);\r
322\r
323 /* call the Python-level function */\r
324 PyFrame_FastToLocals(frame);\r
325 result = PyEval_CallObject(callback, args);\r
326 PyFrame_LocalsToFast(frame, 1);\r
327 if (result == NULL)\r
328 PyTraceBack_Here(frame);\r
329\r
330 /* cleanup */\r
331 Py_DECREF(args);\r
332 return result;\r
333}\r
334\r
335static int\r
336profile_trampoline(PyObject *self, PyFrameObject *frame,\r
337 int what, PyObject *arg)\r
338{\r
339 PyThreadState *tstate = frame->f_tstate;\r
340 PyObject *result;\r
341\r
342 if (arg == NULL)\r
343 arg = Py_None;\r
344 result = call_trampoline(tstate, self, frame, what, arg);\r
345 if (result == NULL) {\r
346 PyEval_SetProfile(NULL, NULL);\r
347 return -1;\r
348 }\r
349 Py_DECREF(result);\r
350 return 0;\r
351}\r
352\r
353static int\r
354trace_trampoline(PyObject *self, PyFrameObject *frame,\r
355 int what, PyObject *arg)\r
356{\r
357 PyThreadState *tstate = frame->f_tstate;\r
358 PyObject *callback;\r
359 PyObject *result;\r
360\r
361 if (what == PyTrace_CALL)\r
362 callback = self;\r
363 else\r
364 callback = frame->f_trace;\r
365 if (callback == NULL)\r
366 return 0;\r
367 result = call_trampoline(tstate, callback, frame, what, arg);\r
368 if (result == NULL) {\r
369 PyEval_SetTrace(NULL, NULL);\r
370 Py_CLEAR(frame->f_trace);\r
371 return -1;\r
372 }\r
373 if (result != Py_None) {\r
374 PyObject *temp = frame->f_trace;\r
375 frame->f_trace = NULL;\r
376 Py_XDECREF(temp);\r
377 frame->f_trace = result;\r
378 }\r
379 else {\r
380 Py_DECREF(result);\r
381 }\r
382 return 0;\r
383}\r
384\r
385static PyObject *\r
386sys_settrace(PyObject *self, PyObject *args)\r
387{\r
388 if (trace_init() == -1)\r
389 return NULL;\r
390 if (args == Py_None)\r
391 PyEval_SetTrace(NULL, NULL);\r
392 else\r
393 PyEval_SetTrace(trace_trampoline, args);\r
394 Py_INCREF(Py_None);\r
395 return Py_None;\r
396}\r
397\r
398PyDoc_STRVAR(settrace_doc,\r
399"settrace(function)\n\\r
400\n\\r
401Set the global debug tracing function. It will be called on each\n\\r
402function call. See the debugger chapter in the library manual."\r
403);\r
404\r
405static PyObject *\r
406sys_gettrace(PyObject *self, PyObject *args)\r
407{\r
408 PyThreadState *tstate = PyThreadState_GET();\r
409 PyObject *temp = tstate->c_traceobj;\r
410\r
411 if (temp == NULL)\r
412 temp = Py_None;\r
413 Py_INCREF(temp);\r
414 return temp;\r
415}\r
416\r
417PyDoc_STRVAR(gettrace_doc,\r
418"gettrace()\n\\r
419\n\\r
420Return the global debug tracing function set with sys.settrace.\n\\r
421See the debugger chapter in the library manual."\r
422);\r
423\r
424static PyObject *\r
425sys_setprofile(PyObject *self, PyObject *args)\r
426{\r
427 if (trace_init() == -1)\r
428 return NULL;\r
429 if (args == Py_None)\r
430 PyEval_SetProfile(NULL, NULL);\r
431 else\r
432 PyEval_SetProfile(profile_trampoline, args);\r
433 Py_INCREF(Py_None);\r
434 return Py_None;\r
435}\r
436\r
437PyDoc_STRVAR(setprofile_doc,\r
438"setprofile(function)\n\\r
439\n\\r
440Set the profiling function. It will be called on each function call\n\\r
441and return. See the profiler chapter in the library manual."\r
442);\r
443\r
444static PyObject *\r
445sys_getprofile(PyObject *self, PyObject *args)\r
446{\r
447 PyThreadState *tstate = PyThreadState_GET();\r
448 PyObject *temp = tstate->c_profileobj;\r
449\r
450 if (temp == NULL)\r
451 temp = Py_None;\r
452 Py_INCREF(temp);\r
453 return temp;\r
454}\r
455\r
456PyDoc_STRVAR(getprofile_doc,\r
457"getprofile()\n\\r
458\n\\r
459Return the profiling function set with sys.setprofile.\n\\r
460See the profiler chapter in the library manual."\r
461);\r
462\r
463static PyObject *\r
464sys_setcheckinterval(PyObject *self, PyObject *args)\r
465{\r
466 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))\r
467 return NULL;\r
468 _Py_Ticker = _Py_CheckInterval;\r
469 Py_INCREF(Py_None);\r
470 return Py_None;\r
471}\r
472\r
473PyDoc_STRVAR(setcheckinterval_doc,\r
474"setcheckinterval(n)\n\\r
475\n\\r
476Tell the Python interpreter to check for asynchronous events every\n\\r
477n instructions. This also affects how often thread switches occur."\r
478);\r
479\r
480static PyObject *\r
481sys_getcheckinterval(PyObject *self, PyObject *args)\r
482{\r
483 return PyInt_FromLong(_Py_CheckInterval);\r
484}\r
485\r
486PyDoc_STRVAR(getcheckinterval_doc,\r
487"getcheckinterval() -> current check interval; see setcheckinterval()."\r
488);\r
489\r
490#ifdef WITH_TSC\r
491static PyObject *\r
492sys_settscdump(PyObject *self, PyObject *args)\r
493{\r
494 int bool;\r
495 PyThreadState *tstate = PyThreadState_Get();\r
496\r
497 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))\r
498 return NULL;\r
499 if (bool)\r
500 tstate->interp->tscdump = 1;\r
501 else\r
502 tstate->interp->tscdump = 0;\r
503 Py_INCREF(Py_None);\r
504 return Py_None;\r
505\r
506}\r
507\r
508PyDoc_STRVAR(settscdump_doc,\r
509"settscdump(bool)\n\\r
510\n\\r
511If true, tell the Python interpreter to dump VM measurements to\n\\r
512stderr. If false, turn off dump. The measurements are based on the\n\\r
513processor's time-stamp counter."\r
514);\r
515#endif /* TSC */\r
516\r
517static PyObject *\r
518sys_setrecursionlimit(PyObject *self, PyObject *args)\r
519{\r
520 int new_limit;\r
521 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))\r
522 return NULL;\r
523 if (new_limit <= 0) {\r
524 PyErr_SetString(PyExc_ValueError,\r
525 "recursion limit must be positive");\r
526 return NULL;\r
527 }\r
528 Py_SetRecursionLimit(new_limit);\r
529 Py_INCREF(Py_None);\r
530 return Py_None;\r
531}\r
532\r
533PyDoc_STRVAR(setrecursionlimit_doc,\r
534"setrecursionlimit(n)\n\\r
535\n\\r
536Set the maximum depth of the Python interpreter stack to n. This\n\\r
537limit prevents infinite recursion from causing an overflow of the C\n\\r
538stack and crashing Python. The highest possible limit is platform-\n\\r
539dependent."\r
540);\r
541\r
542static PyObject *\r
543sys_getrecursionlimit(PyObject *self)\r
544{\r
545 return PyInt_FromLong(Py_GetRecursionLimit());\r
546}\r
547\r
548PyDoc_STRVAR(getrecursionlimit_doc,\r
549"getrecursionlimit()\n\\r
550\n\\r
551Return the current value of the recursion limit, the maximum depth\n\\r
552of the Python interpreter stack. This limit prevents infinite\n\\r
553recursion from causing an overflow of the C stack and crashing Python."\r
554);\r
555\r
556#ifdef MS_WINDOWS\r
557PyDoc_STRVAR(getwindowsversion_doc,\r
558"getwindowsversion()\n\\r
559\n\\r
560Return information about the running version of Windows as a named tuple.\n\\r
561The members are named: major, minor, build, platform, service_pack,\n\\r
562service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\\r
563backward compatibility, only the first 5 items are available by indexing.\n\\r
564All elements are numbers, except service_pack which is a string. Platform\n\\r
565may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\\r
5663 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\\r
567controller, 3 for a server."\r
568);\r
569\r
570static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};\r
571\r
572static PyStructSequence_Field windows_version_fields[] = {\r
573 {"major", "Major version number"},\r
574 {"minor", "Minor version number"},\r
575 {"build", "Build number"},\r
576 {"platform", "Operating system platform"},\r
577 {"service_pack", "Latest Service Pack installed on the system"},\r
578 {"service_pack_major", "Service Pack major version number"},\r
579 {"service_pack_minor", "Service Pack minor version number"},\r
580 {"suite_mask", "Bit mask identifying available product suites"},\r
581 {"product_type", "System product type"},\r
582 {0}\r
583};\r
584\r
585static PyStructSequence_Desc windows_version_desc = {\r
586 "sys.getwindowsversion", /* name */\r
587 getwindowsversion_doc, /* doc */\r
588 windows_version_fields, /* fields */\r
589 5 /* For backward compatibility,\r
590 only the first 5 items are accessible\r
591 via indexing, the rest are name only */\r
592};\r
593\r
594static PyObject *\r
595sys_getwindowsversion(PyObject *self)\r
596{\r
597 PyObject *version;\r
598 int pos = 0;\r
599 OSVERSIONINFOEX ver;\r
600 ver.dwOSVersionInfoSize = sizeof(ver);\r
601 if (!GetVersionEx((OSVERSIONINFO*) &ver))\r
602 return PyErr_SetFromWindowsErr(0);\r
603\r
604 version = PyStructSequence_New(&WindowsVersionType);\r
605 if (version == NULL)\r
606 return NULL;\r
607\r
608 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMajorVersion));\r
609 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMinorVersion));\r
610 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwBuildNumber));\r
611 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwPlatformId));\r
612 PyStructSequence_SET_ITEM(version, pos++, PyString_FromString(ver.szCSDVersion));\r
613 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMajor));\r
614 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMinor));\r
615 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wSuiteMask));\r
616 PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wProductType));\r
617\r
618 if (PyErr_Occurred()) {\r
619 Py_DECREF(version);\r
620 return NULL;\r
621 }\r
622 return version;\r
623}\r
624\r
625#endif /* MS_WINDOWS */\r
626\r
627#ifdef HAVE_DLOPEN\r
628static PyObject *\r
629sys_setdlopenflags(PyObject *self, PyObject *args)\r
630{\r
631 int new_val;\r
632 PyThreadState *tstate = PyThreadState_GET();\r
633 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))\r
634 return NULL;\r
635 if (!tstate)\r
636 return NULL;\r
637 tstate->interp->dlopenflags = new_val;\r
638 Py_INCREF(Py_None);\r
639 return Py_None;\r
640}\r
641\r
642PyDoc_STRVAR(setdlopenflags_doc,\r
643"setdlopenflags(n) -> None\n\\r
644\n\\r
645Set the flags used by the interpreter for dlopen calls, such as when the\n\\r
646interpreter loads extension modules. Among other things, this will enable\n\\r
647a lazy resolving of symbols when importing a module, if called as\n\\r
648sys.setdlopenflags(0). To share symbols across extension modules, call as\n\\r
649sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\\r
650can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\\r
651is not available, it can be generated from /usr/include/dlfcn.h using the\n\\r
652h2py script.");\r
653\r
654static PyObject *\r
655sys_getdlopenflags(PyObject *self, PyObject *args)\r
656{\r
657 PyThreadState *tstate = PyThreadState_GET();\r
658 if (!tstate)\r
659 return NULL;\r
660 return PyInt_FromLong(tstate->interp->dlopenflags);\r
661}\r
662\r
663PyDoc_STRVAR(getdlopenflags_doc,\r
664"getdlopenflags() -> int\n\\r
665\n\\r
666Return the current value of the flags that are used for dlopen calls.\n\\r
667The flag constants are defined in the ctypes and DLFCN modules.");\r
668\r
669#endif /* HAVE_DLOPEN */\r
670\r
671#ifdef USE_MALLOPT\r
672/* Link with -lmalloc (or -lmpc) on an SGI */\r
673#include <malloc.h>\r
674\r
675static PyObject *\r
676sys_mdebug(PyObject *self, PyObject *args)\r
677{\r
678 int flag;\r
679 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))\r
680 return NULL;\r
681 mallopt(M_DEBUG, flag);\r
682 Py_INCREF(Py_None);\r
683 return Py_None;\r
684}\r
685#endif /* USE_MALLOPT */\r
686\r
687size_t\r
688_PySys_GetSizeOf(PyObject *o)\r
689{\r
690 static PyObject *str__sizeof__ = NULL;\r
691 PyObject *res = NULL;\r
692 Py_ssize_t size;\r
693\r
694 /* Make sure the type is initialized. float gets initialized late */\r
695 if (PyType_Ready(Py_TYPE(o)) < 0)\r
696 return (size_t)-1;\r
697\r
698 /* Instance of old-style class */\r
699 if (PyInstance_Check(o))\r
700 size = PyInstance_Type.tp_basicsize;\r
701 /* all other objects */\r
702 else {\r
703 PyObject *method = _PyObject_LookupSpecial(o, "__sizeof__",\r
704 &str__sizeof__);\r
705 if (method == NULL) {\r
706 if (!PyErr_Occurred())\r
707 PyErr_Format(PyExc_TypeError,\r
708 "Type %.100s doesn't define __sizeof__",\r
709 Py_TYPE(o)->tp_name);\r
710 }\r
711 else {\r
712 res = PyObject_CallFunctionObjArgs(method, NULL);\r
713 Py_DECREF(method);\r
714 }\r
715\r
716 if (res == NULL)\r
717 return (size_t)-1;\r
718\r
719 size = (size_t)PyInt_AsSsize_t(res);\r
720 Py_DECREF(res);\r
721 if (size == -1 && PyErr_Occurred())\r
722 return (size_t)-1;\r
723 }\r
724\r
725 if (size < 0) {\r
726 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");\r
727 return (size_t)-1;\r
728 }\r
729\r
730 /* add gc_head size */\r
731 if (PyObject_IS_GC(o))\r
732 return ((size_t)size) + sizeof(PyGC_Head);\r
733 return (size_t)size;\r
734}\r
735\r
736static PyObject *\r
737sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)\r
738{\r
739 static char *kwlist[] = {"object", "default", 0};\r
740 size_t size;\r
741 PyObject *o, *dflt = NULL;\r
742\r
743 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",\r
744 kwlist, &o, &dflt))\r
745 return NULL;\r
746\r
747 size = _PySys_GetSizeOf(o);\r
748\r
749 if (size == (size_t)-1 && PyErr_Occurred()) {\r
750 /* Has a default value been given */\r
751 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {\r
752 PyErr_Clear();\r
753 Py_INCREF(dflt);\r
754 return dflt;\r
755 }\r
756 else\r
757 return NULL;\r
758 }\r
759\r
760 return PyInt_FromSize_t(size);\r
761}\r
762\r
763PyDoc_STRVAR(getsizeof_doc,\r
764"getsizeof(object, default) -> int\n\\r
765\n\\r
766Return the size of object in bytes.");\r
767\r
768static PyObject *\r
769sys_getrefcount(PyObject *self, PyObject *arg)\r
770{\r
771 return PyInt_FromSsize_t(arg->ob_refcnt);\r
772}\r
773\r
774#ifdef Py_REF_DEBUG\r
775static PyObject *\r
776sys_gettotalrefcount(PyObject *self)\r
777{\r
778 return PyInt_FromSsize_t(_Py_GetRefTotal());\r
779}\r
780#endif /* Py_REF_DEBUG */\r
781\r
782PyDoc_STRVAR(getrefcount_doc,\r
783"getrefcount(object) -> integer\n\\r
784\n\\r
785Return the reference count of object. The count returned is generally\n\\r
786one higher than you might expect, because it includes the (temporary)\n\\r
787reference as an argument to getrefcount()."\r
788);\r
789\r
790#ifdef COUNT_ALLOCS\r
791static PyObject *\r
792sys_getcounts(PyObject *self)\r
793{\r
794 extern PyObject *get_counts(void);\r
795\r
796 return get_counts();\r
797}\r
798#endif\r
799\r
800PyDoc_STRVAR(getframe_doc,\r
801"_getframe([depth]) -> frameobject\n\\r
802\n\\r
803Return a frame object from the call stack. If optional integer depth is\n\\r
804given, return the frame object that many calls below the top of the stack.\n\\r
805If that is deeper than the call stack, ValueError is raised. The default\n\\r
806for depth is zero, returning the frame at the top of the call stack.\n\\r
807\n\\r
808This function should be used for internal and specialized\n\\r
809purposes only."\r
810);\r
811\r
812static PyObject *\r
813sys_getframe(PyObject *self, PyObject *args)\r
814{\r
815 PyFrameObject *f = PyThreadState_GET()->frame;\r
816 int depth = -1;\r
817\r
818 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))\r
819 return NULL;\r
820\r
821 while (depth > 0 && f != NULL) {\r
822 f = f->f_back;\r
823 --depth;\r
824 }\r
825 if (f == NULL) {\r
826 PyErr_SetString(PyExc_ValueError,\r
827 "call stack is not deep enough");\r
828 return NULL;\r
829 }\r
830 Py_INCREF(f);\r
831 return (PyObject*)f;\r
832}\r
833\r
834PyDoc_STRVAR(current_frames_doc,\r
835"_current_frames() -> dictionary\n\\r
836\n\\r
837Return a dictionary mapping each current thread T's thread id to T's\n\\r
838current stack frame.\n\\r
839\n\\r
840This function should be used for specialized purposes only."\r
841);\r
842\r
843static PyObject *\r
844sys_current_frames(PyObject *self, PyObject *noargs)\r
845{\r
846 return _PyThread_CurrentFrames();\r
847}\r
848\r
849PyDoc_STRVAR(call_tracing_doc,\r
850"call_tracing(func, args) -> object\n\\r
851\n\\r
852Call func(*args), while tracing is enabled. The tracing state is\n\\r
853saved, and restored afterwards. This is intended to be called from\n\\r
854a debugger from a checkpoint, to recursively debug some other code."\r
855);\r
856\r
857static PyObject *\r
858sys_call_tracing(PyObject *self, PyObject *args)\r
859{\r
860 PyObject *func, *funcargs;\r
861 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))\r
862 return NULL;\r
863 return _PyEval_CallTracing(func, funcargs);\r
864}\r
865\r
866PyDoc_STRVAR(callstats_doc,\r
867"callstats() -> tuple of integers\n\\r
868\n\\r
869Return a tuple of function call statistics, if CALL_PROFILE was defined\n\\r
870when Python was built. Otherwise, return None.\n\\r
871\n\\r
872When enabled, this function returns detailed, implementation-specific\n\\r
873details about the number of function calls executed. The return value is\n\\r
874a 11-tuple where the entries in the tuple are counts of:\n\\r
8750. all function calls\n\\r
8761. calls to PyFunction_Type objects\n\\r
8772. PyFunction calls that do not create an argument tuple\n\\r
8783. PyFunction calls that do not create an argument tuple\n\\r
879 and bypass PyEval_EvalCodeEx()\n\\r
8804. PyMethod calls\n\\r
8815. PyMethod calls on bound methods\n\\r
8826. PyType calls\n\\r
8837. PyCFunction calls\n\\r
8848. generator calls\n\\r
8859. All other calls\n\\r
88610. Number of stack pops performed by call_function()"\r
887);\r
888\r
889#ifdef __cplusplus\r
890extern "C" {\r
891#endif\r
892\r
893#ifdef Py_TRACE_REFS\r
894/* Defined in objects.c because it uses static globals if that file */\r
895extern PyObject *_Py_GetObjects(PyObject *, PyObject *);\r
896#endif\r
897\r
898#ifdef DYNAMIC_EXECUTION_PROFILE\r
899/* Defined in ceval.c because it uses static globals if that file */\r
900extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);\r
901#endif\r
902\r
903#ifdef __cplusplus\r
904}\r
905#endif\r
906\r
907static PyObject *\r
908sys_clear_type_cache(PyObject* self, PyObject* args)\r
909{\r
910 PyType_ClearCache();\r
911 Py_RETURN_NONE;\r
912}\r
913\r
914PyDoc_STRVAR(sys_clear_type_cache__doc__,\r
915"_clear_type_cache() -> None\n\\r
916Clear the internal type lookup cache.");\r
917\r
918\r
919static PyMethodDef sys_methods[] = {\r
920 /* Might as well keep this in alphabetic order */\r
921 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,\r
922 callstats_doc},\r
923 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,\r
924 sys_clear_type_cache__doc__},\r
925 {"_current_frames", sys_current_frames, METH_NOARGS,\r
926 current_frames_doc},\r
927 {"displayhook", sys_displayhook, METH_O, displayhook_doc},\r
928 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},\r
929 {"exc_clear", sys_exc_clear, METH_NOARGS, exc_clear_doc},\r
930 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},\r
931 {"exit", sys_exit, METH_VARARGS, exit_doc},\r
932#ifdef Py_USING_UNICODE\r
933 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,\r
934 METH_NOARGS, getdefaultencoding_doc},\r
935#endif\r
936#ifdef HAVE_DLOPEN\r
937 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,\r
938 getdlopenflags_doc},\r
939#endif\r
940#ifdef COUNT_ALLOCS\r
941 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},\r
942#endif\r
943#ifdef DYNAMIC_EXECUTION_PROFILE\r
944 {"getdxp", _Py_GetDXProfile, METH_VARARGS},\r
945#endif\r
946#ifdef Py_USING_UNICODE\r
947 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,\r
948 METH_NOARGS, getfilesystemencoding_doc},\r
949#endif\r
950#ifdef Py_TRACE_REFS\r
951 {"getobjects", _Py_GetObjects, METH_VARARGS},\r
952#endif\r
953#ifdef Py_REF_DEBUG\r
954 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},\r
955#endif\r
956 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},\r
957 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,\r
958 getrecursionlimit_doc},\r
959 {"getsizeof", (PyCFunction)sys_getsizeof,\r
960 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},\r
961 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},\r
962#ifdef MS_WINDOWS\r
963 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,\r
964 getwindowsversion_doc},\r
965#endif /* MS_WINDOWS */\r
966#ifdef USE_MALLOPT\r
967 {"mdebug", sys_mdebug, METH_VARARGS},\r
968#endif\r
969#ifdef Py_USING_UNICODE\r
970 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,\r
971 setdefaultencoding_doc},\r
972#endif\r
973 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,\r
974 setcheckinterval_doc},\r
975 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,\r
976 getcheckinterval_doc},\r
977#ifdef HAVE_DLOPEN\r
978 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,\r
979 setdlopenflags_doc},\r
980#endif\r
981 {"setprofile", sys_setprofile, METH_O, setprofile_doc},\r
982 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},\r
983 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,\r
984 setrecursionlimit_doc},\r
985#ifdef WITH_TSC\r
986 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},\r
987#endif\r
988 {"settrace", sys_settrace, METH_O, settrace_doc},\r
989 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},\r
990 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},\r
991 {NULL, NULL} /* sentinel */\r
992};\r
993\r
994static PyObject *\r
995list_builtin_module_names(void)\r
996{\r
997 PyObject *list = PyList_New(0);\r
998 int i;\r
999 if (list == NULL)\r
1000 return NULL;\r
1001 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {\r
1002 PyObject *name = PyString_FromString(\r
1003 PyImport_Inittab[i].name);\r
1004 if (name == NULL)\r
1005 break;\r
1006 PyList_Append(list, name);\r
1007 Py_DECREF(name);\r
1008 }\r
1009 if (PyList_Sort(list) != 0) {\r
1010 Py_DECREF(list);\r
1011 list = NULL;\r
1012 }\r
1013 if (list) {\r
1014 PyObject *v = PyList_AsTuple(list);\r
1015 Py_DECREF(list);\r
1016 list = v;\r
1017 }\r
1018 return list;\r
1019}\r
1020\r
1021static PyObject *warnoptions = NULL;\r
1022\r
1023void\r
1024PySys_ResetWarnOptions(void)\r
1025{\r
1026 if (warnoptions == NULL || !PyList_Check(warnoptions))\r
1027 return;\r
1028 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);\r
1029}\r
1030\r
1031void\r
1032PySys_AddWarnOption(char *s)\r
1033{\r
1034 PyObject *str;\r
1035\r
1036 if (warnoptions == NULL || !PyList_Check(warnoptions)) {\r
1037 Py_XDECREF(warnoptions);\r
1038 warnoptions = PyList_New(0);\r
1039 if (warnoptions == NULL)\r
1040 return;\r
1041 }\r
1042 str = PyString_FromString(s);\r
1043 if (str != NULL) {\r
1044 PyList_Append(warnoptions, str);\r
1045 Py_DECREF(str);\r
1046 }\r
1047}\r
1048\r
1049int\r
1050PySys_HasWarnOptions(void)\r
1051{\r
1052 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;\r
1053}\r
1054\r
1055/* XXX This doc string is too long to be a single string literal in VC++ 5.0.\r
1056 Two literals concatenated works just fine. If you have a K&R compiler\r
1057 or other abomination that however *does* understand longer strings,\r
1058 get rid of the !!! comment in the middle and the quotes that surround it. */\r
1059PyDoc_VAR(sys_doc) =\r
1060PyDoc_STR(\r
1061"This module provides access to some objects used or maintained by the\n\\r
1062interpreter and to functions that interact strongly with the interpreter.\n\\r
1063\n\\r
1064Dynamic objects:\n\\r
1065\n\\r
1066argv -- command line arguments; argv[0] is the script pathname if known\n\\r
1067path -- module search path; path[0] is the script directory, else ''\n\\r
1068modules -- dictionary of loaded modules\n\\r
1069\n\\r
1070displayhook -- called to show results in an interactive session\n\\r
1071excepthook -- called to handle any uncaught exception other than SystemExit\n\\r
1072 To customize printing in an interactive session or to install a custom\n\\r
1073 top-level exception handler, assign other functions to replace these.\n\\r
1074\n\\r
1075exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\\r
1076 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\\r
1077\n\\r
1078stdin -- standard input file object; used by raw_input() and input()\n\\r
1079stdout -- standard output file object; used by the print statement\n\\r
1080stderr -- standard error object; used for error messages\n\\r
1081 By assigning other file objects (or objects that behave like files)\n\\r
1082 to these, it is possible to redirect all of the interpreter's I/O.\n\\r
1083\n\\r
1084last_type -- type of last uncaught exception\n\\r
1085last_value -- value of last uncaught exception\n\\r
1086last_traceback -- traceback of last uncaught exception\n\\r
1087 These three are only available in an interactive session after a\n\\r
1088 traceback has been printed.\n\\r
1089\n\\r
1090exc_type -- type of exception currently being handled\n\\r
1091exc_value -- value of exception currently being handled\n\\r
1092exc_traceback -- traceback of exception currently being handled\n\\r
1093 The function exc_info() should be used instead of these three,\n\\r
1094 because it is thread-safe.\n\\r
1095"\r
1096)\r
1097/* concatenating string here */\r
1098PyDoc_STR(\r
1099"\n\\r
1100Static objects:\n\\r
1101\n\\r
1102float_info -- a dict with information about the float inplementation.\n\\r
1103long_info -- a struct sequence with information about the long implementation.\n\\r
1104maxint -- the largest supported integer (the smallest is -maxint-1)\n\\r
1105maxsize -- the largest supported length of containers.\n\\r
1106maxunicode -- the largest supported character\n\\r
1107builtin_module_names -- tuple of module names built into this interpreter\n\\r
1108version -- the version of this interpreter as a string\n\\r
1109version_info -- version information as a named tuple\n\\r
1110hexversion -- version information encoded as a single integer\n\\r
1111copyright -- copyright notice pertaining to this interpreter\n\\r
1112platform -- platform identifier\n\\r
1113executable -- absolute path of the executable binary of the Python interpreter\n\\r
1114prefix -- prefix used to find the Python library\n\\r
1115exec_prefix -- prefix used to find the machine-specific Python library\n\\r
1116float_repr_style -- string indicating the style of repr() output for floats\n\\r
1117"\r
1118)\r
1119#ifdef MS_WINDOWS\r
1120/* concatenating string here */\r
1121PyDoc_STR(\r
1122"dllhandle -- [Windows only] integer handle of the Python DLL\n\\r
1123winver -- [Windows only] version number of the Python DLL\n\\r
1124"\r
1125)\r
1126#endif /* MS_WINDOWS */\r
1127PyDoc_STR(\r
1128"__stdin__ -- the original stdin; don't touch!\n\\r
1129__stdout__ -- the original stdout; don't touch!\n\\r
1130__stderr__ -- the original stderr; don't touch!\n\\r
1131__displayhook__ -- the original displayhook; don't touch!\n\\r
1132__excepthook__ -- the original excepthook; don't touch!\n\\r
1133\n\\r
1134Functions:\n\\r
1135\n\\r
1136displayhook() -- print an object to the screen, and save it in __builtin__._\n\\r
1137excepthook() -- print an exception and its traceback to sys.stderr\n\\r
1138exc_info() -- return thread-safe information about the current exception\n\\r
1139exc_clear() -- clear the exception state for the current thread\n\\r
1140exit() -- exit the interpreter by raising SystemExit\n\\r
1141getdlopenflags() -- returns flags to be used for dlopen() calls\n\\r
1142getprofile() -- get the global profiling function\n\\r
1143getrefcount() -- return the reference count for an object (plus one :-)\n\\r
1144getrecursionlimit() -- return the max recursion depth for the interpreter\n\\r
1145getsizeof() -- return the size of an object in bytes\n\\r
1146gettrace() -- get the global debug tracing function\n\\r
1147setcheckinterval() -- control how often the interpreter checks for events\n\\r
1148setdlopenflags() -- set the flags to be used for dlopen() calls\n\\r
1149setprofile() -- set the global profiling function\n\\r
1150setrecursionlimit() -- set the max recursion depth for the interpreter\n\\r
1151settrace() -- set the global debug tracing function\n\\r
1152"\r
1153)\r
1154/* end of sys_doc */ ;\r
1155\r
1156static int\r
1157_check_and_flush (FILE *stream)\r
1158{\r
1159 int prev_fail = ferror (stream);\r
1160 return fflush (stream) || prev_fail ? EOF : 0;\r
1161}\r
1162\r
1163/* Subversion branch and revision management */\r
1164static int svn_initialized;\r
1165static char patchlevel_revision[50]; /* Just the number */\r
1166static char branch[50];\r
1167static char shortbranch[50];\r
1168static const char *svn_revision;\r
1169\r
1170static void\r
1171svnversion_init(void)\r
1172{\r
1173 if (svn_initialized)\r
1174 return;\r
1175 svn_initialized = 1;\r
1176 *patchlevel_revision = '\0';\r
1177 strcpy(branch, "");\r
1178 strcpy(shortbranch, "unknown");\r
1179 svn_revision = "";\r
1180 return;\r
1181}\r
1182\r
1183/* Return svnversion output if available.\r
1184 Else return Revision of patchlevel.h if on branch.\r
1185 Else return empty string */\r
1186const char*\r
1187Py_SubversionRevision()\r
1188{\r
1189 svnversion_init();\r
1190 return svn_revision;\r
1191}\r
1192\r
1193const char*\r
1194Py_SubversionShortBranch()\r
1195{\r
1196 svnversion_init();\r
1197 return shortbranch;\r
1198}\r
1199\r
1200\r
1201PyDoc_STRVAR(flags__doc__,\r
1202"sys.flags\n\\r
1203\n\\r
1204Flags provided through command line arguments or environment vars.");\r
1205\r
1206static PyTypeObject FlagsType = {0, 0, 0, 0, 0, 0};\r
1207\r
1208static PyStructSequence_Field flags_fields[] = {\r
1209 {"debug", "-d"},\r
1210 {"py3k_warning", "-3"},\r
1211 {"division_warning", "-Q"},\r
1212 {"division_new", "-Qnew"},\r
1213 {"inspect", "-i"},\r
1214 {"interactive", "-i"},\r
1215 {"optimize", "-O or -OO"},\r
1216 {"dont_write_bytecode", "-B"},\r
1217 {"no_user_site", "-s"},\r
1218 {"no_site", "-S"},\r
1219 {"ignore_environment", "-E"},\r
1220 {"tabcheck", "-t or -tt"},\r
1221 {"verbose", "-v"},\r
1222#ifdef RISCOS\r
1223 {"riscos_wimp", "???"},\r
1224#endif\r
1225 /* {"unbuffered", "-u"}, */\r
1226 {"unicode", "-U"},\r
1227 /* {"skip_first", "-x"}, */\r
1228 {"bytes_warning", "-b"},\r
1229 {"hash_randomization", "-R"},\r
1230 {0}\r
1231};\r
1232\r
1233static PyStructSequence_Desc flags_desc = {\r
1234 "sys.flags", /* name */\r
1235 flags__doc__, /* doc */\r
1236 flags_fields, /* fields */\r
1237#ifdef RISCOS\r
1238 17\r
1239#else\r
1240 16\r
1241#endif\r
1242};\r
1243\r
1244static PyObject*\r
1245make_flags(void)\r
1246{\r
1247 int pos = 0;\r
1248 PyObject *seq;\r
1249\r
1250 seq = PyStructSequence_New(&FlagsType);\r
1251 if (seq == NULL)\r
1252 return NULL;\r
1253\r
1254#define SetFlag(flag) \\r
1255 PyStructSequence_SET_ITEM(seq, pos++, PyInt_FromLong(flag))\r
1256\r
1257 SetFlag(Py_DebugFlag);\r
1258 SetFlag(Py_Py3kWarningFlag);\r
1259 SetFlag(Py_DivisionWarningFlag);\r
1260 SetFlag(_Py_QnewFlag);\r
1261 SetFlag(Py_InspectFlag);\r
1262 SetFlag(Py_InteractiveFlag);\r
1263 SetFlag(Py_OptimizeFlag);\r
1264 SetFlag(Py_DontWriteBytecodeFlag);\r
1265 SetFlag(Py_NoUserSiteDirectory);\r
1266 SetFlag(Py_NoSiteFlag);\r
1267 SetFlag(Py_IgnoreEnvironmentFlag);\r
1268 SetFlag(Py_TabcheckFlag);\r
1269 SetFlag(Py_VerboseFlag);\r
1270#ifdef RISCOS\r
1271 SetFlag(Py_RISCOSWimpFlag);\r
1272#endif\r
1273 /* SetFlag(saw_unbuffered_flag); */\r
1274 SetFlag(Py_UnicodeFlag);\r
1275 /* SetFlag(skipfirstline); */\r
1276 SetFlag(Py_BytesWarningFlag);\r
1277 SetFlag(Py_HashRandomizationFlag);\r
1278#undef SetFlag\r
1279\r
1280 if (PyErr_Occurred()) {\r
1281 Py_DECREF(seq);\r
1282 return NULL;\r
1283 }\r
1284 return seq;\r
1285}\r
1286\r
1287PyDoc_STRVAR(version_info__doc__,\r
1288"sys.version_info\n\\r
1289\n\\r
1290Version information as a named tuple.");\r
1291\r
1292static PyTypeObject VersionInfoType = {0, 0, 0, 0, 0, 0};\r
1293\r
1294static PyStructSequence_Field version_info_fields[] = {\r
1295 {"major", "Major release number"},\r
1296 {"minor", "Minor release number"},\r
1297 {"micro", "Patch release number"},\r
1298 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},\r
1299 {"serial", "Serial release number"},\r
1300 {0}\r
1301};\r
1302\r
1303static PyStructSequence_Desc version_info_desc = {\r
1304 "sys.version_info", /* name */\r
1305 version_info__doc__, /* doc */\r
1306 version_info_fields, /* fields */\r
1307 5\r
1308};\r
1309\r
1310static PyObject *\r
1311make_version_info(void)\r
1312{\r
1313 PyObject *version_info;\r
1314 char *s;\r
1315 int pos = 0;\r
1316\r
1317 version_info = PyStructSequence_New(&VersionInfoType);\r
1318 if (version_info == NULL) {\r
1319 return NULL;\r
1320 }\r
1321\r
1322 /*\r
1323 * These release level checks are mutually exclusive and cover\r
1324 * the field, so don't get too fancy with the pre-processor!\r
1325 */\r
1326#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA\r
1327 s = "alpha";\r
1328#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA\r
1329 s = "beta";\r
1330#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA\r
1331 s = "candidate";\r
1332#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL\r
1333 s = "final";\r
1334#endif\r
1335\r
1336#define SetIntItem(flag) \\r
1337 PyStructSequence_SET_ITEM(version_info, pos++, PyInt_FromLong(flag))\r
1338#define SetStrItem(flag) \\r
1339 PyStructSequence_SET_ITEM(version_info, pos++, PyString_FromString(flag))\r
1340\r
1341 SetIntItem(PY_MAJOR_VERSION);\r
1342 SetIntItem(PY_MINOR_VERSION);\r
1343 SetIntItem(PY_MICRO_VERSION);\r
1344 SetStrItem(s);\r
1345 SetIntItem(PY_RELEASE_SERIAL);\r
1346#undef SetIntItem\r
1347#undef SetStrItem\r
1348\r
1349 if (PyErr_Occurred()) {\r
1350 Py_CLEAR(version_info);\r
1351 return NULL;\r
1352 }\r
1353 return version_info;\r
1354}\r
1355\r
1356PyObject *\r
1357_PySys_Init(void)\r
1358{\r
1359 PyObject *m, *v, *sysdict;\r
1360 PyObject *sysin, *sysout, *syserr;\r
1361 char *s;\r
1362\r
1363 m = Py_InitModule3("sys", sys_methods, sys_doc);\r
1364 if (m == NULL)\r
1365 return NULL;\r
1366 sysdict = PyModule_GetDict(m);\r
1367#define SET_SYS_FROM_STRING(key, value) \\r
1368 v = value; \\r
1369 if (v != NULL) \\r
1370 PyDict_SetItemString(sysdict, key, v); \\r
1371 Py_XDECREF(v)\r
1372\r
1373 /* Check that stdin is not a directory\r
1374 Using shell redirection, you can redirect stdin to a directory,\r
1375 crashing the Python interpreter. Catch this common mistake here\r
1376 and output a useful error message. Note that under MS Windows,\r
1377 the shell already prevents that. */\r
1378#if !defined(MS_WINDOWS)\r
1379 {\r
1380 struct stat sb;\r
1381 if (fstat(fileno(stdin), &sb) == 0 &&\r
1382 S_ISDIR(sb.st_mode)) {\r
1383 /* There's nothing more we can do. */\r
1384 /* Py_FatalError() will core dump, so just exit. */\r
1385 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");\r
1386 exit(EXIT_FAILURE);\r
1387 }\r
1388 }\r
1389#endif\r
1390\r
1391 /* Closing the standard FILE* if sys.std* goes aways causes problems\r
1392 * for embedded Python usages. Closing them when somebody explicitly\r
1393 * invokes .close() might be possible, but the FAQ promises they get\r
1394 * never closed. However, we still need to get write errors when\r
1395 * writing fails (e.g. because stdout is redirected), so we flush the\r
1396 * streams and check for errors before the file objects are deleted.\r
1397 * On OS X, fflush()ing stdin causes an error, so we exempt stdin\r
1398 * from that procedure.\r
1399 */\r
1400 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);\r
1401 sysout = PyFile_FromFile(stdout, "<stdout>", "w", _check_and_flush);\r
1402 syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);\r
1403 if (PyErr_Occurred())\r
1404 return NULL;\r
1405\r
1406 PyDict_SetItemString(sysdict, "stdin", sysin);\r
1407 PyDict_SetItemString(sysdict, "stdout", sysout);\r
1408 PyDict_SetItemString(sysdict, "stderr", syserr);\r
1409 /* Make backup copies for cleanup */\r
1410 PyDict_SetItemString(sysdict, "__stdin__", sysin);\r
1411 PyDict_SetItemString(sysdict, "__stdout__", sysout);\r
1412 PyDict_SetItemString(sysdict, "__stderr__", syserr);\r
1413 PyDict_SetItemString(sysdict, "__displayhook__",\r
1414 PyDict_GetItemString(sysdict, "displayhook"));\r
1415 PyDict_SetItemString(sysdict, "__excepthook__",\r
1416 PyDict_GetItemString(sysdict, "excepthook"));\r
1417 Py_XDECREF(sysin);\r
1418 Py_XDECREF(sysout);\r
1419 Py_XDECREF(syserr);\r
1420\r
1421 SET_SYS_FROM_STRING("version",\r
1422 PyString_FromString(Py_GetVersion()));\r
1423 SET_SYS_FROM_STRING("hexversion",\r
1424 PyInt_FromLong(PY_VERSION_HEX));\r
1425 svnversion_init();\r
1426 SET_SYS_FROM_STRING("subversion",\r
1427 Py_BuildValue("(ssz)", "CPython", branch,\r
1428 svn_revision));\r
1429 SET_SYS_FROM_STRING("_mercurial",\r
1430 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),\r
1431 _Py_hgversion()));\r
1432 SET_SYS_FROM_STRING("dont_write_bytecode",\r
1433 PyBool_FromLong(Py_DontWriteBytecodeFlag));\r
1434 SET_SYS_FROM_STRING("api_version",\r
1435 PyInt_FromLong(PYTHON_API_VERSION));\r
1436 SET_SYS_FROM_STRING("copyright",\r
1437 PyString_FromString(Py_GetCopyright()));\r
1438 SET_SYS_FROM_STRING("platform",\r
1439 PyString_FromString(Py_GetPlatform()));\r
1440 SET_SYS_FROM_STRING("executable",\r
1441 PyString_FromString(Py_GetProgramFullPath()));\r
1442 SET_SYS_FROM_STRING("prefix",\r
1443 PyString_FromString(Py_GetPrefix()));\r
1444 SET_SYS_FROM_STRING("exec_prefix",\r
1445 PyString_FromString(Py_GetExecPrefix()));\r
1446 SET_SYS_FROM_STRING("maxsize",\r
1447 PyInt_FromSsize_t(PY_SSIZE_T_MAX));\r
1448 SET_SYS_FROM_STRING("maxint",\r
1449 PyInt_FromLong(PyInt_GetMax()));\r
1450 SET_SYS_FROM_STRING("py3kwarning",\r
1451 PyBool_FromLong(Py_Py3kWarningFlag));\r
1452 SET_SYS_FROM_STRING("float_info",\r
1453 PyFloat_GetInfo());\r
1454 SET_SYS_FROM_STRING("long_info",\r
1455 PyLong_GetInfo());\r
1456#ifdef Py_USING_UNICODE\r
1457 SET_SYS_FROM_STRING("maxunicode",\r
1458 PyInt_FromLong(PyUnicode_GetMax()));\r
1459#endif\r
1460 SET_SYS_FROM_STRING("builtin_module_names",\r
1461 list_builtin_module_names());\r
1462 {\r
1463 /* Assumes that longs are at least 2 bytes long.\r
1464 Should be safe! */\r
1465 unsigned long number = 1;\r
1466 char *value;\r
1467\r
1468 s = (char *) &number;\r
1469 if (s[0] == 0)\r
1470 value = "big";\r
1471 else\r
1472 value = "little";\r
1473 SET_SYS_FROM_STRING("byteorder",\r
1474 PyString_FromString(value));\r
1475 }\r
1476#ifdef MS_COREDLL\r
1477 SET_SYS_FROM_STRING("dllhandle",\r
1478 PyLong_FromVoidPtr(PyWin_DLLhModule));\r
1479 SET_SYS_FROM_STRING("winver",\r
1480 PyString_FromString(PyWin_DLLVersionString));\r
1481#endif\r
1482 if (warnoptions == NULL) {\r
1483 warnoptions = PyList_New(0);\r
1484 }\r
1485 else {\r
1486 Py_INCREF(warnoptions);\r
1487 }\r
1488 if (warnoptions != NULL) {\r
1489 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);\r
1490 }\r
1491\r
1492 /* version_info */\r
1493 if (VersionInfoType.tp_name == 0)\r
1494 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);\r
1495 SET_SYS_FROM_STRING("version_info", make_version_info());\r
1496 /* prevent user from creating new instances */\r
1497 VersionInfoType.tp_init = NULL;\r
1498 VersionInfoType.tp_new = NULL;\r
1499\r
1500 /* flags */\r
1501 if (FlagsType.tp_name == 0)\r
1502 PyStructSequence_InitType(&FlagsType, &flags_desc);\r
1503 SET_SYS_FROM_STRING("flags", make_flags());\r
1504 /* prevent user from creating new instances */\r
1505 FlagsType.tp_init = NULL;\r
1506 FlagsType.tp_new = NULL;\r
1507\r
1508\r
1509#if defined(MS_WINDOWS)\r
1510 /* getwindowsversion */\r
1511 if (WindowsVersionType.tp_name == 0)\r
1512 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);\r
1513 /* prevent user from creating new instances */\r
1514 WindowsVersionType.tp_init = NULL;\r
1515 WindowsVersionType.tp_new = NULL;\r
1516#endif\r
1517\r
1518 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */\r
1519#ifndef PY_NO_SHORT_FLOAT_REPR\r
1520 SET_SYS_FROM_STRING("float_repr_style",\r
1521 PyString_FromString("short"));\r
1522#else\r
1523 SET_SYS_FROM_STRING("float_repr_style",\r
1524 PyString_FromString("legacy"));\r
1525#endif\r
1526\r
1527#undef SET_SYS_FROM_STRING\r
1528 if (PyErr_Occurred())\r
1529 return NULL;\r
1530 return m;\r
1531}\r
1532\r
1533static PyObject *\r
1534makepathobject(char *path, int delim)\r
1535{\r
1536 int i, n;\r
1537 char *p;\r
1538 PyObject *v, *w;\r
1539\r
1540 n = 1;\r
1541 p = path;\r
1542 while ((p = strchr(p, delim)) != NULL) {\r
1543 n++;\r
1544 p++;\r
1545 }\r
1546 v = PyList_New(n);\r
1547 if (v == NULL)\r
1548 return NULL;\r
1549 for (i = 0; ; i++) {\r
1550 p = strchr(path, delim);\r
1551 if (p == NULL)\r
1552 p = strchr(path, '\0'); /* End of string */\r
1553 w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));\r
1554 if (w == NULL) {\r
1555 Py_DECREF(v);\r
1556 return NULL;\r
1557 }\r
1558 PyList_SetItem(v, i, w);\r
1559 if (*p == '\0')\r
1560 break;\r
1561 path = p+1;\r
1562 }\r
1563 return v;\r
1564}\r
1565\r
1566void\r
1567PySys_SetPath(char *path)\r
1568{\r
1569 PyObject *v;\r
1570 if ((v = makepathobject(path, DELIM)) == NULL)\r
1571 Py_FatalError("can't create sys.path");\r
1572 if (PySys_SetObject("path", v) != 0)\r
1573 Py_FatalError("can't assign sys.path");\r
1574 Py_DECREF(v);\r
1575}\r
1576\r
1577static PyObject *\r
1578makeargvobject(int argc, char **argv)\r
1579{\r
1580 PyObject *av;\r
1581 if (argc <= 0 || argv == NULL) {\r
1582 /* Ensure at least one (empty) argument is seen */\r
1583 static char *empty_argv[1] = {""};\r
1584 argv = empty_argv;\r
1585 argc = 1;\r
1586 }\r
1587 av = PyList_New(argc);\r
1588 if (av != NULL) {\r
1589 int i;\r
1590 for (i = 0; i < argc; i++) {\r
1591#ifdef __VMS\r
1592 PyObject *v;\r
1593\r
1594 /* argv[0] is the script pathname if known */\r
1595 if (i == 0) {\r
1596 char* fn = decc$translate_vms(argv[0]);\r
1597 if ((fn == (char *)0) || fn == (char *)-1)\r
1598 v = PyString_FromString(argv[0]);\r
1599 else\r
1600 v = PyString_FromString(\r
1601 decc$translate_vms(argv[0]));\r
1602 } else\r
1603 v = PyString_FromString(argv[i]);\r
1604#else\r
1605 PyObject *v = PyString_FromString(argv[i]);\r
1606#endif\r
1607 if (v == NULL) {\r
1608 Py_DECREF(av);\r
1609 av = NULL;\r
1610 break;\r
1611 }\r
1612 PyList_SetItem(av, i, v);\r
1613 }\r
1614 }\r
1615 return av;\r
1616}\r
1617\r
1618void\r
1619PySys_SetArgvEx(int argc, char **argv, int updatepath)\r
1620{\r
1621#if defined(HAVE_REALPATH)\r
1622 char fullpath[MAXPATHLEN];\r
1623#elif defined(MS_WINDOWS) && !defined(MS_WINCE)\r
1624 char fullpath[MAX_PATH];\r
1625#endif\r
1626 PyObject *av = makeargvobject(argc, argv);\r
1627 PyObject *path = PySys_GetObject("path");\r
1628 if (av == NULL)\r
1629 Py_FatalError("no mem for sys.argv");\r
1630 if (PySys_SetObject("argv", av) != 0)\r
1631 Py_FatalError("can't assign sys.argv");\r
1632 if (updatepath && path != NULL) {\r
1633 char *argv0 = argv[0];\r
1634 char *p = NULL;\r
1635 Py_ssize_t n = 0;\r
1636 PyObject *a;\r
1637#ifdef HAVE_READLINK\r
1638 char link[MAXPATHLEN+1];\r
1639 char argv0copy[2*MAXPATHLEN+1];\r
1640 int nr = 0;\r
1641 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)\r
1642 nr = readlink(argv0, link, MAXPATHLEN);\r
1643 if (nr > 0) {\r
1644 /* It's a symlink */\r
1645 link[nr] = '\0';\r
1646 if (link[0] == SEP)\r
1647 argv0 = link; /* Link to absolute path */\r
1648 else if (strchr(link, SEP) == NULL)\r
1649 ; /* Link without path */\r
1650 else {\r
1651 /* Must join(dirname(argv0), link) */\r
1652 char *q = strrchr(argv0, SEP);\r
1653 if (q == NULL)\r
1654 argv0 = link; /* argv0 without path */\r
1655 else {\r
1656 /* Must make a copy */\r
1657 strcpy(argv0copy, argv0);\r
1658 q = strrchr(argv0copy, SEP);\r
1659 strcpy(q+1, link);\r
1660 argv0 = argv0copy;\r
1661 }\r
1662 }\r
1663 }\r
1664#endif /* HAVE_READLINK */\r
1665#if SEP == '\\' /* Special case for MS filename syntax */\r
1666 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {\r
1667 char *q;\r
1668#if defined(MS_WINDOWS) && !defined(MS_WINCE)\r
1669 /* This code here replaces the first element in argv with the full\r
1670 path that it represents. Under CE, there are no relative paths so\r
1671 the argument must be the full path anyway. */\r
1672 char *ptemp;\r
1673 if (GetFullPathName(argv0,\r
1674 sizeof(fullpath),\r
1675 fullpath,\r
1676 &ptemp)) {\r
1677 argv0 = fullpath;\r
1678 }\r
1679#endif\r
1680 p = strrchr(argv0, SEP);\r
1681 /* Test for alternate separator */\r
1682 q = strrchr(p ? p : argv0, '/');\r
1683 if (q != NULL)\r
1684 p = q;\r
1685 if (p != NULL) {\r
1686 n = p + 1 - argv0;\r
1687 if (n > 1 && p[-1] != ':')\r
1688 n--; /* Drop trailing separator */\r
1689 }\r
1690 }\r
1691#else /* All other filename syntaxes */\r
1692 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {\r
1693#if defined(HAVE_REALPATH)\r
1694 if (realpath(argv0, fullpath)) {\r
1695 argv0 = fullpath;\r
1696 }\r
1697#endif\r
1698 p = strrchr(argv0, SEP);\r
1699 }\r
1700 if (p != NULL) {\r
1701#ifndef RISCOS\r
1702 n = p + 1 - argv0;\r
1703#else /* don't include trailing separator */\r
1704 n = p - argv0;\r
1705#endif /* RISCOS */\r
1706#if SEP == '/' /* Special case for Unix filename syntax */\r
1707 if (n > 1)\r
1708 n--; /* Drop trailing separator */\r
1709#endif /* Unix */\r
1710 }\r
1711#endif /* All others */\r
1712 a = PyString_FromStringAndSize(argv0, n);\r
1713 if (a == NULL)\r
1714 Py_FatalError("no mem for sys.path insertion");\r
1715 if (PyList_Insert(path, 0, a) < 0)\r
1716 Py_FatalError("sys.path.insert(0) failed");\r
1717 Py_DECREF(a);\r
1718 }\r
1719 Py_DECREF(av);\r
1720}\r
1721\r
1722void\r
1723PySys_SetArgv(int argc, char **argv)\r
1724{\r
1725 PySys_SetArgvEx(argc, argv, 1);\r
1726}\r
1727\r
1728\r
1729/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.\r
1730 Adapted from code submitted by Just van Rossum.\r
1731\r
1732 PySys_WriteStdout(format, ...)\r
1733 PySys_WriteStderr(format, ...)\r
1734\r
1735 The first function writes to sys.stdout; the second to sys.stderr. When\r
1736 there is a problem, they write to the real (C level) stdout or stderr;\r
1737 no exceptions are raised.\r
1738\r
1739 Both take a printf-style format string as their first argument followed\r
1740 by a variable length argument list determined by the format string.\r
1741\r
1742 *** WARNING ***\r
1743\r
1744 The format should limit the total size of the formatted output string to\r
1745 1000 bytes. In particular, this means that no unrestricted "%s" formats\r
1746 should occur; these should be limited using "%.<N>s where <N> is a\r
1747 decimal number calculated so that <N> plus the maximum size of other\r
1748 formatted text does not exceed 1000 bytes. Also watch out for "%f",\r
1749 which can print hundreds of digits for very large numbers.\r
1750\r
1751 */\r
1752\r
1753static void\r
1754mywrite(char *name, FILE *fp, const char *format, va_list va)\r
1755{\r
1756 PyObject *file;\r
1757 PyObject *error_type, *error_value, *error_traceback;\r
1758\r
1759 PyErr_Fetch(&error_type, &error_value, &error_traceback);\r
1760 file = PySys_GetObject(name);\r
1761 if (file == NULL || PyFile_AsFile(file) == fp)\r
1762 vfprintf(fp, format, va);\r
1763 else {\r
1764 char buffer[1001];\r
1765 const int written = PyOS_vsnprintf(buffer, sizeof(buffer),\r
1766 format, va);\r
1767 if (PyFile_WriteString(buffer, file) != 0) {\r
1768 PyErr_Clear();\r
1769 fputs(buffer, fp);\r
1770 }\r
1771 if (written < 0 || (size_t)written >= sizeof(buffer)) {\r
1772 const char *truncated = "... truncated";\r
1773 if (PyFile_WriteString(truncated, file) != 0) {\r
1774 PyErr_Clear();\r
1775 fputs(truncated, fp);\r
1776 }\r
1777 }\r
1778 }\r
1779 PyErr_Restore(error_type, error_value, error_traceback);\r
1780}\r
1781\r
1782void\r
1783PySys_WriteStdout(const char *format, ...)\r
1784{\r
1785 va_list va;\r
1786\r
1787 va_start(va, format);\r
1788 mywrite("stdout", stdout, format, va);\r
1789 va_end(va);\r
1790}\r
1791\r
1792void\r
1793PySys_WriteStderr(const char *format, ...)\r
1794{\r
1795 va_list va;\r
1796\r
1797 va_start(va, format);\r
1798 mywrite("stderr", stderr, format, va);\r
1799 va_end(va);\r
1800}\r