sysmodule.c revision a37d4c693a024154093b36a612810c3bd72d9254
1 2/* System module */ 3 4/* 5Various bits of information used by the interpreter are collected in 6module 'sys'. 7Function member: 8- exit(sts): raise SystemExit 9Data members: 10- stdin, stdout, stderr: standard file objects 11- modules: the table of modules (dictionary) 12- path: module search path (list of strings) 13- argv: script arguments (list of strings) 14- ps1, ps2: optional primary and secondary prompts (strings) 15*/ 16 17#include "Python.h" 18#include "code.h" 19#include "frameobject.h" 20#include "eval.h" 21 22#include "osdefs.h" 23 24#ifdef MS_WINDOWS 25#define WIN32_LEAN_AND_MEAN 26#include <windows.h> 27#endif /* MS_WINDOWS */ 28 29#ifdef MS_COREDLL 30extern void *PyWin_DLLhModule; 31/* A string loaded from the DLL at startup: */ 32extern const char *PyWin_DLLVersionString; 33#endif 34 35#ifdef __VMS 36#include <unixlib.h> 37#endif 38 39#ifdef HAVE_LANGINFO_H 40#include <locale.h> 41#include <langinfo.h> 42#endif 43 44PyObject * 45PySys_GetObject(const char *name) 46{ 47 PyThreadState *tstate = PyThreadState_GET(); 48 PyObject *sd = tstate->interp->sysdict; 49 if (sd == NULL) 50 return NULL; 51 return PyDict_GetItemString(sd, name); 52} 53 54int 55PySys_SetObject(const char *name, PyObject *v) 56{ 57 PyThreadState *tstate = PyThreadState_GET(); 58 PyObject *sd = tstate->interp->sysdict; 59 if (v == NULL) { 60 if (PyDict_GetItemString(sd, name) == NULL) 61 return 0; 62 else 63 return PyDict_DelItemString(sd, name); 64 } 65 else 66 return PyDict_SetItemString(sd, name, v); 67} 68 69static PyObject * 70sys_displayhook(PyObject *self, PyObject *o) 71{ 72 PyObject *outf; 73 PyInterpreterState *interp = PyThreadState_GET()->interp; 74 PyObject *modules = interp->modules; 75 PyObject *builtins = PyDict_GetItemString(modules, "builtins"); 76 77 if (builtins == NULL) { 78 PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); 79 return NULL; 80 } 81 82 /* Print value except if None */ 83 /* After printing, also assign to '_' */ 84 /* Before, set '_' to None to avoid recursion */ 85 if (o == Py_None) { 86 Py_INCREF(Py_None); 87 return Py_None; 88 } 89 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) 90 return NULL; 91 outf = PySys_GetObject("stdout"); 92 if (outf == NULL || outf == Py_None) { 93 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); 94 return NULL; 95 } 96 if (PyFile_WriteObject(o, outf, 0) != 0) 97 return NULL; 98 if (PyFile_WriteString("\n", outf) != 0) 99 return NULL; 100 if (PyObject_SetAttrString(builtins, "_", o) != 0) 101 return NULL; 102 Py_INCREF(Py_None); 103 return Py_None; 104} 105 106PyDoc_STRVAR(displayhook_doc, 107"displayhook(object) -> None\n" 108"\n" 109"Print an object to sys.stdout and also save it in builtins.\n" 110); 111 112static PyObject * 113sys_excepthook(PyObject* self, PyObject* args) 114{ 115 PyObject *exc, *value, *tb; 116 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) 117 return NULL; 118 PyErr_Display(exc, value, tb); 119 Py_INCREF(Py_None); 120 return Py_None; 121} 122 123PyDoc_STRVAR(excepthook_doc, 124"excepthook(exctype, value, traceback) -> None\n" 125"\n" 126"Handle an exception by displaying it with a traceback on sys.stderr.\n" 127); 128 129static PyObject * 130sys_exc_info(PyObject *self, PyObject *noargs) 131{ 132 PyThreadState *tstate; 133 tstate = PyThreadState_GET(); 134 return Py_BuildValue( 135 "(OOO)", 136 tstate->exc_type != NULL ? tstate->exc_type : Py_None, 137 tstate->exc_value != NULL ? tstate->exc_value : Py_None, 138 tstate->exc_traceback != NULL ? 139 tstate->exc_traceback : Py_None); 140} 141 142PyDoc_STRVAR(exc_info_doc, 143"exc_info() -> (type, value, traceback)\n\ 144\n\ 145Return information about the most recent exception caught by an except\n\ 146clause in the current stack frame or in an older stack frame." 147); 148 149static PyObject * 150sys_exit(PyObject *self, PyObject *args) 151{ 152 PyObject *exit_code = 0; 153 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) 154 return NULL; 155 /* Raise SystemExit so callers may catch it or clean up. */ 156 PyErr_SetObject(PyExc_SystemExit, exit_code); 157 return NULL; 158} 159 160PyDoc_STRVAR(exit_doc, 161"exit([status])\n\ 162\n\ 163Exit the interpreter by raising SystemExit(status).\n\ 164If the status is omitted or None, it defaults to zero (i.e., success).\n\ 165If the status is numeric, it will be used as the system exit status.\n\ 166If it is another kind of object, it will be printed and the system\n\ 167exit status will be one (i.e., failure)." 168); 169 170 171static PyObject * 172sys_getdefaultencoding(PyObject *self) 173{ 174 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); 175} 176 177PyDoc_STRVAR(getdefaultencoding_doc, 178"getdefaultencoding() -> string\n\ 179\n\ 180Return the current default string encoding used by the Unicode \n\ 181implementation." 182); 183 184static PyObject * 185sys_setdefaultencoding(PyObject *self, PyObject *args) 186{ 187 char *encoding; 188 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) 189 return NULL; 190 if (PyUnicode_SetDefaultEncoding(encoding)) 191 return NULL; 192 Py_INCREF(Py_None); 193 return Py_None; 194} 195 196PyDoc_STRVAR(setdefaultencoding_doc, 197"setdefaultencoding(encoding)\n\ 198\n\ 199Set the current default string encoding used by the Unicode implementation." 200); 201 202static PyObject * 203sys_getfilesystemencoding(PyObject *self) 204{ 205 if (Py_FileSystemDefaultEncoding) 206 return PyUnicode_FromString(Py_FileSystemDefaultEncoding); 207 Py_INCREF(Py_None); 208 return Py_None; 209} 210 211PyDoc_STRVAR(getfilesystemencoding_doc, 212"getfilesystemencoding() -> string\n\ 213\n\ 214Return the encoding used to convert Unicode filenames in\n\ 215operating system filenames." 216); 217 218 219 220static PyObject * 221sys_intern(PyObject *self, PyObject *args) 222{ 223 PyObject *s; 224 if (!PyArg_ParseTuple(args, "U:intern", &s)) 225 return NULL; 226 if (PyUnicode_CheckExact(s)) { 227 Py_INCREF(s); 228 PyUnicode_InternInPlace(&s); 229 return s; 230 } 231 else { 232 PyErr_Format(PyExc_TypeError, 233 "can't intern %.400s", s->ob_type->tp_name); 234 return NULL; 235 } 236} 237 238PyDoc_STRVAR(intern_doc, 239"intern(string) -> string\n\ 240\n\ 241``Intern'' the given string. This enters the string in the (global)\n\ 242table of interned strings whose purpose is to speed up dictionary lookups.\n\ 243Return the string itself or the previously interned string object with the\n\ 244same value."); 245 246 247/* 248 * Cached interned string objects used for calling the profile and 249 * trace functions. Initialized by trace_init(). 250 */ 251static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL}; 252 253static int 254trace_init(void) 255{ 256 static char *whatnames[7] = {"call", "exception", "line", "return", 257 "c_call", "c_exception", "c_return"}; 258 PyObject *name; 259 int i; 260 for (i = 0; i < 7; ++i) { 261 if (whatstrings[i] == NULL) { 262 name = PyUnicode_InternFromString(whatnames[i]); 263 if (name == NULL) 264 return -1; 265 whatstrings[i] = name; 266 } 267 } 268 return 0; 269} 270 271 272static PyObject * 273call_trampoline(PyThreadState *tstate, PyObject* callback, 274 PyFrameObject *frame, int what, PyObject *arg) 275{ 276 PyObject *args = PyTuple_New(3); 277 PyObject *whatstr; 278 PyObject *result; 279 280 if (args == NULL) 281 return NULL; 282 Py_INCREF(frame); 283 whatstr = whatstrings[what]; 284 Py_INCREF(whatstr); 285 if (arg == NULL) 286 arg = Py_None; 287 Py_INCREF(arg); 288 PyTuple_SET_ITEM(args, 0, (PyObject *)frame); 289 PyTuple_SET_ITEM(args, 1, whatstr); 290 PyTuple_SET_ITEM(args, 2, arg); 291 292 /* call the Python-level function */ 293 PyFrame_FastToLocals(frame); 294 result = PyEval_CallObject(callback, args); 295 PyFrame_LocalsToFast(frame, 1); 296 if (result == NULL) 297 PyTraceBack_Here(frame); 298 299 /* cleanup */ 300 Py_DECREF(args); 301 return result; 302} 303 304static int 305profile_trampoline(PyObject *self, PyFrameObject *frame, 306 int what, PyObject *arg) 307{ 308 PyThreadState *tstate = frame->f_tstate; 309 PyObject *result; 310 311 if (arg == NULL) 312 arg = Py_None; 313 result = call_trampoline(tstate, self, frame, what, arg); 314 if (result == NULL) { 315 PyEval_SetProfile(NULL, NULL); 316 return -1; 317 } 318 Py_DECREF(result); 319 return 0; 320} 321 322static int 323trace_trampoline(PyObject *self, PyFrameObject *frame, 324 int what, PyObject *arg) 325{ 326 PyThreadState *tstate = frame->f_tstate; 327 PyObject *callback; 328 PyObject *result; 329 330 if (what == PyTrace_CALL) 331 callback = self; 332 else 333 callback = frame->f_trace; 334 if (callback == NULL) 335 return 0; 336 result = call_trampoline(tstate, callback, frame, what, arg); 337 if (result == NULL) { 338 PyEval_SetTrace(NULL, NULL); 339 Py_XDECREF(frame->f_trace); 340 frame->f_trace = NULL; 341 return -1; 342 } 343 if (result != Py_None) { 344 PyObject *temp = frame->f_trace; 345 frame->f_trace = NULL; 346 Py_XDECREF(temp); 347 frame->f_trace = result; 348 } 349 else { 350 Py_DECREF(result); 351 } 352 return 0; 353} 354 355static PyObject * 356sys_settrace(PyObject *self, PyObject *args) 357{ 358 if (trace_init() == -1) 359 return NULL; 360 if (args == Py_None) 361 PyEval_SetTrace(NULL, NULL); 362 else 363 PyEval_SetTrace(trace_trampoline, args); 364 Py_INCREF(Py_None); 365 return Py_None; 366} 367 368PyDoc_STRVAR(settrace_doc, 369"settrace(function)\n\ 370\n\ 371Set the global debug tracing function. It will be called on each\n\ 372function call. See the debugger chapter in the library manual." 373); 374 375static PyObject * 376sys_setprofile(PyObject *self, PyObject *args) 377{ 378 if (trace_init() == -1) 379 return NULL; 380 if (args == Py_None) 381 PyEval_SetProfile(NULL, NULL); 382 else 383 PyEval_SetProfile(profile_trampoline, args); 384 Py_INCREF(Py_None); 385 return Py_None; 386} 387 388PyDoc_STRVAR(setprofile_doc, 389"setprofile(function)\n\ 390\n\ 391Set the profiling function. It will be called on each function call\n\ 392and return. See the profiler chapter in the library manual." 393); 394 395static PyObject * 396sys_setcheckinterval(PyObject *self, PyObject *args) 397{ 398 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval)) 399 return NULL; 400 Py_INCREF(Py_None); 401 return Py_None; 402} 403 404PyDoc_STRVAR(setcheckinterval_doc, 405"setcheckinterval(n)\n\ 406\n\ 407Tell the Python interpreter to check for asynchronous events every\n\ 408n instructions. This also affects how often thread switches occur." 409); 410 411static PyObject * 412sys_getcheckinterval(PyObject *self, PyObject *args) 413{ 414 return PyLong_FromLong(_Py_CheckInterval); 415} 416 417PyDoc_STRVAR(getcheckinterval_doc, 418"getcheckinterval() -> current check interval; see setcheckinterval()." 419); 420 421#ifdef WITH_TSC 422static PyObject * 423sys_settscdump(PyObject *self, PyObject *args) 424{ 425 int bool; 426 PyThreadState *tstate = PyThreadState_Get(); 427 428 if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) 429 return NULL; 430 if (bool) 431 tstate->interp->tscdump = 1; 432 else 433 tstate->interp->tscdump = 0; 434 Py_INCREF(Py_None); 435 return Py_None; 436 437} 438 439PyDoc_STRVAR(settscdump_doc, 440"settscdump(bool)\n\ 441\n\ 442If true, tell the Python interpreter to dump VM measurements to\n\ 443stderr. If false, turn off dump. The measurements are based on the\n\ 444processor's time-stamp counter." 445); 446#endif /* TSC */ 447 448static PyObject * 449sys_setrecursionlimit(PyObject *self, PyObject *args) 450{ 451 int new_limit; 452 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) 453 return NULL; 454 if (new_limit <= 0) { 455 PyErr_SetString(PyExc_ValueError, 456 "recursion limit must be positive"); 457 return NULL; 458 } 459 Py_SetRecursionLimit(new_limit); 460 Py_INCREF(Py_None); 461 return Py_None; 462} 463 464PyDoc_STRVAR(setrecursionlimit_doc, 465"setrecursionlimit(n)\n\ 466\n\ 467Set the maximum depth of the Python interpreter stack to n. This\n\ 468limit prevents infinite recursion from causing an overflow of the C\n\ 469stack and crashing Python. The highest possible limit is platform-\n\ 470dependent." 471); 472 473static PyObject * 474sys_getrecursionlimit(PyObject *self) 475{ 476 return PyLong_FromLong(Py_GetRecursionLimit()); 477} 478 479PyDoc_STRVAR(getrecursionlimit_doc, 480"getrecursionlimit()\n\ 481\n\ 482Return the current value of the recursion limit, the maximum depth\n\ 483of the Python interpreter stack. This limit prevents infinite\n\ 484recursion from causing an overflow of the C stack and crashing Python." 485); 486 487#ifdef MS_WINDOWS 488PyDoc_STRVAR(getwindowsversion_doc, 489"getwindowsversion()\n\ 490\n\ 491Return information about the running version of Windows.\n\ 492The result is a tuple of (major, minor, build, platform, text)\n\ 493All elements are numbers, except text which is a string.\n\ 494Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\ 495" 496); 497 498static PyObject * 499sys_getwindowsversion(PyObject *self) 500{ 501 OSVERSIONINFO ver; 502 ver.dwOSVersionInfoSize = sizeof(ver); 503 if (!GetVersionEx(&ver)) 504 return PyErr_SetFromWindowsErr(0); 505 return Py_BuildValue("HHHHs", 506 ver.dwMajorVersion, 507 ver.dwMinorVersion, 508 ver.dwBuildNumber, 509 ver.dwPlatformId, 510 ver.szCSDVersion); 511} 512 513#endif /* MS_WINDOWS */ 514 515#ifdef HAVE_DLOPEN 516static PyObject * 517sys_setdlopenflags(PyObject *self, PyObject *args) 518{ 519 int new_val; 520 PyThreadState *tstate = PyThreadState_GET(); 521 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) 522 return NULL; 523 if (!tstate) 524 return NULL; 525 tstate->interp->dlopenflags = new_val; 526 Py_INCREF(Py_None); 527 return Py_None; 528} 529 530PyDoc_STRVAR(setdlopenflags_doc, 531"setdlopenflags(n) -> None\n\ 532\n\ 533Set the flags that will be used for dlopen() calls. Among other\n\ 534things, this will enable a lazy resolving of symbols when importing\n\ 535a module, if called as sys.setdlopenflags(0)\n\ 536To share symbols across extension modules, call as\n\ 537sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)" 538); 539 540static PyObject * 541sys_getdlopenflags(PyObject *self, PyObject *args) 542{ 543 PyThreadState *tstate = PyThreadState_GET(); 544 if (!tstate) 545 return NULL; 546 return PyLong_FromLong(tstate->interp->dlopenflags); 547} 548 549PyDoc_STRVAR(getdlopenflags_doc, 550"getdlopenflags() -> int\n\ 551\n\ 552Return the current value of the flags that are used for dlopen()\n\ 553calls. The flag constants are defined in the dl module." 554); 555#endif 556 557#ifdef USE_MALLOPT 558/* Link with -lmalloc (or -lmpc) on an SGI */ 559#include <malloc.h> 560 561static PyObject * 562sys_mdebug(PyObject *self, PyObject *args) 563{ 564 int flag; 565 if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) 566 return NULL; 567 mallopt(M_DEBUG, flag); 568 Py_INCREF(Py_None); 569 return Py_None; 570} 571#endif /* USE_MALLOPT */ 572 573static PyObject * 574sys_getrefcount(PyObject *self, PyObject *arg) 575{ 576 return PyLong_FromSsize_t(arg->ob_refcnt); 577} 578 579#ifdef Py_REF_DEBUG 580static PyObject * 581sys_gettotalrefcount(PyObject *self) 582{ 583 return PyLong_FromSsize_t(_Py_GetRefTotal()); 584} 585#endif /* Py_REF_DEBUG */ 586 587PyDoc_STRVAR(getrefcount_doc, 588"getrefcount(object) -> integer\n\ 589\n\ 590Return the reference count of object. The count returned is generally\n\ 591one higher than you might expect, because it includes the (temporary)\n\ 592reference as an argument to getrefcount()." 593); 594 595#ifdef COUNT_ALLOCS 596static PyObject * 597sys_getcounts(PyObject *self) 598{ 599 extern PyObject *get_counts(void); 600 601 return get_counts(); 602} 603#endif 604 605PyDoc_STRVAR(getframe_doc, 606"_getframe([depth]) -> frameobject\n\ 607\n\ 608Return a frame object from the call stack. If optional integer depth is\n\ 609given, return the frame object that many calls below the top of the stack.\n\ 610If that is deeper than the call stack, ValueError is raised. The default\n\ 611for depth is zero, returning the frame at the top of the call stack.\n\ 612\n\ 613This function should be used for internal and specialized\n\ 614purposes only." 615); 616 617static PyObject * 618sys_getframe(PyObject *self, PyObject *args) 619{ 620 PyFrameObject *f = PyThreadState_GET()->frame; 621 int depth = -1; 622 623 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) 624 return NULL; 625 626 while (depth > 0 && f != NULL) { 627 f = f->f_back; 628 --depth; 629 } 630 if (f == NULL) { 631 PyErr_SetString(PyExc_ValueError, 632 "call stack is not deep enough"); 633 return NULL; 634 } 635 Py_INCREF(f); 636 return (PyObject*)f; 637} 638 639PyDoc_STRVAR(current_frames_doc, 640"_current_frames() -> dictionary\n\ 641\n\ 642Return a dictionary mapping each current thread T's thread id to T's\n\ 643current stack frame.\n\ 644\n\ 645This function should be used for specialized purposes only." 646); 647 648static PyObject * 649sys_current_frames(PyObject *self, PyObject *noargs) 650{ 651 return _PyThread_CurrentFrames(); 652} 653 654PyDoc_STRVAR(call_tracing_doc, 655"call_tracing(func, args) -> object\n\ 656\n\ 657Call func(*args), while tracing is enabled. The tracing state is\n\ 658saved, and restored afterwards. This is intended to be called from\n\ 659a debugger from a checkpoint, to recursively debug some other code." 660); 661 662static PyObject * 663sys_call_tracing(PyObject *self, PyObject *args) 664{ 665 PyObject *func, *funcargs; 666 if (!PyArg_UnpackTuple(args, "call_tracing", 2, 2, &func, &funcargs)) 667 return NULL; 668 return _PyEval_CallTracing(func, funcargs); 669} 670 671PyDoc_STRVAR(callstats_doc, 672"callstats() -> tuple of integers\n\ 673\n\ 674Return a tuple of function call statistics, if CALL_PROFILE was defined\n\ 675when Python was built. Otherwise, return None.\n\ 676\n\ 677When enabled, this function returns detailed, implementation-specific\n\ 678details about the number of function calls executed. The return value is\n\ 679a 11-tuple where the entries in the tuple are counts of:\n\ 6800. all function calls\n\ 6811. calls to PyFunction_Type objects\n\ 6822. PyFunction calls that do not create an argument tuple\n\ 6833. PyFunction calls that do not create an argument tuple\n\ 684 and bypass PyEval_EvalCodeEx()\n\ 6854. PyMethod calls\n\ 6865. PyMethod calls on bound methods\n\ 6876. PyType calls\n\ 6887. PyCFunction calls\n\ 6898. generator calls\n\ 6909. All other calls\n\ 69110. Number of stack pops performed by call_function()" 692); 693 694#ifdef __cplusplus 695extern "C" { 696#endif 697 698#ifdef Py_TRACE_REFS 699/* Defined in objects.c because it uses static globals if that file */ 700extern PyObject *_Py_GetObjects(PyObject *, PyObject *); 701#endif 702 703#ifdef DYNAMIC_EXECUTION_PROFILE 704/* Defined in ceval.c because it uses static globals if that file */ 705extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *); 706#endif 707 708#ifdef __cplusplus 709} 710#endif 711 712static PyMethodDef sys_methods[] = { 713 /* Might as well keep this in alphabetic order */ 714 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, 715 callstats_doc}, 716 {"_current_frames", sys_current_frames, METH_NOARGS, 717 current_frames_doc}, 718 {"displayhook", sys_displayhook, METH_O, displayhook_doc}, 719 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, 720 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, 721 {"exit", sys_exit, METH_VARARGS, exit_doc}, 722 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, 723 METH_NOARGS, getdefaultencoding_doc}, 724#ifdef HAVE_DLOPEN 725 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, 726 getdlopenflags_doc}, 727#endif 728#ifdef COUNT_ALLOCS 729 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, 730#endif 731#ifdef DYNAMIC_EXECUTION_PROFILE 732 {"getdxp", _Py_GetDXProfile, METH_VARARGS}, 733#endif 734 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, 735 METH_NOARGS, getfilesystemencoding_doc}, 736#ifdef Py_TRACE_REFS 737 {"getobjects", _Py_GetObjects, METH_VARARGS}, 738#endif 739#ifdef Py_REF_DEBUG 740 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, 741#endif 742 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, 743 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, 744 getrecursionlimit_doc}, 745 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, 746#ifdef MS_WINDOWS 747 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, 748 getwindowsversion_doc}, 749#endif /* MS_WINDOWS */ 750 {"intern", sys_intern, METH_VARARGS, intern_doc}, 751#ifdef USE_MALLOPT 752 {"mdebug", sys_mdebug, METH_VARARGS}, 753#endif 754 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, 755 setdefaultencoding_doc}, 756 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, 757 setcheckinterval_doc}, 758 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, 759 getcheckinterval_doc}, 760#ifdef HAVE_DLOPEN 761 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, 762 setdlopenflags_doc}, 763#endif 764 {"setprofile", sys_setprofile, METH_O, setprofile_doc}, 765 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, 766 setrecursionlimit_doc}, 767#ifdef WITH_TSC 768 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, 769#endif 770 {"settrace", sys_settrace, METH_O, settrace_doc}, 771 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, 772 {NULL, NULL} /* sentinel */ 773}; 774 775static PyObject * 776list_builtin_module_names(void) 777{ 778 PyObject *list = PyList_New(0); 779 int i; 780 if (list == NULL) 781 return NULL; 782 for (i = 0; PyImport_Inittab[i].name != NULL; i++) { 783 PyObject *name = PyUnicode_FromString( 784 PyImport_Inittab[i].name); 785 if (name == NULL) 786 break; 787 PyList_Append(list, name); 788 Py_DECREF(name); 789 } 790 if (PyList_Sort(list) != 0) { 791 Py_DECREF(list); 792 list = NULL; 793 } 794 if (list) { 795 PyObject *v = PyList_AsTuple(list); 796 Py_DECREF(list); 797 list = v; 798 } 799 return list; 800} 801 802static PyObject *warnoptions = NULL; 803 804void 805PySys_ResetWarnOptions(void) 806{ 807 if (warnoptions == NULL || !PyList_Check(warnoptions)) 808 return; 809 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); 810} 811 812void 813PySys_AddWarnOption(const char *s) 814{ 815 PyObject *str; 816 817 if (warnoptions == NULL || !PyList_Check(warnoptions)) { 818 Py_XDECREF(warnoptions); 819 warnoptions = PyList_New(0); 820 if (warnoptions == NULL) 821 return; 822 } 823 str = PyUnicode_FromString(s); 824 if (str != NULL) { 825 PyList_Append(warnoptions, str); 826 Py_DECREF(str); 827 } 828} 829 830/* XXX This doc string is too long to be a single string literal in VC++ 5.0. 831 Two literals concatenated works just fine. If you have a K&R compiler 832 or other abomination that however *does* understand longer strings, 833 get rid of the !!! comment in the middle and the quotes that surround it. */ 834PyDoc_VAR(sys_doc) = 835PyDoc_STR( 836"This module provides access to some objects used or maintained by the\n\ 837interpreter and to functions that interact strongly with the interpreter.\n\ 838\n\ 839Dynamic objects:\n\ 840\n\ 841argv -- command line arguments; argv[0] is the script pathname if known\n\ 842path -- module search path; path[0] is the script directory, else ''\n\ 843modules -- dictionary of loaded modules\n\ 844\n\ 845displayhook -- called to show results in an interactive session\n\ 846excepthook -- called to handle any uncaught exception other than SystemExit\n\ 847 To customize printing in an interactive session or to install a custom\n\ 848 top-level exception handler, assign other functions to replace these.\n\ 849\n\ 850stdin -- standard input file object; used by raw_input() and input()\n\ 851stdout -- standard output file object; used by print()\n\ 852stderr -- standard error object; used for error messages\n\ 853 By assigning other file objects (or objects that behave like files)\n\ 854 to these, it is possible to redirect all of the interpreter's I/O.\n\ 855\n\ 856last_type -- type of last uncaught exception\n\ 857last_value -- value of last uncaught exception\n\ 858last_traceback -- traceback of last uncaught exception\n\ 859 These three are only available in an interactive session after a\n\ 860 traceback has been printed.\n\ 861" 862) 863/* concatenating string here */ 864PyDoc_STR( 865"\n\ 866Static objects:\n\ 867\n\ 868maxint -- the largest supported integer (the smallest is -maxint-1)\n\ 869maxsize -- the largest supported length of containers.\n\ 870maxunicode -- the largest supported character\n\ 871builtin_module_names -- tuple of module names built into this interpreter\n\ 872version -- the version of this interpreter as a string\n\ 873version_info -- version information as a tuple\n\ 874hexversion -- version information encoded as a single integer\n\ 875copyright -- copyright notice pertaining to this interpreter\n\ 876platform -- platform identifier\n\ 877executable -- pathname of this Python interpreter\n\ 878prefix -- prefix used to find the Python library\n\ 879exec_prefix -- prefix used to find the machine-specific Python library\n\ 880" 881) 882#ifdef MS_WINDOWS 883/* concatenating string here */ 884PyDoc_STR( 885"dllhandle -- [Windows only] integer handle of the Python DLL\n\ 886winver -- [Windows only] version number of the Python DLL\n\ 887" 888) 889#endif /* MS_WINDOWS */ 890PyDoc_STR( 891"__stdin__ -- the original stdin; don't touch!\n\ 892__stdout__ -- the original stdout; don't touch!\n\ 893__stderr__ -- the original stderr; don't touch!\n\ 894__displayhook__ -- the original displayhook; don't touch!\n\ 895__excepthook__ -- the original excepthook; don't touch!\n\ 896\n\ 897Functions:\n\ 898\n\ 899displayhook() -- print an object to the screen, and save it in builtins._\n\ 900excepthook() -- print an exception and its traceback to sys.stderr\n\ 901exc_info() -- return thread-safe information about the current exception\n\ 902exit() -- exit the interpreter by raising SystemExit\n\ 903getdlopenflags() -- returns flags to be used for dlopen() calls\n\ 904getrefcount() -- return the reference count for an object (plus one :-)\n\ 905getrecursionlimit() -- return the max recursion depth for the interpreter\n\ 906setcheckinterval() -- control how often the interpreter checks for events\n\ 907setdlopenflags() -- set the flags to be used for dlopen() calls\n\ 908setprofile() -- set the global profiling function\n\ 909setrecursionlimit() -- set the max recursion depth for the interpreter\n\ 910settrace() -- set the global debug tracing function\n\ 911" 912) 913/* end of sys_doc */ ; 914 915/* Subversion branch and revision management */ 916static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION; 917static const char headurl[] = "$HeadURL$"; 918static int svn_initialized; 919static char patchlevel_revision[50]; /* Just the number */ 920static char branch[50]; 921static char shortbranch[50]; 922static const char *svn_revision; 923 924static void 925svnversion_init(void) 926{ 927 const char *python, *br_start, *br_end, *br_end2, *svnversion; 928 Py_ssize_t len; 929 int istag = 0; 930 931 if (svn_initialized) 932 return; 933 934 python = strstr(headurl, "/python/"); 935 if (!python) { 936 strcpy(branch, "unknown branch"); 937 strcpy(shortbranch, "unknown"); 938 } 939 else { 940 br_start = python + 8; 941 br_end = strchr(br_start, '/'); 942 assert(br_end); 943 944 /* Works even for trunk, 945 as we are in trunk/Python/sysmodule.c */ 946 br_end2 = strchr(br_end+1, '/'); 947 948 istag = strncmp(br_start, "tags", 4) == 0; 949 if (strncmp(br_start, "trunk", 5) == 0) { 950 strcpy(branch, "trunk"); 951 strcpy(shortbranch, "trunk"); 952 } 953 else if (istag || strncmp(br_start, "branches", 8) == 0) { 954 len = br_end2 - br_start; 955 strncpy(branch, br_start, len); 956 branch[len] = '\0'; 957 958 len = br_end2 - (br_end + 1); 959 strncpy(shortbranch, br_end + 1, len); 960 shortbranch[len] = '\0'; 961 } 962 else { 963 Py_FatalError("bad HeadURL"); 964 return; 965 } 966 } 967 968 969 svnversion = _Py_svnversion(); 970 if (strcmp(svnversion, "exported") != 0) 971 svn_revision = svnversion; 972 else if (istag) { 973 len = strlen(_patchlevel_revision); 974 assert(len >= 13); 975 assert(len < (sizeof(patchlevel_revision) + 13)); 976 strncpy(patchlevel_revision, _patchlevel_revision + 11, 977 len - 13); 978 patchlevel_revision[len - 13] = '\0'; 979 svn_revision = patchlevel_revision; 980 } 981 else 982 svn_revision = ""; 983 984 svn_initialized = 1; 985} 986 987/* Return svnversion output if available. 988 Else return Revision of patchlevel.h if on branch. 989 Else return empty string */ 990const char* 991Py_SubversionRevision() 992{ 993 svnversion_init(); 994 return svn_revision; 995} 996 997const char* 998Py_SubversionShortBranch() 999{ 1000 svnversion_init(); 1001 return shortbranch; 1002} 1003 1004PyObject * 1005_PySys_Init(void) 1006{ 1007 PyObject *m, *v, *sysdict; 1008 char *s; 1009 1010 m = Py_InitModule3("sys", sys_methods, sys_doc); 1011 if (m == NULL) 1012 return NULL; 1013 sysdict = PyModule_GetDict(m); 1014 1015 { 1016 /* XXX: does this work on Win/Win64? (see posix_fstat) */ 1017 struct stat sb; 1018 if (fstat(fileno(stdin), &sb) == 0 && 1019 S_ISDIR(sb.st_mode)) { 1020 /* There's nothing more we can do. */ 1021 /* Py_FatalError() will core dump, so just exit. */ 1022 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n"); 1023 exit(EXIT_FAILURE); 1024 } 1025 } 1026 1027 /* stdin/stdout/stderr are now set by site.py. */ 1028 1029 PyDict_SetItemString(sysdict, "__displayhook__", 1030 PyDict_GetItemString(sysdict, "displayhook")); 1031 PyDict_SetItemString(sysdict, "__excepthook__", 1032 PyDict_GetItemString(sysdict, "excepthook")); 1033 PyDict_SetItemString(sysdict, "version", 1034 v = PyUnicode_FromString(Py_GetVersion())); 1035 Py_XDECREF(v); 1036 PyDict_SetItemString(sysdict, "hexversion", 1037 v = PyLong_FromLong(PY_VERSION_HEX)); 1038 Py_XDECREF(v); 1039 svnversion_init(); 1040 v = Py_BuildValue("(UUU)", "CPython", branch, svn_revision); 1041 PyDict_SetItemString(sysdict, "subversion", v); 1042 Py_XDECREF(v); 1043 /* 1044 * These release level checks are mutually exclusive and cover 1045 * the field, so don't get too fancy with the pre-processor! 1046 */ 1047#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA 1048 s = "alpha"; 1049#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA 1050 s = "beta"; 1051#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA 1052 s = "candidate"; 1053#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL 1054 s = "final"; 1055#endif 1056 1057#define SET_SYS_FROM_STRING(key, value) \ 1058 v = value; \ 1059 if (v != NULL) \ 1060 PyDict_SetItemString(sysdict, key, v); \ 1061 Py_XDECREF(v) 1062 1063 SET_SYS_FROM_STRING("version_info", 1064 Py_BuildValue("iiiUi", PY_MAJOR_VERSION, 1065 PY_MINOR_VERSION, 1066 PY_MICRO_VERSION, s, 1067 PY_RELEASE_SERIAL)); 1068 SET_SYS_FROM_STRING("api_version", 1069 PyLong_FromLong(PYTHON_API_VERSION)); 1070 SET_SYS_FROM_STRING("copyright", 1071 PyUnicode_FromString(Py_GetCopyright())); 1072 SET_SYS_FROM_STRING("platform", 1073 PyUnicode_FromString(Py_GetPlatform())); 1074 SET_SYS_FROM_STRING("executable", 1075 PyUnicode_DecodeFSDefault( 1076 Py_GetProgramFullPath())); 1077 SET_SYS_FROM_STRING("prefix", 1078 PyUnicode_DecodeFSDefault(Py_GetPrefix())); 1079 SET_SYS_FROM_STRING("exec_prefix", 1080 PyUnicode_DecodeFSDefault(Py_GetExecPrefix())); 1081 SET_SYS_FROM_STRING("maxsize", 1082 PyLong_FromSsize_t(PY_SSIZE_T_MAX)); 1083 SET_SYS_FROM_STRING("float_info", 1084 PyFloat_GetInfo()); 1085 SET_SYS_FROM_STRING("maxunicode", 1086 PyLong_FromLong(PyUnicode_GetMax())); 1087 SET_SYS_FROM_STRING("builtin_module_names", 1088 list_builtin_module_names()); 1089 { 1090 /* Assumes that longs are at least 2 bytes long. 1091 Should be safe! */ 1092 unsigned long number = 1; 1093 char *value; 1094 1095 s = (char *) &number; 1096 if (s[0] == 0) 1097 value = "big"; 1098 else 1099 value = "little"; 1100 SET_SYS_FROM_STRING("byteorder", 1101 PyUnicode_FromString(value)); 1102 } 1103#ifdef MS_COREDLL 1104 SET_SYS_FROM_STRING("dllhandle", 1105 PyLong_FromVoidPtr(PyWin_DLLhModule)); 1106 SET_SYS_FROM_STRING("winver", 1107 PyUnicode_FromString(PyWin_DLLVersionString)); 1108#endif 1109#undef SET_SYS_FROM_STRING 1110 if (warnoptions == NULL) { 1111 warnoptions = PyList_New(0); 1112 } 1113 else { 1114 Py_INCREF(warnoptions); 1115 } 1116 if (warnoptions != NULL) { 1117 PyDict_SetItemString(sysdict, "warnoptions", warnoptions); 1118 } 1119 1120 if (PyErr_Occurred()) 1121 return NULL; 1122 return m; 1123} 1124 1125static PyObject * 1126makepathobject(const char *path, int delim) 1127{ 1128 int i, n; 1129 const char *p; 1130 PyObject *v, *w; 1131 1132 n = 1; 1133 p = path; 1134 while ((p = strchr(p, delim)) != NULL) { 1135 n++; 1136 p++; 1137 } 1138 v = PyList_New(n); 1139 if (v == NULL) 1140 return NULL; 1141 for (i = 0; ; i++) { 1142 p = strchr(path, delim); 1143 if (p == NULL) 1144 p = strchr(path, '\0'); /* End of string */ 1145 w = PyUnicode_DecodeFSDefaultAndSize(path, (Py_ssize_t) (p - path)); 1146 if (w == NULL) { 1147 Py_DECREF(v); 1148 return NULL; 1149 } 1150 PyList_SetItem(v, i, w); 1151 if (*p == '\0') 1152 break; 1153 path = p+1; 1154 } 1155 return v; 1156} 1157 1158void 1159PySys_SetPath(const char *path) 1160{ 1161 PyObject *v; 1162 if ((v = makepathobject(path, DELIM)) == NULL) 1163 Py_FatalError("can't create sys.path"); 1164 if (PySys_SetObject("path", v) != 0) 1165 Py_FatalError("can't assign sys.path"); 1166 Py_DECREF(v); 1167} 1168 1169static PyObject * 1170makeargvobject(int argc, char **argv) 1171{ 1172 PyObject *av; 1173 if (argc <= 0 || argv == NULL) { 1174 /* Ensure at least one (empty) argument is seen */ 1175 static char *empty_argv[1] = {""}; 1176 argv = empty_argv; 1177 argc = 1; 1178 } 1179 av = PyList_New(argc); 1180 if (av != NULL) { 1181 int i; 1182 for (i = 0; i < argc; i++) { 1183#ifdef __VMS 1184 PyObject *v; 1185 1186 /* argv[0] is the script pathname if known */ 1187 if (i == 0) { 1188 char* fn = decc$translate_vms(argv[0]); 1189 if ((fn == (char *)0) || fn == (char *)-1) 1190 v = PyUnicode_FromString(argv[0]); 1191 else 1192 v = PyUnicode_FromString( 1193 decc$translate_vms(argv[0])); 1194 } else 1195 v = PyUnicode_FromString(argv[i]); 1196#else 1197 PyObject *v = PyUnicode_FromString(argv[i]); 1198#endif 1199 if (v == NULL) { 1200 Py_DECREF(av); 1201 av = NULL; 1202 break; 1203 } 1204 PyList_SetItem(av, i, v); 1205 } 1206 } 1207 return av; 1208} 1209 1210void 1211PySys_SetArgv(int argc, char **argv) 1212{ 1213#if defined(HAVE_REALPATH) 1214 char fullpath[MAXPATHLEN]; 1215#elif defined(MS_WINDOWS) 1216 char fullpath[MAX_PATH]; 1217#endif 1218 PyObject *av = makeargvobject(argc, argv); 1219 PyObject *path = PySys_GetObject("path"); 1220 if (av == NULL) 1221 Py_FatalError("no mem for sys.argv"); 1222 if (PySys_SetObject("argv", av) != 0) 1223 Py_FatalError("can't assign sys.argv"); 1224 if (path != NULL) { 1225 char *argv0 = argv[0]; 1226 char *p = NULL; 1227 Py_ssize_t n = 0; 1228 PyObject *a; 1229#ifdef HAVE_READLINK 1230 char link[MAXPATHLEN+1]; 1231 char argv0copy[2*MAXPATHLEN+1]; 1232 int nr = 0; 1233 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) 1234 nr = readlink(argv0, link, MAXPATHLEN); 1235 if (nr > 0) { 1236 /* It's a symlink */ 1237 link[nr] = '\0'; 1238 if (link[0] == SEP) 1239 argv0 = link; /* Link to absolute path */ 1240 else if (strchr(link, SEP) == NULL) 1241 ; /* Link without path */ 1242 else { 1243 /* Must join(dirname(argv0), link) */ 1244 char *q = strrchr(argv0, SEP); 1245 if (q == NULL) 1246 argv0 = link; /* argv0 without path */ 1247 else { 1248 /* Must make a copy */ 1249 strcpy(argv0copy, argv0); 1250 q = strrchr(argv0copy, SEP); 1251 strcpy(q+1, link); 1252 argv0 = argv0copy; 1253 } 1254 } 1255 } 1256#endif /* HAVE_READLINK */ 1257#if SEP == '\\' /* Special case for MS filename syntax */ 1258 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { 1259 char *q; 1260#ifdef MS_WINDOWS 1261 char *ptemp; 1262 if (GetFullPathName(argv0, 1263 sizeof(fullpath), 1264 fullpath, 1265 &ptemp)) { 1266 argv0 = fullpath; 1267 } 1268#endif 1269 p = strrchr(argv0, SEP); 1270 /* Test for alternate separator */ 1271 q = strrchr(p ? p : argv0, '/'); 1272 if (q != NULL) 1273 p = q; 1274 if (p != NULL) { 1275 n = p + 1 - argv0; 1276 if (n > 1 && p[-1] != ':') 1277 n--; /* Drop trailing separator */ 1278 } 1279 } 1280#else /* All other filename syntaxes */ 1281 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { 1282#if defined(HAVE_REALPATH) 1283 if (realpath(argv0, fullpath)) { 1284 argv0 = fullpath; 1285 } 1286#endif 1287 p = strrchr(argv0, SEP); 1288 } 1289 if (p != NULL) { 1290 n = p + 1 - argv0; 1291#if SEP == '/' /* Special case for Unix filename syntax */ 1292 if (n > 1) 1293 n--; /* Drop trailing separator */ 1294#endif /* Unix */ 1295 } 1296#endif /* All others */ 1297 a = PyUnicode_FromStringAndSize(argv0, n); 1298 if (a == NULL) 1299 Py_FatalError("no mem for sys.path insertion"); 1300 if (PyList_Insert(path, 0, a) < 0) 1301 Py_FatalError("sys.path.insert(0) failed"); 1302 Py_DECREF(a); 1303 } 1304 Py_DECREF(av); 1305} 1306 1307 1308/* APIs to write to sys.stdout or sys.stderr using a printf-like interface. 1309 Adapted from code submitted by Just van Rossum. 1310 1311 PySys_WriteStdout(format, ...) 1312 PySys_WriteStderr(format, ...) 1313 1314 The first function writes to sys.stdout; the second to sys.stderr. When 1315 there is a problem, they write to the real (C level) stdout or stderr; 1316 no exceptions are raised. 1317 1318 Both take a printf-style format string as their first argument followed 1319 by a variable length argument list determined by the format string. 1320 1321 *** WARNING *** 1322 1323 The format should limit the total size of the formatted output string to 1324 1000 bytes. In particular, this means that no unrestricted "%s" formats 1325 should occur; these should be limited using "%.<N>s where <N> is a 1326 decimal number calculated so that <N> plus the maximum size of other 1327 formatted text does not exceed 1000 bytes. Also watch out for "%f", 1328 which can print hundreds of digits for very large numbers. 1329 1330 */ 1331 1332static void 1333mywrite(char *name, FILE *fp, const char *format, va_list va) 1334{ 1335 PyObject *file; 1336 PyObject *error_type, *error_value, *error_traceback; 1337 char buffer[1001]; 1338 int written; 1339 1340 PyErr_Fetch(&error_type, &error_value, &error_traceback); 1341 file = PySys_GetObject(name); 1342 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); 1343 if (PyFile_WriteString(buffer, file) != 0) { 1344 PyErr_Clear(); 1345 fputs(buffer, fp); 1346 } 1347 if (written < 0 || (size_t)written >= sizeof(buffer)) { 1348 const char *truncated = "... truncated"; 1349 if (PyFile_WriteString(truncated, file) != 0) { 1350 PyErr_Clear(); 1351 fputs(truncated, fp); 1352 } 1353 } 1354 PyErr_Restore(error_type, error_value, error_traceback); 1355} 1356 1357void 1358PySys_WriteStdout(const char *format, ...) 1359{ 1360 va_list va; 1361 1362 va_start(va, format); 1363 mywrite("stdout", stdout, format, va); 1364 va_end(va); 1365} 1366 1367void 1368PySys_WriteStderr(const char *format, ...) 1369{ 1370 va_list va; 1371 1372 va_start(va, format); 1373 mywrite("stderr", stderr, format, va); 1374 va_end(va); 1375} 1376