]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.2/Python/sysmodule.c
EmbeddedPkg: Extend NvVarStoreFormattedLib LIBRARY_CLASS
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Python / sysmodule.c
CommitLineData
4710c53d 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 numeric, 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_XDECREF(frame->f_trace);\r
371 frame->f_trace = NULL;\r
372 return -1;\r
373 }\r
374 if (result != Py_None) {\r
375 PyObject *temp = frame->f_trace;\r
376 frame->f_trace = NULL;\r
377 Py_XDECREF(temp);\r
378 frame->f_trace = result;\r
379 }\r
380 else {\r
381 Py_DECREF(result);\r
382 }\r
383 return 0;\r
384}\r
385\r
386static PyObject *\r
387sys_settrace(PyObject *self, PyObject *args)\r
388{\r
389 if (trace_init() == -1)\r
390 return NULL;\r
391 if (args == Py_None)\r
392 PyEval_SetTrace(NULL, NULL);\r
393 else\r
394 PyEval_SetTrace(trace_trampoline, args);\r
395 Py_INCREF(Py_None);\r
396 return Py_None;\r
397}\r
398\r
399PyDoc_STRVAR(settrace_doc,\r
400"settrace(function)\n\\r
401\n\\r
402Set the global debug tracing function. It will be called on each\n\\r
403function call. See the debugger chapter in the library manual."\r
404);\r
405\r
406static PyObject *\r
407sys_gettrace(PyObject *self, PyObject *args)\r
408{\r
409 PyThreadState *tstate = PyThreadState_GET();\r
410 PyObject *temp = tstate->c_traceobj;\r
411\r
412 if (temp == NULL)\r
413 temp = Py_None;\r
414 Py_INCREF(temp);\r
415 return temp;\r
416}\r
417\r
418PyDoc_STRVAR(gettrace_doc,\r
419"gettrace()\n\\r
420\n\\r
421Return the global debug tracing function set with sys.settrace.\n\\r
422See the debugger chapter in the library manual."\r
423);\r
424\r
425static PyObject *\r
426sys_setprofile(PyObject *self, PyObject *args)\r
427{\r
428 if (trace_init() == -1)\r
429 return NULL;\r
430 if (args == Py_None)\r
431 PyEval_SetProfile(NULL, NULL);\r
432 else\r
433 PyEval_SetProfile(profile_trampoline, args);\r
434 Py_INCREF(Py_None);\r
435 return Py_None;\r
436}\r
437\r
438PyDoc_STRVAR(setprofile_doc,\r
439"setprofile(function)\n\\r
440\n\\r
441Set the profiling function. It will be called on each function call\n\\r
442and return. See the profiler chapter in the library manual."\r
443);\r
444\r
445static PyObject *\r
446sys_getprofile(PyObject *self, PyObject *args)\r
447{\r
448 PyThreadState *tstate = PyThreadState_GET();\r
449 PyObject *temp = tstate->c_profileobj;\r
450\r
451 if (temp == NULL)\r
452 temp = Py_None;\r
453 Py_INCREF(temp);\r
454 return temp;\r
455}\r
456\r
457PyDoc_STRVAR(getprofile_doc,\r
458"getprofile()\n\\r
459\n\\r
460Return the profiling function set with sys.setprofile.\n\\r
461See the profiler chapter in the library manual."\r
462);\r
463\r
464static PyObject *\r
465sys_setcheckinterval(PyObject *self, PyObject *args)\r
466{\r
467 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))\r
468 return NULL;\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 return version;\r
619}\r
620\r
621#endif /* MS_WINDOWS */\r
622\r
623#ifdef HAVE_DLOPEN\r
624static PyObject *\r
625sys_setdlopenflags(PyObject *self, PyObject *args)\r
626{\r
627 int new_val;\r
628 PyThreadState *tstate = PyThreadState_GET();\r
629 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))\r
630 return NULL;\r
631 if (!tstate)\r
632 return NULL;\r
633 tstate->interp->dlopenflags = new_val;\r
634 Py_INCREF(Py_None);\r
635 return Py_None;\r
636}\r
637\r
638PyDoc_STRVAR(setdlopenflags_doc,\r
639"setdlopenflags(n) -> None\n\\r
640\n\\r
641Set the flags used by the interpreter for dlopen calls, such as when the\n\\r
642interpreter loads extension modules. Among other things, this will enable\n\\r
643a lazy resolving of symbols when importing a module, if called as\n\\r
644sys.setdlopenflags(0). To share symbols across extension modules, call as\n\\r
645sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\\r
646can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\\r
647is not available, it can be generated from /usr/include/dlfcn.h using the\n\\r
648h2py script.");\r
649\r
650static PyObject *\r
651sys_getdlopenflags(PyObject *self, PyObject *args)\r
652{\r
653 PyThreadState *tstate = PyThreadState_GET();\r
654 if (!tstate)\r
655 return NULL;\r
656 return PyInt_FromLong(tstate->interp->dlopenflags);\r
657}\r
658\r
659PyDoc_STRVAR(getdlopenflags_doc,\r
660"getdlopenflags() -> int\n\\r
661\n\\r
662Return the current value of the flags that are used for dlopen calls.\n\\r
663The flag constants are defined in the ctypes and DLFCN modules.");\r
664\r
665#endif /* HAVE_DLOPEN */\r
666\r
667#ifdef USE_MALLOPT\r
668/* Link with -lmalloc (or -lmpc) on an SGI */\r
669#include <malloc.h>\r
670\r
671static PyObject *\r
672sys_mdebug(PyObject *self, PyObject *args)\r
673{\r
674 int flag;\r
675 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))\r
676 return NULL;\r
677 mallopt(M_DEBUG, flag);\r
678 Py_INCREF(Py_None);\r
679 return Py_None;\r
680}\r
681#endif /* USE_MALLOPT */\r
682\r
683static PyObject *\r
684sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)\r
685{\r
686 PyObject *res = NULL;\r
687 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;\r
688 static char *kwlist[] = {"object", "default", 0};\r
689 PyObject *o, *dflt = NULL;\r
690\r
691 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",\r
692 kwlist, &o, &dflt))\r
693 return NULL;\r
694\r
695 /* Initialize static variable for GC head size */\r
696 if (gc_head_size == NULL) {\r
697 gc_head_size = PyInt_FromSsize_t(sizeof(PyGC_Head));\r
698 if (gc_head_size == NULL)\r
699 return NULL;\r
700 }\r
701\r
702 /* Make sure the type is initialized. float gets initialized late */\r
703 if (PyType_Ready(Py_TYPE(o)) < 0)\r
704 return NULL;\r
705\r
706 /* Instance of old-style class */\r
707 if (PyInstance_Check(o))\r
708 res = PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);\r
709 /* all other objects */\r
710 else {\r
711 PyObject *method = _PyObject_LookupSpecial(o, "__sizeof__",\r
712 &str__sizeof__);\r
713 if (method == NULL) {\r
714 if (!PyErr_Occurred())\r
715 PyErr_Format(PyExc_TypeError,\r
716 "Type %.100s doesn't define __sizeof__",\r
717 Py_TYPE(o)->tp_name);\r
718 }\r
719 else {\r
720 res = PyObject_CallFunctionObjArgs(method, NULL);\r
721 Py_DECREF(method);\r
722 }\r
723 }\r
724\r
725 /* Has a default value been given? */\r
726 if ((res == NULL) && (dflt != NULL) &&\r
727 PyErr_ExceptionMatches(PyExc_TypeError))\r
728 {\r
729 PyErr_Clear();\r
730 Py_INCREF(dflt);\r
731 return dflt;\r
732 }\r
733 else if (res == NULL)\r
734 return res;\r
735\r
736 /* add gc_head size */\r
737 if (PyObject_IS_GC(o)) {\r
738 PyObject *tmp = res;\r
739 res = PyNumber_Add(tmp, gc_head_size);\r
740 Py_DECREF(tmp);\r
741 }\r
742 return res;\r
743}\r
744\r
745PyDoc_STRVAR(getsizeof_doc,\r
746"getsizeof(object, default) -> int\n\\r
747\n\\r
748Return the size of object in bytes.");\r
749\r
750static PyObject *\r
751sys_getrefcount(PyObject *self, PyObject *arg)\r
752{\r
753 return PyInt_FromSsize_t(arg->ob_refcnt);\r
754}\r
755\r
756#ifdef Py_REF_DEBUG\r
757static PyObject *\r
758sys_gettotalrefcount(PyObject *self)\r
759{\r
760 return PyInt_FromSsize_t(_Py_GetRefTotal());\r
761}\r
762#endif /* Py_REF_DEBUG */\r
763\r
764PyDoc_STRVAR(getrefcount_doc,\r
765"getrefcount(object) -> integer\n\\r
766\n\\r
767Return the reference count of object. The count returned is generally\n\\r
768one higher than you might expect, because it includes the (temporary)\n\\r
769reference as an argument to getrefcount()."\r
770);\r
771\r
772#ifdef COUNT_ALLOCS\r
773static PyObject *\r
774sys_getcounts(PyObject *self)\r
775{\r
776 extern PyObject *get_counts(void);\r
777\r
778 return get_counts();\r
779}\r
780#endif\r
781\r
782PyDoc_STRVAR(getframe_doc,\r
783"_getframe([depth]) -> frameobject\n\\r
784\n\\r
785Return a frame object from the call stack. If optional integer depth is\n\\r
786given, return the frame object that many calls below the top of the stack.\n\\r
787If that is deeper than the call stack, ValueError is raised. The default\n\\r
788for depth is zero, returning the frame at the top of the call stack.\n\\r
789\n\\r
790This function should be used for internal and specialized\n\\r
791purposes only."\r
792);\r
793\r
794static PyObject *\r
795sys_getframe(PyObject *self, PyObject *args)\r
796{\r
797 PyFrameObject *f = PyThreadState_GET()->frame;\r
798 int depth = -1;\r
799\r
800 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))\r
801 return NULL;\r
802\r
803 while (depth > 0 && f != NULL) {\r
804 f = f->f_back;\r
805 --depth;\r
806 }\r
807 if (f == NULL) {\r
808 PyErr_SetString(PyExc_ValueError,\r
809 "call stack is not deep enough");\r
810 return NULL;\r
811 }\r
812 Py_INCREF(f);\r
813 return (PyObject*)f;\r
814}\r
815\r
816PyDoc_STRVAR(current_frames_doc,\r
817"_current_frames() -> dictionary\n\\r
818\n\\r
819Return a dictionary mapping each current thread T's thread id to T's\n\\r
820current stack frame.\n\\r
821\n\\r
822This function should be used for specialized purposes only."\r
823);\r
824\r
825static PyObject *\r
826sys_current_frames(PyObject *self, PyObject *noargs)\r
827{\r
828 return _PyThread_CurrentFrames();\r
829}\r
830\r
831PyDoc_STRVAR(call_tracing_doc,\r
832"call_tracing(func, args) -> object\n\\r
833\n\\r
834Call func(*args), while tracing is enabled. The tracing state is\n\\r
835saved, and restored afterwards. This is intended to be called from\n\\r
836a debugger from a checkpoint, to recursively debug some other code."\r
837);\r
838\r
839static PyObject *\r
840sys_call_tracing(PyObject *self, PyObject *args)\r
841{\r
842 PyObject *func, *funcargs;\r
843 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))\r
844 return NULL;\r
845 return _PyEval_CallTracing(func, funcargs);\r
846}\r
847\r
848PyDoc_STRVAR(callstats_doc,\r
849"callstats() -> tuple of integers\n\\r
850\n\\r
851Return a tuple of function call statistics, if CALL_PROFILE was defined\n\\r
852when Python was built. Otherwise, return None.\n\\r
853\n\\r
854When enabled, this function returns detailed, implementation-specific\n\\r
855details about the number of function calls executed. The return value is\n\\r
856a 11-tuple where the entries in the tuple are counts of:\n\\r
8570. all function calls\n\\r
8581. calls to PyFunction_Type objects\n\\r
8592. PyFunction calls that do not create an argument tuple\n\\r
8603. PyFunction calls that do not create an argument tuple\n\\r
861 and bypass PyEval_EvalCodeEx()\n\\r
8624. PyMethod calls\n\\r
8635. PyMethod calls on bound methods\n\\r
8646. PyType calls\n\\r
8657. PyCFunction calls\n\\r
8668. generator calls\n\\r
8679. All other calls\n\\r
86810. Number of stack pops performed by call_function()"\r
869);\r
870\r
871#ifdef __cplusplus\r
872extern "C" {\r
873#endif\r
874\r
875#ifdef Py_TRACE_REFS\r
876/* Defined in objects.c because it uses static globals if that file */\r
877extern PyObject *_Py_GetObjects(PyObject *, PyObject *);\r
878#endif\r
879\r
880#ifdef DYNAMIC_EXECUTION_PROFILE\r
881/* Defined in ceval.c because it uses static globals if that file */\r
882extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);\r
883#endif\r
884\r
885#ifdef __cplusplus\r
886}\r
887#endif\r
888\r
889static PyObject *\r
890sys_clear_type_cache(PyObject* self, PyObject* args)\r
891{\r
892 PyType_ClearCache();\r
893 Py_RETURN_NONE;\r
894}\r
895\r
896PyDoc_STRVAR(sys_clear_type_cache__doc__,\r
897"_clear_type_cache() -> None\n\\r
898Clear the internal type lookup cache.");\r
899\r
900\r
901static PyMethodDef sys_methods[] = {\r
902 /* Might as well keep this in alphabetic order */\r
903 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,\r
904 callstats_doc},\r
905 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,\r
906 sys_clear_type_cache__doc__},\r
907 {"_current_frames", sys_current_frames, METH_NOARGS,\r
908 current_frames_doc},\r
909 {"displayhook", sys_displayhook, METH_O, displayhook_doc},\r
910 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},\r
911 {"exc_clear", sys_exc_clear, METH_NOARGS, exc_clear_doc},\r
912 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},\r
913 {"exit", sys_exit, METH_VARARGS, exit_doc},\r
914#ifdef Py_USING_UNICODE\r
915 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,\r
916 METH_NOARGS, getdefaultencoding_doc},\r
917#endif\r
918#ifdef HAVE_DLOPEN\r
919 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,\r
920 getdlopenflags_doc},\r
921#endif\r
922#ifdef COUNT_ALLOCS\r
923 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},\r
924#endif\r
925#ifdef DYNAMIC_EXECUTION_PROFILE\r
926 {"getdxp", _Py_GetDXProfile, METH_VARARGS},\r
927#endif\r
928#ifdef Py_USING_UNICODE\r
929 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,\r
930 METH_NOARGS, getfilesystemencoding_doc},\r
931#endif\r
932#ifdef Py_TRACE_REFS\r
933 {"getobjects", _Py_GetObjects, METH_VARARGS},\r
934#endif\r
935#ifdef Py_REF_DEBUG\r
936 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},\r
937#endif\r
938 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},\r
939 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,\r
940 getrecursionlimit_doc},\r
941 {"getsizeof", (PyCFunction)sys_getsizeof,\r
942 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},\r
943 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},\r
944#ifdef MS_WINDOWS\r
945 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,\r
946 getwindowsversion_doc},\r
947#endif /* MS_WINDOWS */\r
948#ifdef USE_MALLOPT\r
949 {"mdebug", sys_mdebug, METH_VARARGS},\r
950#endif\r
951#ifdef Py_USING_UNICODE\r
952 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,\r
953 setdefaultencoding_doc},\r
954#endif\r
955 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,\r
956 setcheckinterval_doc},\r
957 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,\r
958 getcheckinterval_doc},\r
959#ifdef HAVE_DLOPEN\r
960 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,\r
961 setdlopenflags_doc},\r
962#endif\r
963 {"setprofile", sys_setprofile, METH_O, setprofile_doc},\r
964 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},\r
965 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,\r
966 setrecursionlimit_doc},\r
967#ifdef WITH_TSC\r
968 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},\r
969#endif\r
970 {"settrace", sys_settrace, METH_O, settrace_doc},\r
971 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},\r
972 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},\r
973 {NULL, NULL} /* sentinel */\r
974};\r
975\r
976static PyObject *\r
977list_builtin_module_names(void)\r
978{\r
979 PyObject *list = PyList_New(0);\r
980 int i;\r
981 if (list == NULL)\r
982 return NULL;\r
983 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {\r
984 PyObject *name = PyString_FromString(\r
985 PyImport_Inittab[i].name);\r
986 if (name == NULL)\r
987 break;\r
988 PyList_Append(list, name);\r
989 Py_DECREF(name);\r
990 }\r
991 if (PyList_Sort(list) != 0) {\r
992 Py_DECREF(list);\r
993 list = NULL;\r
994 }\r
995 if (list) {\r
996 PyObject *v = PyList_AsTuple(list);\r
997 Py_DECREF(list);\r
998 list = v;\r
999 }\r
1000 return list;\r
1001}\r
1002\r
1003static PyObject *warnoptions = NULL;\r
1004\r
1005void\r
1006PySys_ResetWarnOptions(void)\r
1007{\r
1008 if (warnoptions == NULL || !PyList_Check(warnoptions))\r
1009 return;\r
1010 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);\r
1011}\r
1012\r
1013void\r
1014PySys_AddWarnOption(char *s)\r
1015{\r
1016 PyObject *str;\r
1017\r
1018 if (warnoptions == NULL || !PyList_Check(warnoptions)) {\r
1019 Py_XDECREF(warnoptions);\r
1020 warnoptions = PyList_New(0);\r
1021 if (warnoptions == NULL)\r
1022 return;\r
1023 }\r
1024 str = PyString_FromString(s);\r
1025 if (str != NULL) {\r
1026 PyList_Append(warnoptions, str);\r
1027 Py_DECREF(str);\r
1028 }\r
1029}\r
1030\r
1031int\r
1032PySys_HasWarnOptions(void)\r
1033{\r
1034 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;\r
1035}\r
1036\r
1037/* XXX This doc string is too long to be a single string literal in VC++ 5.0.\r
1038 Two literals concatenated works just fine. If you have a K&R compiler\r
1039 or other abomination that however *does* understand longer strings,\r
1040 get rid of the !!! comment in the middle and the quotes that surround it. */\r
1041PyDoc_VAR(sys_doc) =\r
1042PyDoc_STR(\r
1043"This module provides access to some objects used or maintained by the\n\\r
1044interpreter and to functions that interact strongly with the interpreter.\n\\r
1045\n\\r
1046Dynamic objects:\n\\r
1047\n\\r
1048argv -- command line arguments; argv[0] is the script pathname if known\n\\r
1049path -- module search path; path[0] is the script directory, else ''\n\\r
1050modules -- dictionary of loaded modules\n\\r
1051\n\\r
1052displayhook -- called to show results in an interactive session\n\\r
1053excepthook -- called to handle any uncaught exception other than SystemExit\n\\r
1054 To customize printing in an interactive session or to install a custom\n\\r
1055 top-level exception handler, assign other functions to replace these.\n\\r
1056\n\\r
1057exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\\r
1058 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\\r
1059\n\\r
1060stdin -- standard input file object; used by raw_input() and input()\n\\r
1061stdout -- standard output file object; used by the print statement\n\\r
1062stderr -- standard error object; used for error messages\n\\r
1063 By assigning other file objects (or objects that behave like files)\n\\r
1064 to these, it is possible to redirect all of the interpreter's I/O.\n\\r
1065\n\\r
1066last_type -- type of last uncaught exception\n\\r
1067last_value -- value of last uncaught exception\n\\r
1068last_traceback -- traceback of last uncaught exception\n\\r
1069 These three are only available in an interactive session after a\n\\r
1070 traceback has been printed.\n\\r
1071\n\\r
1072exc_type -- type of exception currently being handled\n\\r
1073exc_value -- value of exception currently being handled\n\\r
1074exc_traceback -- traceback of exception currently being handled\n\\r
1075 The function exc_info() should be used instead of these three,\n\\r
1076 because it is thread-safe.\n\\r
1077"\r
1078)\r
1079/* concatenating string here */\r
1080PyDoc_STR(\r
1081"\n\\r
1082Static objects:\n\\r
1083\n\\r
1084float_info -- a dict with information about the float inplementation.\n\\r
1085long_info -- a struct sequence with information about the long implementation.\n\\r
1086maxint -- the largest supported integer (the smallest is -maxint-1)\n\\r
1087maxsize -- the largest supported length of containers.\n\\r
1088maxunicode -- the largest supported character\n\\r
1089builtin_module_names -- tuple of module names built into this interpreter\n\\r
1090version -- the version of this interpreter as a string\n\\r
1091version_info -- version information as a named tuple\n\\r
1092hexversion -- version information encoded as a single integer\n\\r
1093copyright -- copyright notice pertaining to this interpreter\n\\r
1094platform -- platform identifier\n\\r
1095executable -- pathname of this Python interpreter\n\\r
1096prefix -- prefix used to find the Python library\n\\r
1097exec_prefix -- prefix used to find the machine-specific Python library\n\\r
1098float_repr_style -- string indicating the style of repr() output for floats\n\\r
1099"\r
1100)\r
1101#ifdef MS_WINDOWS\r
1102/* concatenating string here */\r
1103PyDoc_STR(\r
1104"dllhandle -- [Windows only] integer handle of the Python DLL\n\\r
1105winver -- [Windows only] version number of the Python DLL\n\\r
1106"\r
1107)\r
1108#endif /* MS_WINDOWS */\r
1109PyDoc_STR(\r
1110"__stdin__ -- the original stdin; don't touch!\n\\r
1111__stdout__ -- the original stdout; don't touch!\n\\r
1112__stderr__ -- the original stderr; don't touch!\n\\r
1113__displayhook__ -- the original displayhook; don't touch!\n\\r
1114__excepthook__ -- the original excepthook; don't touch!\n\\r
1115\n\\r
1116Functions:\n\\r
1117\n\\r
1118displayhook() -- print an object to the screen, and save it in __builtin__._\n\\r
1119excepthook() -- print an exception and its traceback to sys.stderr\n\\r
1120exc_info() -- return thread-safe information about the current exception\n\\r
1121exc_clear() -- clear the exception state for the current thread\n\\r
1122exit() -- exit the interpreter by raising SystemExit\n\\r
1123getdlopenflags() -- returns flags to be used for dlopen() calls\n\\r
1124getprofile() -- get the global profiling function\n\\r
1125getrefcount() -- return the reference count for an object (plus one :-)\n\\r
1126getrecursionlimit() -- return the max recursion depth for the interpreter\n\\r
1127getsizeof() -- return the size of an object in bytes\n\\r
1128gettrace() -- get the global debug tracing function\n\\r
1129setcheckinterval() -- control how often the interpreter checks for events\n\\r
1130setdlopenflags() -- set the flags to be used for dlopen() calls\n\\r
1131setprofile() -- set the global profiling function\n\\r
1132setrecursionlimit() -- set the max recursion depth for the interpreter\n\\r
1133settrace() -- set the global debug tracing function\n\\r
1134"\r
1135)\r
1136/* end of sys_doc */ ;\r
1137\r
1138static int\r
1139_check_and_flush (FILE *stream)\r
1140{\r
1141 int prev_fail = ferror (stream);\r
1142 return fflush (stream) || prev_fail ? EOF : 0;\r
1143}\r
1144\r
1145/* Subversion branch and revision management */\r
1146static int svn_initialized;\r
1147static char patchlevel_revision[50]; /* Just the number */\r
1148static char branch[50];\r
1149static char shortbranch[50];\r
1150static const char *svn_revision;\r
1151\r
1152static void\r
1153svnversion_init(void)\r
1154{\r
1155 if (svn_initialized)\r
1156 return;\r
1157 svn_initialized = 1;\r
1158 *patchlevel_revision = '\0';\r
1159 strcpy(branch, "");\r
1160 strcpy(shortbranch, "unknown");\r
1161 svn_revision = "";\r
1162 return;\r
1163}\r
1164\r
1165/* Return svnversion output if available.\r
1166 Else return Revision of patchlevel.h if on branch.\r
1167 Else return empty string */\r
1168const char*\r
1169Py_SubversionRevision()\r
1170{\r
1171 svnversion_init();\r
1172 return svn_revision;\r
1173}\r
1174\r
1175const char*\r
1176Py_SubversionShortBranch()\r
1177{\r
1178 svnversion_init();\r
1179 return shortbranch;\r
1180}\r
1181\r
1182\r
1183PyDoc_STRVAR(flags__doc__,\r
1184"sys.flags\n\\r
1185\n\\r
1186Flags provided through command line arguments or environment vars.");\r
1187\r
1188static PyTypeObject FlagsType = {0, 0, 0, 0, 0, 0};\r
1189\r
1190static PyStructSequence_Field flags_fields[] = {\r
1191 {"debug", "-d"},\r
1192 {"py3k_warning", "-3"},\r
1193 {"division_warning", "-Q"},\r
1194 {"division_new", "-Qnew"},\r
1195 {"inspect", "-i"},\r
1196 {"interactive", "-i"},\r
1197 {"optimize", "-O or -OO"},\r
1198 {"dont_write_bytecode", "-B"},\r
1199 {"no_user_site", "-s"},\r
1200 {"no_site", "-S"},\r
1201 {"ignore_environment", "-E"},\r
1202 {"tabcheck", "-t or -tt"},\r
1203 {"verbose", "-v"},\r
1204#ifdef RISCOS\r
1205 {"riscos_wimp", "???"},\r
1206#endif\r
1207 /* {"unbuffered", "-u"}, */\r
1208 {"unicode", "-U"},\r
1209 /* {"skip_first", "-x"}, */\r
1210 {"bytes_warning", "-b"},\r
1211 {0}\r
1212};\r
1213\r
1214static PyStructSequence_Desc flags_desc = {\r
1215 "sys.flags", /* name */\r
1216 flags__doc__, /* doc */\r
1217 flags_fields, /* fields */\r
1218#ifdef RISCOS\r
1219 16\r
1220#else\r
1221 15\r
1222#endif\r
1223};\r
1224\r
1225static PyObject*\r
1226make_flags(void)\r
1227{\r
1228 int pos = 0;\r
1229 PyObject *seq;\r
1230\r
1231 seq = PyStructSequence_New(&FlagsType);\r
1232 if (seq == NULL)\r
1233 return NULL;\r
1234\r
1235#define SetFlag(flag) \\r
1236 PyStructSequence_SET_ITEM(seq, pos++, PyInt_FromLong(flag))\r
1237\r
1238 SetFlag(Py_DebugFlag);\r
1239 SetFlag(Py_Py3kWarningFlag);\r
1240 SetFlag(Py_DivisionWarningFlag);\r
1241 SetFlag(_Py_QnewFlag);\r
1242 SetFlag(Py_InspectFlag);\r
1243 SetFlag(Py_InteractiveFlag);\r
1244 SetFlag(Py_OptimizeFlag);\r
1245 SetFlag(Py_DontWriteBytecodeFlag);\r
1246 SetFlag(Py_NoUserSiteDirectory);\r
1247 SetFlag(Py_NoSiteFlag);\r
1248 SetFlag(Py_IgnoreEnvironmentFlag);\r
1249 SetFlag(Py_TabcheckFlag);\r
1250 SetFlag(Py_VerboseFlag);\r
1251#ifdef RISCOS\r
1252 SetFlag(Py_RISCOSWimpFlag);\r
1253#endif\r
1254 /* SetFlag(saw_unbuffered_flag); */\r
1255 SetFlag(Py_UnicodeFlag);\r
1256 /* SetFlag(skipfirstline); */\r
1257 SetFlag(Py_BytesWarningFlag);\r
1258#undef SetFlag\r
1259\r
1260 if (PyErr_Occurred()) {\r
1261 return NULL;\r
1262 }\r
1263 return seq;\r
1264}\r
1265\r
1266PyDoc_STRVAR(version_info__doc__,\r
1267"sys.version_info\n\\r
1268\n\\r
1269Version information as a named tuple.");\r
1270\r
1271static PyTypeObject VersionInfoType = {0, 0, 0, 0, 0, 0};\r
1272\r
1273static PyStructSequence_Field version_info_fields[] = {\r
1274 {"major", "Major release number"},\r
1275 {"minor", "Minor release number"},\r
1276 {"micro", "Patch release number"},\r
1277 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},\r
1278 {"serial", "Serial release number"},\r
1279 {0}\r
1280};\r
1281\r
1282static PyStructSequence_Desc version_info_desc = {\r
1283 "sys.version_info", /* name */\r
1284 version_info__doc__, /* doc */\r
1285 version_info_fields, /* fields */\r
1286 5\r
1287};\r
1288\r
1289static PyObject *\r
1290make_version_info(void)\r
1291{\r
1292 PyObject *version_info;\r
1293 char *s;\r
1294 int pos = 0;\r
1295\r
1296 version_info = PyStructSequence_New(&VersionInfoType);\r
1297 if (version_info == NULL) {\r
1298 return NULL;\r
1299 }\r
1300\r
1301 /*\r
1302 * These release level checks are mutually exclusive and cover\r
1303 * the field, so don't get too fancy with the pre-processor!\r
1304 */\r
1305#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA\r
1306 s = "alpha";\r
1307#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA\r
1308 s = "beta";\r
1309#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA\r
1310 s = "candidate";\r
1311#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL\r
1312 s = "final";\r
1313#endif\r
1314\r
1315#define SetIntItem(flag) \\r
1316 PyStructSequence_SET_ITEM(version_info, pos++, PyInt_FromLong(flag))\r
1317#define SetStrItem(flag) \\r
1318 PyStructSequence_SET_ITEM(version_info, pos++, PyString_FromString(flag))\r
1319\r
1320 SetIntItem(PY_MAJOR_VERSION);\r
1321 SetIntItem(PY_MINOR_VERSION);\r
1322 SetIntItem(PY_MICRO_VERSION);\r
1323 SetStrItem(s);\r
1324 SetIntItem(PY_RELEASE_SERIAL);\r
1325#undef SetIntItem\r
1326#undef SetStrItem\r
1327\r
1328 if (PyErr_Occurred()) {\r
1329 Py_CLEAR(version_info);\r
1330 return NULL;\r
1331 }\r
1332 return version_info;\r
1333}\r
1334\r
1335PyObject *\r
1336_PySys_Init(void)\r
1337{\r
1338 PyObject *m, *v, *sysdict;\r
1339 PyObject *sysin, *sysout, *syserr;\r
1340 char *s;\r
1341\r
1342 m = Py_InitModule3("sys", sys_methods, sys_doc);\r
1343 if (m == NULL)\r
1344 return NULL;\r
1345 sysdict = PyModule_GetDict(m);\r
1346#define SET_SYS_FROM_STRING(key, value) \\r
1347 v = value; \\r
1348 if (v != NULL) \\r
1349 PyDict_SetItemString(sysdict, key, v); \\r
1350 Py_XDECREF(v)\r
1351\r
1352 /* Check that stdin is not a directory\r
1353 Using shell redirection, you can redirect stdin to a directory,\r
1354 crashing the Python interpreter. Catch this common mistake here\r
1355 and output a useful error message. Note that under MS Windows,\r
1356 the shell already prevents that. */\r
1357#if !defined(MS_WINDOWS)\r
1358 {\r
1359 struct stat sb;\r
1360 if (fstat(fileno(stdin), &sb) == 0 &&\r
1361 S_ISDIR(sb.st_mode)) {\r
1362 /* There's nothing more we can do. */\r
1363 /* Py_FatalError() will core dump, so just exit. */\r
1364 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");\r
1365 exit(EXIT_FAILURE);\r
1366 }\r
1367 }\r
1368#endif\r
1369\r
1370 /* Closing the standard FILE* if sys.std* goes aways causes problems\r
1371 * for embedded Python usages. Closing them when somebody explicitly\r
1372 * invokes .close() might be possible, but the FAQ promises they get\r
1373 * never closed. However, we still need to get write errors when\r
1374 * writing fails (e.g. because stdout is redirected), so we flush the\r
1375 * streams and check for errors before the file objects are deleted.\r
1376 * On OS X, fflush()ing stdin causes an error, so we exempt stdin\r
1377 * from that procedure.\r
1378 */\r
1379 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);\r
1380 sysout = PyFile_FromFile(stdout, "<stdout>", "w", _check_and_flush);\r
1381 syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);\r
1382 if (PyErr_Occurred())\r
1383 return NULL;\r
1384\r
1385 PyDict_SetItemString(sysdict, "stdin", sysin);\r
1386 PyDict_SetItemString(sysdict, "stdout", sysout);\r
1387 PyDict_SetItemString(sysdict, "stderr", syserr);\r
1388 /* Make backup copies for cleanup */\r
1389 PyDict_SetItemString(sysdict, "__stdin__", sysin);\r
1390 PyDict_SetItemString(sysdict, "__stdout__", sysout);\r
1391 PyDict_SetItemString(sysdict, "__stderr__", syserr);\r
1392 PyDict_SetItemString(sysdict, "__displayhook__",\r
1393 PyDict_GetItemString(sysdict, "displayhook"));\r
1394 PyDict_SetItemString(sysdict, "__excepthook__",\r
1395 PyDict_GetItemString(sysdict, "excepthook"));\r
1396 Py_XDECREF(sysin);\r
1397 Py_XDECREF(sysout);\r
1398 Py_XDECREF(syserr);\r
1399\r
1400 SET_SYS_FROM_STRING("version",\r
1401 PyString_FromString(Py_GetVersion()));\r
1402 SET_SYS_FROM_STRING("hexversion",\r
1403 PyInt_FromLong(PY_VERSION_HEX));\r
1404 svnversion_init();\r
1405 SET_SYS_FROM_STRING("subversion",\r
1406 Py_BuildValue("(ssz)", "CPython", branch,\r
1407 svn_revision));\r
1408 SET_SYS_FROM_STRING("_mercurial",\r
1409 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),\r
1410 _Py_hgversion()));\r
1411 SET_SYS_FROM_STRING("dont_write_bytecode",\r
1412 PyBool_FromLong(Py_DontWriteBytecodeFlag));\r
1413 SET_SYS_FROM_STRING("api_version",\r
1414 PyInt_FromLong(PYTHON_API_VERSION));\r
1415 SET_SYS_FROM_STRING("copyright",\r
1416 PyString_FromString(Py_GetCopyright()));\r
1417 SET_SYS_FROM_STRING("platform",\r
1418 PyString_FromString(Py_GetPlatform()));\r
1419 SET_SYS_FROM_STRING("executable",\r
1420 PyString_FromString(Py_GetProgramFullPath()));\r
1421 SET_SYS_FROM_STRING("prefix",\r
1422 PyString_FromString(Py_GetPrefix()));\r
1423 SET_SYS_FROM_STRING("exec_prefix",\r
1424 PyString_FromString(Py_GetExecPrefix()));\r
1425 SET_SYS_FROM_STRING("maxsize",\r
1426 PyInt_FromSsize_t(PY_SSIZE_T_MAX));\r
1427 SET_SYS_FROM_STRING("maxint",\r
1428 PyInt_FromLong(PyInt_GetMax()));\r
1429 SET_SYS_FROM_STRING("py3kwarning",\r
1430 PyBool_FromLong(Py_Py3kWarningFlag));\r
1431 SET_SYS_FROM_STRING("float_info",\r
1432 PyFloat_GetInfo());\r
1433 SET_SYS_FROM_STRING("long_info",\r
1434 PyLong_GetInfo());\r
1435#ifdef Py_USING_UNICODE\r
1436 SET_SYS_FROM_STRING("maxunicode",\r
1437 PyInt_FromLong(PyUnicode_GetMax()));\r
1438#endif\r
1439 SET_SYS_FROM_STRING("builtin_module_names",\r
1440 list_builtin_module_names());\r
1441 {\r
1442 /* Assumes that longs are at least 2 bytes long.\r
1443 Should be safe! */\r
1444 unsigned long number = 1;\r
1445 char *value;\r
1446\r
1447 s = (char *) &number;\r
1448 if (s[0] == 0)\r
1449 value = "big";\r
1450 else\r
1451 value = "little";\r
1452 SET_SYS_FROM_STRING("byteorder",\r
1453 PyString_FromString(value));\r
1454 }\r
1455#ifdef MS_COREDLL\r
1456 SET_SYS_FROM_STRING("dllhandle",\r
1457 PyLong_FromVoidPtr(PyWin_DLLhModule));\r
1458 SET_SYS_FROM_STRING("winver",\r
1459 PyString_FromString(PyWin_DLLVersionString));\r
1460#endif\r
1461 if (warnoptions == NULL) {\r
1462 warnoptions = PyList_New(0);\r
1463 }\r
1464 else {\r
1465 Py_INCREF(warnoptions);\r
1466 }\r
1467 if (warnoptions != NULL) {\r
1468 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);\r
1469 }\r
1470\r
1471 /* version_info */\r
1472 if (VersionInfoType.tp_name == 0)\r
1473 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);\r
1474 SET_SYS_FROM_STRING("version_info", make_version_info());\r
1475 /* prevent user from creating new instances */\r
1476 VersionInfoType.tp_init = NULL;\r
1477 VersionInfoType.tp_new = NULL;\r
1478\r
1479 /* flags */\r
1480 if (FlagsType.tp_name == 0)\r
1481 PyStructSequence_InitType(&FlagsType, &flags_desc);\r
1482 SET_SYS_FROM_STRING("flags", make_flags());\r
1483 /* prevent user from creating new instances */\r
1484 FlagsType.tp_init = NULL;\r
1485 FlagsType.tp_new = NULL;\r
1486\r
1487\r
1488#if defined(MS_WINDOWS)\r
1489 /* getwindowsversion */\r
1490 if (WindowsVersionType.tp_name == 0)\r
1491 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);\r
1492 /* prevent user from creating new instances */\r
1493 WindowsVersionType.tp_init = NULL;\r
1494 WindowsVersionType.tp_new = NULL;\r
1495#endif\r
1496\r
1497 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */\r
1498#ifndef PY_NO_SHORT_FLOAT_REPR\r
1499 SET_SYS_FROM_STRING("float_repr_style",\r
1500 PyString_FromString("short"));\r
1501#else\r
1502 SET_SYS_FROM_STRING("float_repr_style",\r
1503 PyString_FromString("legacy"));\r
1504#endif\r
1505\r
1506#undef SET_SYS_FROM_STRING\r
1507 if (PyErr_Occurred())\r
1508 return NULL;\r
1509 return m;\r
1510}\r
1511\r
1512static PyObject *\r
1513makepathobject(char *path, int delim)\r
1514{\r
1515 int i, n;\r
1516 char *p;\r
1517 PyObject *v, *w;\r
1518\r
1519 n = 1;\r
1520 p = path;\r
1521 while ((p = strchr(p, delim)) != NULL) {\r
1522 n++;\r
1523 p++;\r
1524 }\r
1525 v = PyList_New(n);\r
1526 if (v == NULL)\r
1527 return NULL;\r
1528 for (i = 0; ; i++) {\r
1529 p = strchr(path, delim);\r
1530 if (p == NULL)\r
1531 p = strchr(path, '\0'); /* End of string */\r
1532 w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));\r
1533 if (w == NULL) {\r
1534 Py_DECREF(v);\r
1535 return NULL;\r
1536 }\r
1537 PyList_SetItem(v, i, w);\r
1538 if (*p == '\0')\r
1539 break;\r
1540 path = p+1;\r
1541 }\r
1542 return v;\r
1543}\r
1544\r
1545void\r
1546PySys_SetPath(char *path)\r
1547{\r
1548 PyObject *v;\r
1549 if ((v = makepathobject(path, DELIM)) == NULL)\r
1550 Py_FatalError("can't create sys.path");\r
1551 if (PySys_SetObject("path", v) != 0)\r
1552 Py_FatalError("can't assign sys.path");\r
1553 Py_DECREF(v);\r
1554}\r
1555\r
1556static PyObject *\r
1557makeargvobject(int argc, char **argv)\r
1558{\r
1559 PyObject *av;\r
1560 if (argc <= 0 || argv == NULL) {\r
1561 /* Ensure at least one (empty) argument is seen */\r
1562 static char *empty_argv[1] = {""};\r
1563 argv = empty_argv;\r
1564 argc = 1;\r
1565 }\r
1566 av = PyList_New(argc);\r
1567 if (av != NULL) {\r
1568 int i;\r
1569 for (i = 0; i < argc; i++) {\r
1570#ifdef __VMS\r
1571 PyObject *v;\r
1572\r
1573 /* argv[0] is the script pathname if known */\r
1574 if (i == 0) {\r
1575 char* fn = decc$translate_vms(argv[0]);\r
1576 if ((fn == (char *)0) || fn == (char *)-1)\r
1577 v = PyString_FromString(argv[0]);\r
1578 else\r
1579 v = PyString_FromString(\r
1580 decc$translate_vms(argv[0]));\r
1581 } else\r
1582 v = PyString_FromString(argv[i]);\r
1583#else\r
1584 PyObject *v = PyString_FromString(argv[i]);\r
1585#endif\r
1586 if (v == NULL) {\r
1587 Py_DECREF(av);\r
1588 av = NULL;\r
1589 break;\r
1590 }\r
1591 PyList_SetItem(av, i, v);\r
1592 }\r
1593 }\r
1594 return av;\r
1595}\r
1596\r
1597void\r
1598PySys_SetArgvEx(int argc, char **argv, int updatepath)\r
1599{\r
1600#if defined(HAVE_REALPATH)\r
1601 char fullpath[MAXPATHLEN];\r
1602#elif defined(MS_WINDOWS) && !defined(MS_WINCE)\r
1603 char fullpath[MAX_PATH];\r
1604#endif\r
1605 PyObject *av = makeargvobject(argc, argv);\r
1606 PyObject *path = PySys_GetObject("path");\r
1607 if (av == NULL)\r
1608 Py_FatalError("no mem for sys.argv");\r
1609 if (PySys_SetObject("argv", av) != 0)\r
1610 Py_FatalError("can't assign sys.argv");\r
1611 if (updatepath && path != NULL) {\r
1612 char *argv0 = argv[0];\r
1613 char *p = NULL;\r
1614 Py_ssize_t n = 0;\r
1615 PyObject *a;\r
1616#ifdef HAVE_READLINK\r
1617 char link[MAXPATHLEN+1];\r
1618 char argv0copy[2*MAXPATHLEN+1];\r
1619 int nr = 0;\r
1620 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)\r
1621 nr = readlink(argv0, link, MAXPATHLEN);\r
1622 if (nr > 0) {\r
1623 /* It's a symlink */\r
1624 link[nr] = '\0';\r
1625 if (link[0] == SEP)\r
1626 argv0 = link; /* Link to absolute path */\r
1627 else if (strchr(link, SEP) == NULL)\r
1628 ; /* Link without path */\r
1629 else {\r
1630 /* Must join(dirname(argv0), link) */\r
1631 char *q = strrchr(argv0, SEP);\r
1632 if (q == NULL)\r
1633 argv0 = link; /* argv0 without path */\r
1634 else {\r
1635 /* Must make a copy */\r
1636 strcpy(argv0copy, argv0);\r
1637 q = strrchr(argv0copy, SEP);\r
1638 strcpy(q+1, link);\r
1639 argv0 = argv0copy;\r
1640 }\r
1641 }\r
1642 }\r
1643#endif /* HAVE_READLINK */\r
1644#if SEP == '\\' /* Special case for MS filename syntax */\r
1645 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {\r
1646 char *q;\r
1647#if defined(MS_WINDOWS) && !defined(MS_WINCE)\r
1648 /* This code here replaces the first element in argv with the full\r
1649 path that it represents. Under CE, there are no relative paths so\r
1650 the argument must be the full path anyway. */\r
1651 char *ptemp;\r
1652 if (GetFullPathName(argv0,\r
1653 sizeof(fullpath),\r
1654 fullpath,\r
1655 &ptemp)) {\r
1656 argv0 = fullpath;\r
1657 }\r
1658#endif\r
1659 p = strrchr(argv0, SEP);\r
1660 /* Test for alternate separator */\r
1661 q = strrchr(p ? p : argv0, '/');\r
1662 if (q != NULL)\r
1663 p = q;\r
1664 if (p != NULL) {\r
1665 n = p + 1 - argv0;\r
1666 if (n > 1 && p[-1] != ':')\r
1667 n--; /* Drop trailing separator */\r
1668 }\r
1669 }\r
1670#else /* All other filename syntaxes */\r
1671 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {\r
1672#if defined(HAVE_REALPATH)\r
1673 if (realpath(argv0, fullpath)) {\r
1674 argv0 = fullpath;\r
1675 }\r
1676#endif\r
1677 p = strrchr(argv0, SEP);\r
1678 }\r
1679 if (p != NULL) {\r
1680#ifndef RISCOS\r
1681 n = p + 1 - argv0;\r
1682#else /* don't include trailing separator */\r
1683 n = p - argv0;\r
1684#endif /* RISCOS */\r
1685#if SEP == '/' /* Special case for Unix filename syntax */\r
1686 if (n > 1)\r
1687 n--; /* Drop trailing separator */\r
1688#endif /* Unix */\r
1689 }\r
1690#endif /* All others */\r
1691 a = PyString_FromStringAndSize(argv0, n);\r
1692 if (a == NULL)\r
1693 Py_FatalError("no mem for sys.path insertion");\r
1694 if (PyList_Insert(path, 0, a) < 0)\r
1695 Py_FatalError("sys.path.insert(0) failed");\r
1696 Py_DECREF(a);\r
1697 }\r
1698 Py_DECREF(av);\r
1699}\r
1700\r
1701void\r
1702PySys_SetArgv(int argc, char **argv)\r
1703{\r
1704 PySys_SetArgvEx(argc, argv, 1);\r
1705}\r
1706\r
1707\r
1708/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.\r
1709 Adapted from code submitted by Just van Rossum.\r
1710\r
1711 PySys_WriteStdout(format, ...)\r
1712 PySys_WriteStderr(format, ...)\r
1713\r
1714 The first function writes to sys.stdout; the second to sys.stderr. When\r
1715 there is a problem, they write to the real (C level) stdout or stderr;\r
1716 no exceptions are raised.\r
1717\r
1718 Both take a printf-style format string as their first argument followed\r
1719 by a variable length argument list determined by the format string.\r
1720\r
1721 *** WARNING ***\r
1722\r
1723 The format should limit the total size of the formatted output string to\r
1724 1000 bytes. In particular, this means that no unrestricted "%s" formats\r
1725 should occur; these should be limited using "%.<N>s where <N> is a\r
1726 decimal number calculated so that <N> plus the maximum size of other\r
1727 formatted text does not exceed 1000 bytes. Also watch out for "%f",\r
1728 which can print hundreds of digits for very large numbers.\r
1729\r
1730 */\r
1731\r
1732static void\r
1733mywrite(char *name, FILE *fp, const char *format, va_list va)\r
1734{\r
1735 PyObject *file;\r
1736 PyObject *error_type, *error_value, *error_traceback;\r
1737\r
1738 PyErr_Fetch(&error_type, &error_value, &error_traceback);\r
1739 file = PySys_GetObject(name);\r
1740 if (file == NULL || PyFile_AsFile(file) == fp)\r
1741 vfprintf(fp, format, va);\r
1742 else {\r
1743 char buffer[1001];\r
1744 const int written = PyOS_vsnprintf(buffer, sizeof(buffer),\r
1745 format, va);\r
1746 if (PyFile_WriteString(buffer, file) != 0) {\r
1747 PyErr_Clear();\r
1748 fputs(buffer, fp);\r
1749 }\r
1750 if (written < 0 || (size_t)written >= sizeof(buffer)) {\r
1751 const char *truncated = "... truncated";\r
1752 if (PyFile_WriteString(truncated, file) != 0) {\r
1753 PyErr_Clear();\r
1754 fputs(truncated, fp);\r
1755 }\r
1756 }\r
1757 }\r
1758 PyErr_Restore(error_type, error_value, error_traceback);\r
1759}\r
1760\r
1761void\r
1762PySys_WriteStdout(const char *format, ...)\r
1763{\r
1764 va_list va;\r
1765\r
1766 va_start(va, format);\r
1767 mywrite("stdout", stdout, format, va);\r
1768 va_end(va);\r
1769}\r
1770\r
1771void\r
1772PySys_WriteStderr(const char *format, ...)\r
1773{\r
1774 va_list va;\r
1775\r
1776 va_start(va, format);\r
1777 mywrite("stderr", stderr, format, va);\r
1778 va_end(va);\r
1779}\r