sysmodule.c revision 11ee080ea77c037c5a0bd8de972b040930a9b7e6
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 "pythread.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 44_Py_IDENTIFIER(_); 45_Py_IDENTIFIER(__sizeof__); 46_Py_IDENTIFIER(buffer); 47_Py_IDENTIFIER(builtins); 48_Py_IDENTIFIER(encoding); 49_Py_IDENTIFIER(path); 50_Py_IDENTIFIER(stdout); 51_Py_IDENTIFIER(stderr); 52_Py_IDENTIFIER(write); 53 54PyObject * 55_PySys_GetObjectId(_Py_Identifier *key) 56{ 57 PyThreadState *tstate = PyThreadState_GET(); 58 PyObject *sd = tstate->interp->sysdict; 59 if (sd == NULL) 60 return NULL; 61 return _PyDict_GetItemId(sd, key); 62} 63 64PyObject * 65PySys_GetObject(const char *name) 66{ 67 PyThreadState *tstate = PyThreadState_GET(); 68 PyObject *sd = tstate->interp->sysdict; 69 if (sd == NULL) 70 return NULL; 71 return PyDict_GetItemString(sd, name); 72} 73 74int 75_PySys_SetObjectId(_Py_Identifier *key, PyObject *v) 76{ 77 PyThreadState *tstate = PyThreadState_GET(); 78 PyObject *sd = tstate->interp->sysdict; 79 if (v == NULL) { 80 if (_PyDict_GetItemId(sd, key) == NULL) 81 return 0; 82 else 83 return _PyDict_DelItemId(sd, key); 84 } 85 else 86 return _PyDict_SetItemId(sd, key, v); 87} 88 89int 90PySys_SetObject(const char *name, PyObject *v) 91{ 92 PyThreadState *tstate = PyThreadState_GET(); 93 PyObject *sd = tstate->interp->sysdict; 94 if (v == NULL) { 95 if (PyDict_GetItemString(sd, name) == NULL) 96 return 0; 97 else 98 return PyDict_DelItemString(sd, name); 99 } 100 else 101 return PyDict_SetItemString(sd, name, v); 102} 103 104/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace' 105 error handler. If sys.stdout has a buffer attribute, use 106 sys.stdout.buffer.write(encoded), otherwise redecode the string and use 107 sys.stdout.write(redecoded). 108 109 Helper function for sys_displayhook(). */ 110static int 111sys_displayhook_unencodable(PyObject *outf, PyObject *o) 112{ 113 PyObject *stdout_encoding = NULL; 114 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result; 115 char *stdout_encoding_str; 116 int ret; 117 118 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding); 119 if (stdout_encoding == NULL) 120 goto error; 121 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding); 122 if (stdout_encoding_str == NULL) 123 goto error; 124 125 repr_str = PyObject_Repr(o); 126 if (repr_str == NULL) 127 goto error; 128 encoded = PyUnicode_AsEncodedString(repr_str, 129 stdout_encoding_str, 130 "backslashreplace"); 131 Py_DECREF(repr_str); 132 if (encoded == NULL) 133 goto error; 134 135 buffer = _PyObject_GetAttrId(outf, &PyId_buffer); 136 if (buffer) { 137 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded); 138 Py_DECREF(buffer); 139 Py_DECREF(encoded); 140 if (result == NULL) 141 goto error; 142 Py_DECREF(result); 143 } 144 else { 145 PyErr_Clear(); 146 escaped_str = PyUnicode_FromEncodedObject(encoded, 147 stdout_encoding_str, 148 "strict"); 149 Py_DECREF(encoded); 150 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) { 151 Py_DECREF(escaped_str); 152 goto error; 153 } 154 Py_DECREF(escaped_str); 155 } 156 ret = 0; 157 goto finally; 158 159error: 160 ret = -1; 161finally: 162 Py_XDECREF(stdout_encoding); 163 return ret; 164} 165 166static PyObject * 167sys_displayhook(PyObject *self, PyObject *o) 168{ 169 PyObject *outf; 170 PyInterpreterState *interp = PyThreadState_GET()->interp; 171 PyObject *modules = interp->modules; 172 PyObject *builtins; 173 static PyObject *newline = NULL; 174 int err; 175 176 builtins = _PyDict_GetItemId(modules, &PyId_builtins); 177 if (builtins == NULL) { 178 PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); 179 return NULL; 180 } 181 182 /* Print value except if None */ 183 /* After printing, also assign to '_' */ 184 /* Before, set '_' to None to avoid recursion */ 185 if (o == Py_None) { 186 Py_INCREF(Py_None); 187 return Py_None; 188 } 189 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0) 190 return NULL; 191 outf = _PySys_GetObjectId(&PyId_stdout); 192 if (outf == NULL || outf == Py_None) { 193 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); 194 return NULL; 195 } 196 if (PyFile_WriteObject(o, outf, 0) != 0) { 197 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) { 198 /* repr(o) is not encodable to sys.stdout.encoding with 199 * sys.stdout.errors error handler (which is probably 'strict') */ 200 PyErr_Clear(); 201 err = sys_displayhook_unencodable(outf, o); 202 if (err) 203 return NULL; 204 } 205 else { 206 return NULL; 207 } 208 } 209 if (newline == NULL) { 210 newline = PyUnicode_FromString("\n"); 211 if (newline == NULL) 212 return NULL; 213 } 214 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0) 215 return NULL; 216 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0) 217 return NULL; 218 Py_INCREF(Py_None); 219 return Py_None; 220} 221 222PyDoc_STRVAR(displayhook_doc, 223"displayhook(object) -> None\n" 224"\n" 225"Print an object to sys.stdout and also save it in builtins._\n" 226); 227 228static PyObject * 229sys_excepthook(PyObject* self, PyObject* args) 230{ 231 PyObject *exc, *value, *tb; 232 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) 233 return NULL; 234 PyErr_Display(exc, value, tb); 235 Py_INCREF(Py_None); 236 return Py_None; 237} 238 239PyDoc_STRVAR(excepthook_doc, 240"excepthook(exctype, value, traceback) -> None\n" 241"\n" 242"Handle an exception by displaying it with a traceback on sys.stderr.\n" 243); 244 245static PyObject * 246sys_exc_info(PyObject *self, PyObject *noargs) 247{ 248 PyThreadState *tstate; 249 tstate = PyThreadState_GET(); 250 return Py_BuildValue( 251 "(OOO)", 252 tstate->exc_type != NULL ? tstate->exc_type : Py_None, 253 tstate->exc_value != NULL ? tstate->exc_value : Py_None, 254 tstate->exc_traceback != NULL ? 255 tstate->exc_traceback : Py_None); 256} 257 258PyDoc_STRVAR(exc_info_doc, 259"exc_info() -> (type, value, traceback)\n\ 260\n\ 261Return information about the most recent exception caught by an except\n\ 262clause in the current stack frame or in an older stack frame." 263); 264 265static PyObject * 266sys_exit(PyObject *self, PyObject *args) 267{ 268 PyObject *exit_code = 0; 269 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) 270 return NULL; 271 /* Raise SystemExit so callers may catch it or clean up. */ 272 PyErr_SetObject(PyExc_SystemExit, exit_code); 273 return NULL; 274} 275 276PyDoc_STRVAR(exit_doc, 277"exit([status])\n\ 278\n\ 279Exit the interpreter by raising SystemExit(status).\n\ 280If the status is omitted or None, it defaults to zero (i.e., success).\n\ 281If the status is an integer, it will be used as the system exit status.\n\ 282If it is another kind of object, it will be printed and the system\n\ 283exit status will be one (i.e., failure)." 284); 285 286 287static PyObject * 288sys_getdefaultencoding(PyObject *self) 289{ 290 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); 291} 292 293PyDoc_STRVAR(getdefaultencoding_doc, 294"getdefaultencoding() -> string\n\ 295\n\ 296Return the current default string encoding used by the Unicode \n\ 297implementation." 298); 299 300static PyObject * 301sys_getfilesystemencoding(PyObject *self) 302{ 303 if (Py_FileSystemDefaultEncoding) 304 return PyUnicode_FromString(Py_FileSystemDefaultEncoding); 305 PyErr_SetString(PyExc_RuntimeError, 306 "filesystem encoding is not initialized"); 307 return NULL; 308} 309 310PyDoc_STRVAR(getfilesystemencoding_doc, 311"getfilesystemencoding() -> string\n\ 312\n\ 313Return the encoding used to convert Unicode filenames in\n\ 314operating system filenames." 315); 316 317static PyObject * 318sys_intern(PyObject *self, PyObject *args) 319{ 320 PyObject *s; 321 if (!PyArg_ParseTuple(args, "U:intern", &s)) 322 return NULL; 323 if (PyUnicode_CheckExact(s)) { 324 Py_INCREF(s); 325 PyUnicode_InternInPlace(&s); 326 return s; 327 } 328 else { 329 PyErr_Format(PyExc_TypeError, 330 "can't intern %.400s", s->ob_type->tp_name); 331 return NULL; 332 } 333} 334 335PyDoc_STRVAR(intern_doc, 336"intern(string) -> string\n\ 337\n\ 338``Intern'' the given string. This enters the string in the (global)\n\ 339table of interned strings whose purpose is to speed up dictionary lookups.\n\ 340Return the string itself or the previously interned string object with the\n\ 341same value."); 342 343 344/* 345 * Cached interned string objects used for calling the profile and 346 * trace functions. Initialized by trace_init(). 347 */ 348static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL}; 349 350static int 351trace_init(void) 352{ 353 static char *whatnames[7] = {"call", "exception", "line", "return", 354 "c_call", "c_exception", "c_return"}; 355 PyObject *name; 356 int i; 357 for (i = 0; i < 7; ++i) { 358 if (whatstrings[i] == NULL) { 359 name = PyUnicode_InternFromString(whatnames[i]); 360 if (name == NULL) 361 return -1; 362 whatstrings[i] = name; 363 } 364 } 365 return 0; 366} 367 368 369static PyObject * 370call_trampoline(PyObject* callback, 371 PyFrameObject *frame, int what, PyObject *arg) 372{ 373 PyObject *args; 374 PyObject *whatstr; 375 PyObject *result; 376 377 args = PyTuple_New(3); 378 if (args == NULL) 379 return NULL; 380 if (PyFrame_FastToLocalsWithError(frame) < 0) 381 return NULL; 382 383 Py_INCREF(frame); 384 whatstr = whatstrings[what]; 385 Py_INCREF(whatstr); 386 if (arg == NULL) 387 arg = Py_None; 388 Py_INCREF(arg); 389 PyTuple_SET_ITEM(args, 0, (PyObject *)frame); 390 PyTuple_SET_ITEM(args, 1, whatstr); 391 PyTuple_SET_ITEM(args, 2, arg); 392 393 /* call the Python-level function */ 394 result = PyEval_CallObject(callback, args); 395 PyFrame_LocalsToFast(frame, 1); 396 if (result == NULL) 397 PyTraceBack_Here(frame); 398 399 /* cleanup */ 400 Py_DECREF(args); 401 return result; 402} 403 404static int 405profile_trampoline(PyObject *self, PyFrameObject *frame, 406 int what, PyObject *arg) 407{ 408 PyObject *result; 409 410 if (arg == NULL) 411 arg = Py_None; 412 result = call_trampoline(self, frame, what, arg); 413 if (result == NULL) { 414 PyEval_SetProfile(NULL, NULL); 415 return -1; 416 } 417 Py_DECREF(result); 418 return 0; 419} 420 421static int 422trace_trampoline(PyObject *self, PyFrameObject *frame, 423 int what, PyObject *arg) 424{ 425 PyObject *callback; 426 PyObject *result; 427 428 if (what == PyTrace_CALL) 429 callback = self; 430 else 431 callback = frame->f_trace; 432 if (callback == NULL) 433 return 0; 434 result = call_trampoline(callback, frame, what, arg); 435 if (result == NULL) { 436 PyEval_SetTrace(NULL, NULL); 437 Py_XDECREF(frame->f_trace); 438 frame->f_trace = NULL; 439 return -1; 440 } 441 if (result != Py_None) { 442 PyObject *temp = frame->f_trace; 443 frame->f_trace = NULL; 444 Py_XDECREF(temp); 445 frame->f_trace = result; 446 } 447 else { 448 Py_DECREF(result); 449 } 450 return 0; 451} 452 453static PyObject * 454sys_settrace(PyObject *self, PyObject *args) 455{ 456 if (trace_init() == -1) 457 return NULL; 458 if (args == Py_None) 459 PyEval_SetTrace(NULL, NULL); 460 else 461 PyEval_SetTrace(trace_trampoline, args); 462 Py_INCREF(Py_None); 463 return Py_None; 464} 465 466PyDoc_STRVAR(settrace_doc, 467"settrace(function)\n\ 468\n\ 469Set the global debug tracing function. It will be called on each\n\ 470function call. See the debugger chapter in the library manual." 471); 472 473static PyObject * 474sys_gettrace(PyObject *self, PyObject *args) 475{ 476 PyThreadState *tstate = PyThreadState_GET(); 477 PyObject *temp = tstate->c_traceobj; 478 479 if (temp == NULL) 480 temp = Py_None; 481 Py_INCREF(temp); 482 return temp; 483} 484 485PyDoc_STRVAR(gettrace_doc, 486"gettrace()\n\ 487\n\ 488Return the global debug tracing function set with sys.settrace.\n\ 489See the debugger chapter in the library manual." 490); 491 492static PyObject * 493sys_setprofile(PyObject *self, PyObject *args) 494{ 495 if (trace_init() == -1) 496 return NULL; 497 if (args == Py_None) 498 PyEval_SetProfile(NULL, NULL); 499 else 500 PyEval_SetProfile(profile_trampoline, args); 501 Py_INCREF(Py_None); 502 return Py_None; 503} 504 505PyDoc_STRVAR(setprofile_doc, 506"setprofile(function)\n\ 507\n\ 508Set the profiling function. It will be called on each function call\n\ 509and return. See the profiler chapter in the library manual." 510); 511 512static PyObject * 513sys_getprofile(PyObject *self, PyObject *args) 514{ 515 PyThreadState *tstate = PyThreadState_GET(); 516 PyObject *temp = tstate->c_profileobj; 517 518 if (temp == NULL) 519 temp = Py_None; 520 Py_INCREF(temp); 521 return temp; 522} 523 524PyDoc_STRVAR(getprofile_doc, 525"getprofile()\n\ 526\n\ 527Return the profiling function set with sys.setprofile.\n\ 528See the profiler chapter in the library manual." 529); 530 531static int _check_interval = 100; 532 533static PyObject * 534sys_setcheckinterval(PyObject *self, PyObject *args) 535{ 536 if (PyErr_WarnEx(PyExc_DeprecationWarning, 537 "sys.getcheckinterval() and sys.setcheckinterval() " 538 "are deprecated. Use sys.setswitchinterval() " 539 "instead.", 1) < 0) 540 return NULL; 541 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval)) 542 return NULL; 543 Py_INCREF(Py_None); 544 return Py_None; 545} 546 547PyDoc_STRVAR(setcheckinterval_doc, 548"setcheckinterval(n)\n\ 549\n\ 550Tell the Python interpreter to check for asynchronous events every\n\ 551n instructions. This also affects how often thread switches occur." 552); 553 554static PyObject * 555sys_getcheckinterval(PyObject *self, PyObject *args) 556{ 557 if (PyErr_WarnEx(PyExc_DeprecationWarning, 558 "sys.getcheckinterval() and sys.setcheckinterval() " 559 "are deprecated. Use sys.getswitchinterval() " 560 "instead.", 1) < 0) 561 return NULL; 562 return PyLong_FromLong(_check_interval); 563} 564 565PyDoc_STRVAR(getcheckinterval_doc, 566"getcheckinterval() -> current check interval; see setcheckinterval()." 567); 568 569#ifdef WITH_THREAD 570static PyObject * 571sys_setswitchinterval(PyObject *self, PyObject *args) 572{ 573 double d; 574 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d)) 575 return NULL; 576 if (d <= 0.0) { 577 PyErr_SetString(PyExc_ValueError, 578 "switch interval must be strictly positive"); 579 return NULL; 580 } 581 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d)); 582 Py_INCREF(Py_None); 583 return Py_None; 584} 585 586PyDoc_STRVAR(setswitchinterval_doc, 587"setswitchinterval(n)\n\ 588\n\ 589Set the ideal thread switching delay inside the Python interpreter\n\ 590The actual frequency of switching threads can be lower if the\n\ 591interpreter executes long sequences of uninterruptible code\n\ 592(this is implementation-specific and workload-dependent).\n\ 593\n\ 594The parameter must represent the desired switching delay in seconds\n\ 595A typical value is 0.005 (5 milliseconds)." 596); 597 598static PyObject * 599sys_getswitchinterval(PyObject *self, PyObject *args) 600{ 601 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval()); 602} 603 604PyDoc_STRVAR(getswitchinterval_doc, 605"getswitchinterval() -> current thread switch interval; see setswitchinterval()." 606); 607 608#endif /* WITH_THREAD */ 609 610#ifdef WITH_TSC 611static PyObject * 612sys_settscdump(PyObject *self, PyObject *args) 613{ 614 int bool; 615 PyThreadState *tstate = PyThreadState_Get(); 616 617 if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) 618 return NULL; 619 if (bool) 620 tstate->interp->tscdump = 1; 621 else 622 tstate->interp->tscdump = 0; 623 Py_INCREF(Py_None); 624 return Py_None; 625 626} 627 628PyDoc_STRVAR(settscdump_doc, 629"settscdump(bool)\n\ 630\n\ 631If true, tell the Python interpreter to dump VM measurements to\n\ 632stderr. If false, turn off dump. The measurements are based on the\n\ 633processor's time-stamp counter." 634); 635#endif /* TSC */ 636 637static PyObject * 638sys_setrecursionlimit(PyObject *self, PyObject *args) 639{ 640 int new_limit; 641 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) 642 return NULL; 643 if (new_limit <= 0) { 644 PyErr_SetString(PyExc_ValueError, 645 "recursion limit must be positive"); 646 return NULL; 647 } 648 Py_SetRecursionLimit(new_limit); 649 Py_INCREF(Py_None); 650 return Py_None; 651} 652 653static PyTypeObject Hash_InfoType; 654 655PyDoc_STRVAR(hash_info_doc, 656"hash_info\n\ 657\n\ 658A struct sequence providing parameters used for computing\n\ 659hashes. The attributes are read only."); 660 661static PyStructSequence_Field hash_info_fields[] = { 662 {"width", "width of the type used for hashing, in bits"}, 663 {"modulus", "prime number giving the modulus on which the hash " 664 "function is based"}, 665 {"inf", "value to be used for hash of a positive infinity"}, 666 {"nan", "value to be used for hash of a nan"}, 667 {"imag", "multiplier used for the imaginary part of a complex number"}, 668 {"algorithm", "name of the algorithm for hashing of str, bytes and " 669 "memoryviews"}, 670 {"hash_bits", "internal output size of hash algorithm"}, 671 {"seed_bits", "seed size of hash algorithm"}, 672 {"cutoff", "small string optimization cutoff"}, 673 {NULL, NULL} 674}; 675 676static PyStructSequence_Desc hash_info_desc = { 677 "sys.hash_info", 678 hash_info_doc, 679 hash_info_fields, 680 9, 681}; 682 683static PyObject * 684get_hash_info(void) 685{ 686 PyObject *hash_info; 687 int field = 0; 688 PyHash_FuncDef *hashfunc; 689 hash_info = PyStructSequence_New(&Hash_InfoType); 690 if (hash_info == NULL) 691 return NULL; 692 hashfunc = PyHash_GetFuncDef(); 693 PyStructSequence_SET_ITEM(hash_info, field++, 694 PyLong_FromLong(8*sizeof(Py_hash_t))); 695 PyStructSequence_SET_ITEM(hash_info, field++, 696 PyLong_FromSsize_t(_PyHASH_MODULUS)); 697 PyStructSequence_SET_ITEM(hash_info, field++, 698 PyLong_FromLong(_PyHASH_INF)); 699 PyStructSequence_SET_ITEM(hash_info, field++, 700 PyLong_FromLong(_PyHASH_NAN)); 701 PyStructSequence_SET_ITEM(hash_info, field++, 702 PyLong_FromLong(_PyHASH_IMAG)); 703 PyStructSequence_SET_ITEM(hash_info, field++, 704 PyUnicode_FromString(hashfunc->name)); 705 PyStructSequence_SET_ITEM(hash_info, field++, 706 PyLong_FromLong(hashfunc->hash_bits)); 707 PyStructSequence_SET_ITEM(hash_info, field++, 708 PyLong_FromLong(hashfunc->seed_bits)); 709 PyStructSequence_SET_ITEM(hash_info, field++, 710 PyLong_FromLong(Py_HASH_CUTOFF)); 711 if (PyErr_Occurred()) { 712 Py_CLEAR(hash_info); 713 return NULL; 714 } 715 return hash_info; 716} 717 718 719PyDoc_STRVAR(setrecursionlimit_doc, 720"setrecursionlimit(n)\n\ 721\n\ 722Set the maximum depth of the Python interpreter stack to n. This\n\ 723limit prevents infinite recursion from causing an overflow of the C\n\ 724stack and crashing Python. The highest possible limit is platform-\n\ 725dependent." 726); 727 728static PyObject * 729sys_getrecursionlimit(PyObject *self) 730{ 731 return PyLong_FromLong(Py_GetRecursionLimit()); 732} 733 734PyDoc_STRVAR(getrecursionlimit_doc, 735"getrecursionlimit()\n\ 736\n\ 737Return the current value of the recursion limit, the maximum depth\n\ 738of the Python interpreter stack. This limit prevents infinite\n\ 739recursion from causing an overflow of the C stack and crashing Python." 740); 741 742#ifdef MS_WINDOWS 743PyDoc_STRVAR(getwindowsversion_doc, 744"getwindowsversion()\n\ 745\n\ 746Return information about the running version of Windows as a named tuple.\n\ 747The members are named: major, minor, build, platform, service_pack,\n\ 748service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\ 749backward compatibility, only the first 5 items are available by indexing.\n\ 750All elements are numbers, except service_pack which is a string. Platform\n\ 751may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\ 7523 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\ 753controller, 3 for a server." 754); 755 756static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0}; 757 758static PyStructSequence_Field windows_version_fields[] = { 759 {"major", "Major version number"}, 760 {"minor", "Minor version number"}, 761 {"build", "Build number"}, 762 {"platform", "Operating system platform"}, 763 {"service_pack", "Latest Service Pack installed on the system"}, 764 {"service_pack_major", "Service Pack major version number"}, 765 {"service_pack_minor", "Service Pack minor version number"}, 766 {"suite_mask", "Bit mask identifying available product suites"}, 767 {"product_type", "System product type"}, 768 {0} 769}; 770 771static PyStructSequence_Desc windows_version_desc = { 772 "sys.getwindowsversion", /* name */ 773 getwindowsversion_doc, /* doc */ 774 windows_version_fields, /* fields */ 775 5 /* For backward compatibility, 776 only the first 5 items are accessible 777 via indexing, the rest are name only */ 778}; 779 780static PyObject * 781sys_getwindowsversion(PyObject *self) 782{ 783 PyObject *version; 784 int pos = 0; 785 OSVERSIONINFOEX ver; 786 ver.dwOSVersionInfoSize = sizeof(ver); 787 if (!GetVersionEx((OSVERSIONINFO*) &ver)) 788 return PyErr_SetFromWindowsErr(0); 789 790 version = PyStructSequence_New(&WindowsVersionType); 791 if (version == NULL) 792 return NULL; 793 794 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); 795 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); 796 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); 797 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); 798 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion)); 799 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); 800 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); 801 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); 802 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); 803 804 return version; 805} 806 807#endif /* MS_WINDOWS */ 808 809#ifdef HAVE_DLOPEN 810static PyObject * 811sys_setdlopenflags(PyObject *self, PyObject *args) 812{ 813 int new_val; 814 PyThreadState *tstate = PyThreadState_GET(); 815 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) 816 return NULL; 817 if (!tstate) 818 return NULL; 819 tstate->interp->dlopenflags = new_val; 820 Py_INCREF(Py_None); 821 return Py_None; 822} 823 824PyDoc_STRVAR(setdlopenflags_doc, 825"setdlopenflags(n) -> None\n\ 826\n\ 827Set the flags used by the interpreter for dlopen calls, such as when the\n\ 828interpreter loads extension modules. Among other things, this will enable\n\ 829a lazy resolving of symbols when importing a module, if called as\n\ 830sys.setdlopenflags(0). To share symbols across extension modules, call as\n\ 831sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\ 832can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY)."); 833 834static PyObject * 835sys_getdlopenflags(PyObject *self, PyObject *args) 836{ 837 PyThreadState *tstate = PyThreadState_GET(); 838 if (!tstate) 839 return NULL; 840 return PyLong_FromLong(tstate->interp->dlopenflags); 841} 842 843PyDoc_STRVAR(getdlopenflags_doc, 844"getdlopenflags() -> int\n\ 845\n\ 846Return the current value of the flags that are used for dlopen calls.\n\ 847The flag constants are defined in the os module."); 848 849#endif /* HAVE_DLOPEN */ 850 851#ifdef USE_MALLOPT 852/* Link with -lmalloc (or -lmpc) on an SGI */ 853#include <malloc.h> 854 855static PyObject * 856sys_mdebug(PyObject *self, PyObject *args) 857{ 858 int flag; 859 if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) 860 return NULL; 861 mallopt(M_DEBUG, flag); 862 Py_INCREF(Py_None); 863 return Py_None; 864} 865#endif /* USE_MALLOPT */ 866 867static PyObject * 868sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) 869{ 870 PyObject *res = NULL; 871 static PyObject *gc_head_size = NULL; 872 static char *kwlist[] = {"object", "default", 0}; 873 PyObject *o, *dflt = NULL; 874 PyObject *method; 875 876 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", 877 kwlist, &o, &dflt)) 878 return NULL; 879 880 /* Initialize static variable for GC head size */ 881 if (gc_head_size == NULL) { 882 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); 883 if (gc_head_size == NULL) 884 return NULL; 885 } 886 887 /* Make sure the type is initialized. float gets initialized late */ 888 if (PyType_Ready(Py_TYPE(o)) < 0) 889 return NULL; 890 891 method = _PyObject_LookupSpecial(o, &PyId___sizeof__); 892 if (method == NULL) { 893 if (!PyErr_Occurred()) 894 PyErr_Format(PyExc_TypeError, 895 "Type %.100s doesn't define __sizeof__", 896 Py_TYPE(o)->tp_name); 897 } 898 else { 899 res = PyObject_CallFunctionObjArgs(method, NULL); 900 Py_DECREF(method); 901 } 902 903 /* Has a default value been given */ 904 if ((res == NULL) && (dflt != NULL) && 905 PyErr_ExceptionMatches(PyExc_TypeError)) 906 { 907 PyErr_Clear(); 908 Py_INCREF(dflt); 909 return dflt; 910 } 911 else if (res == NULL) 912 return res; 913 914 /* add gc_head size */ 915 if (PyObject_IS_GC(o)) { 916 PyObject *tmp = res; 917 res = PyNumber_Add(tmp, gc_head_size); 918 Py_DECREF(tmp); 919 } 920 return res; 921} 922 923PyDoc_STRVAR(getsizeof_doc, 924"getsizeof(object, default) -> int\n\ 925\n\ 926Return the size of object in bytes."); 927 928static PyObject * 929sys_getrefcount(PyObject *self, PyObject *arg) 930{ 931 return PyLong_FromSsize_t(arg->ob_refcnt); 932} 933 934#ifdef Py_REF_DEBUG 935static PyObject * 936sys_gettotalrefcount(PyObject *self) 937{ 938 return PyLong_FromSsize_t(_Py_GetRefTotal()); 939} 940#endif /* Py_REF_DEBUG */ 941 942PyDoc_STRVAR(getrefcount_doc, 943"getrefcount(object) -> integer\n\ 944\n\ 945Return the reference count of object. The count returned is generally\n\ 946one higher than you might expect, because it includes the (temporary)\n\ 947reference as an argument to getrefcount()." 948); 949 950static PyObject * 951sys_getallocatedblocks(PyObject *self) 952{ 953 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks()); 954} 955 956PyDoc_STRVAR(getallocatedblocks_doc, 957"getallocatedblocks() -> integer\n\ 958\n\ 959Return the number of memory blocks currently allocated, regardless of their\n\ 960size." 961); 962 963#ifdef COUNT_ALLOCS 964static PyObject * 965sys_getcounts(PyObject *self) 966{ 967 extern PyObject *get_counts(void); 968 969 return get_counts(); 970} 971#endif 972 973PyDoc_STRVAR(getframe_doc, 974"_getframe([depth]) -> frameobject\n\ 975\n\ 976Return a frame object from the call stack. If optional integer depth is\n\ 977given, return the frame object that many calls below the top of the stack.\n\ 978If that is deeper than the call stack, ValueError is raised. The default\n\ 979for depth is zero, returning the frame at the top of the call stack.\n\ 980\n\ 981This function should be used for internal and specialized\n\ 982purposes only." 983); 984 985static PyObject * 986sys_getframe(PyObject *self, PyObject *args) 987{ 988 PyFrameObject *f = PyThreadState_GET()->frame; 989 int depth = -1; 990 991 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) 992 return NULL; 993 994 while (depth > 0 && f != NULL) { 995 f = f->f_back; 996 --depth; 997 } 998 if (f == NULL) { 999 PyErr_SetString(PyExc_ValueError, 1000 "call stack is not deep enough"); 1001 return NULL; 1002 } 1003 Py_INCREF(f); 1004 return (PyObject*)f; 1005} 1006 1007PyDoc_STRVAR(current_frames_doc, 1008"_current_frames() -> dictionary\n\ 1009\n\ 1010Return a dictionary mapping each current thread T's thread id to T's\n\ 1011current stack frame.\n\ 1012\n\ 1013This function should be used for specialized purposes only." 1014); 1015 1016static PyObject * 1017sys_current_frames(PyObject *self, PyObject *noargs) 1018{ 1019 return _PyThread_CurrentFrames(); 1020} 1021 1022PyDoc_STRVAR(call_tracing_doc, 1023"call_tracing(func, args) -> object\n\ 1024\n\ 1025Call func(*args), while tracing is enabled. The tracing state is\n\ 1026saved, and restored afterwards. This is intended to be called from\n\ 1027a debugger from a checkpoint, to recursively debug some other code." 1028); 1029 1030static PyObject * 1031sys_call_tracing(PyObject *self, PyObject *args) 1032{ 1033 PyObject *func, *funcargs; 1034 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) 1035 return NULL; 1036 return _PyEval_CallTracing(func, funcargs); 1037} 1038 1039PyDoc_STRVAR(callstats_doc, 1040"callstats() -> tuple of integers\n\ 1041\n\ 1042Return a tuple of function call statistics, if CALL_PROFILE was defined\n\ 1043when Python was built. Otherwise, return None.\n\ 1044\n\ 1045When enabled, this function returns detailed, implementation-specific\n\ 1046details about the number of function calls executed. The return value is\n\ 1047a 11-tuple where the entries in the tuple are counts of:\n\ 10480. all function calls\n\ 10491. calls to PyFunction_Type objects\n\ 10502. PyFunction calls that do not create an argument tuple\n\ 10513. PyFunction calls that do not create an argument tuple\n\ 1052 and bypass PyEval_EvalCodeEx()\n\ 10534. PyMethod calls\n\ 10545. PyMethod calls on bound methods\n\ 10556. PyType calls\n\ 10567. PyCFunction calls\n\ 10578. generator calls\n\ 10589. All other calls\n\ 105910. Number of stack pops performed by call_function()" 1060); 1061 1062#ifdef __cplusplus 1063extern "C" { 1064#endif 1065 1066static PyObject * 1067sys_debugmallocstats(PyObject *self, PyObject *args) 1068{ 1069#ifdef WITH_PYMALLOC 1070 _PyObject_DebugMallocStats(stderr); 1071 fputc('\n', stderr); 1072#endif 1073 _PyObject_DebugTypeStats(stderr); 1074 1075 Py_RETURN_NONE; 1076} 1077PyDoc_STRVAR(debugmallocstats_doc, 1078"_debugmallocstats()\n\ 1079\n\ 1080Print summary info to stderr about the state of\n\ 1081pymalloc's structures.\n\ 1082\n\ 1083In Py_DEBUG mode, also perform some expensive internal consistency\n\ 1084checks.\n\ 1085"); 1086 1087#ifdef Py_TRACE_REFS 1088/* Defined in objects.c because it uses static globals if that file */ 1089extern PyObject *_Py_GetObjects(PyObject *, PyObject *); 1090#endif 1091 1092#ifdef DYNAMIC_EXECUTION_PROFILE 1093/* Defined in ceval.c because it uses static globals if that file */ 1094extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *); 1095#endif 1096 1097#ifdef __cplusplus 1098} 1099#endif 1100 1101static PyObject * 1102sys_clear_type_cache(PyObject* self, PyObject* args) 1103{ 1104 PyType_ClearCache(); 1105 Py_RETURN_NONE; 1106} 1107 1108PyDoc_STRVAR(sys_clear_type_cache__doc__, 1109"_clear_type_cache() -> None\n\ 1110Clear the internal type lookup cache."); 1111 1112 1113static PyMethodDef sys_methods[] = { 1114 /* Might as well keep this in alphabetic order */ 1115 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, 1116 callstats_doc}, 1117 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, 1118 sys_clear_type_cache__doc__}, 1119 {"_current_frames", sys_current_frames, METH_NOARGS, 1120 current_frames_doc}, 1121 {"displayhook", sys_displayhook, METH_O, displayhook_doc}, 1122 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, 1123 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, 1124 {"exit", sys_exit, METH_VARARGS, exit_doc}, 1125 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, 1126 METH_NOARGS, getdefaultencoding_doc}, 1127#ifdef HAVE_DLOPEN 1128 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, 1129 getdlopenflags_doc}, 1130#endif 1131 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS, 1132 getallocatedblocks_doc}, 1133#ifdef COUNT_ALLOCS 1134 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, 1135#endif 1136#ifdef DYNAMIC_EXECUTION_PROFILE 1137 {"getdxp", _Py_GetDXProfile, METH_VARARGS}, 1138#endif 1139 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, 1140 METH_NOARGS, getfilesystemencoding_doc}, 1141#ifdef Py_TRACE_REFS 1142 {"getobjects", _Py_GetObjects, METH_VARARGS}, 1143#endif 1144#ifdef Py_REF_DEBUG 1145 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, 1146#endif 1147 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, 1148 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, 1149 getrecursionlimit_doc}, 1150 {"getsizeof", (PyCFunction)sys_getsizeof, 1151 METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, 1152 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, 1153#ifdef MS_WINDOWS 1154 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, 1155 getwindowsversion_doc}, 1156#endif /* MS_WINDOWS */ 1157 {"intern", sys_intern, METH_VARARGS, intern_doc}, 1158#ifdef USE_MALLOPT 1159 {"mdebug", sys_mdebug, METH_VARARGS}, 1160#endif 1161 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, 1162 setcheckinterval_doc}, 1163 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, 1164 getcheckinterval_doc}, 1165#ifdef WITH_THREAD 1166 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS, 1167 setswitchinterval_doc}, 1168 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS, 1169 getswitchinterval_doc}, 1170#endif 1171#ifdef HAVE_DLOPEN 1172 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, 1173 setdlopenflags_doc}, 1174#endif 1175 {"setprofile", sys_setprofile, METH_O, setprofile_doc}, 1176 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, 1177 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, 1178 setrecursionlimit_doc}, 1179#ifdef WITH_TSC 1180 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, 1181#endif 1182 {"settrace", sys_settrace, METH_O, settrace_doc}, 1183 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, 1184 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, 1185 {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS, 1186 debugmallocstats_doc}, 1187 {NULL, NULL} /* sentinel */ 1188}; 1189 1190static PyObject * 1191list_builtin_module_names(void) 1192{ 1193 PyObject *list = PyList_New(0); 1194 int i; 1195 if (list == NULL) 1196 return NULL; 1197 for (i = 0; PyImport_Inittab[i].name != NULL; i++) { 1198 PyObject *name = PyUnicode_FromString( 1199 PyImport_Inittab[i].name); 1200 if (name == NULL) 1201 break; 1202 PyList_Append(list, name); 1203 Py_DECREF(name); 1204 } 1205 if (PyList_Sort(list) != 0) { 1206 Py_DECREF(list); 1207 list = NULL; 1208 } 1209 if (list) { 1210 PyObject *v = PyList_AsTuple(list); 1211 Py_DECREF(list); 1212 list = v; 1213 } 1214 return list; 1215} 1216 1217static PyObject *warnoptions = NULL; 1218 1219void 1220PySys_ResetWarnOptions(void) 1221{ 1222 if (warnoptions == NULL || !PyList_Check(warnoptions)) 1223 return; 1224 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); 1225} 1226 1227void 1228PySys_AddWarnOptionUnicode(PyObject *unicode) 1229{ 1230 if (warnoptions == NULL || !PyList_Check(warnoptions)) { 1231 Py_XDECREF(warnoptions); 1232 warnoptions = PyList_New(0); 1233 if (warnoptions == NULL) 1234 return; 1235 } 1236 PyList_Append(warnoptions, unicode); 1237} 1238 1239void 1240PySys_AddWarnOption(const wchar_t *s) 1241{ 1242 PyObject *unicode; 1243 unicode = PyUnicode_FromWideChar(s, -1); 1244 if (unicode == NULL) 1245 return; 1246 PySys_AddWarnOptionUnicode(unicode); 1247 Py_DECREF(unicode); 1248} 1249 1250int 1251PySys_HasWarnOptions(void) 1252{ 1253 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0; 1254} 1255 1256static PyObject *xoptions = NULL; 1257 1258static PyObject * 1259get_xoptions(void) 1260{ 1261 if (xoptions == NULL || !PyDict_Check(xoptions)) { 1262 Py_XDECREF(xoptions); 1263 xoptions = PyDict_New(); 1264 } 1265 return xoptions; 1266} 1267 1268void 1269PySys_AddXOption(const wchar_t *s) 1270{ 1271 PyObject *opts; 1272 PyObject *name = NULL, *value = NULL; 1273 const wchar_t *name_end; 1274 1275 opts = get_xoptions(); 1276 if (opts == NULL) 1277 goto error; 1278 1279 name_end = wcschr(s, L'='); 1280 if (!name_end) { 1281 name = PyUnicode_FromWideChar(s, -1); 1282 value = Py_True; 1283 Py_INCREF(value); 1284 } 1285 else { 1286 name = PyUnicode_FromWideChar(s, name_end - s); 1287 value = PyUnicode_FromWideChar(name_end + 1, -1); 1288 } 1289 if (name == NULL || value == NULL) 1290 goto error; 1291 PyDict_SetItem(opts, name, value); 1292 Py_DECREF(name); 1293 Py_DECREF(value); 1294 return; 1295 1296error: 1297 Py_XDECREF(name); 1298 Py_XDECREF(value); 1299 /* No return value, therefore clear error state if possible */ 1300 if (_Py_atomic_load_relaxed(&_PyThreadState_Current)) 1301 PyErr_Clear(); 1302} 1303 1304PyObject * 1305PySys_GetXOptions(void) 1306{ 1307 return get_xoptions(); 1308} 1309 1310/* XXX This doc string is too long to be a single string literal in VC++ 5.0. 1311 Two literals concatenated works just fine. If you have a K&R compiler 1312 or other abomination that however *does* understand longer strings, 1313 get rid of the !!! comment in the middle and the quotes that surround it. */ 1314PyDoc_VAR(sys_doc) = 1315PyDoc_STR( 1316"This module provides access to some objects used or maintained by the\n\ 1317interpreter and to functions that interact strongly with the interpreter.\n\ 1318\n\ 1319Dynamic objects:\n\ 1320\n\ 1321argv -- command line arguments; argv[0] is the script pathname if known\n\ 1322path -- module search path; path[0] is the script directory, else ''\n\ 1323modules -- dictionary of loaded modules\n\ 1324\n\ 1325displayhook -- called to show results in an interactive session\n\ 1326excepthook -- called to handle any uncaught exception other than SystemExit\n\ 1327 To customize printing in an interactive session or to install a custom\n\ 1328 top-level exception handler, assign other functions to replace these.\n\ 1329\n\ 1330stdin -- standard input file object; used by input()\n\ 1331stdout -- standard output file object; used by print()\n\ 1332stderr -- standard error object; used for error messages\n\ 1333 By assigning other file objects (or objects that behave like files)\n\ 1334 to these, it is possible to redirect all of the interpreter's I/O.\n\ 1335\n\ 1336last_type -- type of last uncaught exception\n\ 1337last_value -- value of last uncaught exception\n\ 1338last_traceback -- traceback of last uncaught exception\n\ 1339 These three are only available in an interactive session after a\n\ 1340 traceback has been printed.\n\ 1341" 1342) 1343/* concatenating string here */ 1344PyDoc_STR( 1345"\n\ 1346Static objects:\n\ 1347\n\ 1348builtin_module_names -- tuple of module names built into this interpreter\n\ 1349copyright -- copyright notice pertaining to this interpreter\n\ 1350exec_prefix -- prefix used to find the machine-specific Python library\n\ 1351executable -- absolute path of the executable binary of the Python interpreter\n\ 1352float_info -- a struct sequence with information about the float implementation.\n\ 1353float_repr_style -- string indicating the style of repr() output for floats\n\ 1354hash_info -- a struct sequence with information about the hash algorithm.\n\ 1355hexversion -- version information encoded as a single integer\n\ 1356implementation -- Python implementation information.\n\ 1357int_info -- a struct sequence with information about the int implementation.\n\ 1358maxsize -- the largest supported length of containers.\n\ 1359maxunicode -- the value of the largest Unicode codepoint\n\ 1360platform -- platform identifier\n\ 1361prefix -- prefix used to find the Python library\n\ 1362thread_info -- a struct sequence with information about the thread implementation.\n\ 1363version -- the version of this interpreter as a string\n\ 1364version_info -- version information as a named tuple\n\ 1365" 1366) 1367#ifdef MS_WINDOWS 1368/* concatenating string here */ 1369PyDoc_STR( 1370"dllhandle -- [Windows only] integer handle of the Python DLL\n\ 1371winver -- [Windows only] version number of the Python DLL\n\ 1372" 1373) 1374#endif /* MS_WINDOWS */ 1375PyDoc_STR( 1376"__stdin__ -- the original stdin; don't touch!\n\ 1377__stdout__ -- the original stdout; don't touch!\n\ 1378__stderr__ -- the original stderr; don't touch!\n\ 1379__displayhook__ -- the original displayhook; don't touch!\n\ 1380__excepthook__ -- the original excepthook; don't touch!\n\ 1381\n\ 1382Functions:\n\ 1383\n\ 1384displayhook() -- print an object to the screen, and save it in builtins._\n\ 1385excepthook() -- print an exception and its traceback to sys.stderr\n\ 1386exc_info() -- return thread-safe information about the current exception\n\ 1387exit() -- exit the interpreter by raising SystemExit\n\ 1388getdlopenflags() -- returns flags to be used for dlopen() calls\n\ 1389getprofile() -- get the global profiling function\n\ 1390getrefcount() -- return the reference count for an object (plus one :-)\n\ 1391getrecursionlimit() -- return the max recursion depth for the interpreter\n\ 1392getsizeof() -- return the size of an object in bytes\n\ 1393gettrace() -- get the global debug tracing function\n\ 1394setcheckinterval() -- control how often the interpreter checks for events\n\ 1395setdlopenflags() -- set the flags to be used for dlopen() calls\n\ 1396setprofile() -- set the global profiling function\n\ 1397setrecursionlimit() -- set the max recursion depth for the interpreter\n\ 1398settrace() -- set the global debug tracing function\n\ 1399" 1400) 1401/* end of sys_doc */ ; 1402 1403 1404PyDoc_STRVAR(flags__doc__, 1405"sys.flags\n\ 1406\n\ 1407Flags provided through command line arguments or environment vars."); 1408 1409static PyTypeObject FlagsType; 1410 1411static PyStructSequence_Field flags_fields[] = { 1412 {"debug", "-d"}, 1413 {"inspect", "-i"}, 1414 {"interactive", "-i"}, 1415 {"optimize", "-O or -OO"}, 1416 {"dont_write_bytecode", "-B"}, 1417 {"no_user_site", "-s"}, 1418 {"no_site", "-S"}, 1419 {"ignore_environment", "-E"}, 1420 {"verbose", "-v"}, 1421 /* {"unbuffered", "-u"}, */ 1422 /* {"skip_first", "-x"}, */ 1423 {"bytes_warning", "-b"}, 1424 {"quiet", "-q"}, 1425 {"hash_randomization", "-R"}, 1426 {"isolated", "-I"}, 1427 {0} 1428}; 1429 1430static PyStructSequence_Desc flags_desc = { 1431 "sys.flags", /* name */ 1432 flags__doc__, /* doc */ 1433 flags_fields, /* fields */ 1434 13 1435}; 1436 1437static PyObject* 1438make_flags(void) 1439{ 1440 int pos = 0; 1441 PyObject *seq; 1442 1443 seq = PyStructSequence_New(&FlagsType); 1444 if (seq == NULL) 1445 return NULL; 1446 1447#define SetFlag(flag) \ 1448 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) 1449 1450 SetFlag(Py_DebugFlag); 1451 SetFlag(Py_InspectFlag); 1452 SetFlag(Py_InteractiveFlag); 1453 SetFlag(Py_OptimizeFlag); 1454 SetFlag(Py_DontWriteBytecodeFlag); 1455 SetFlag(Py_NoUserSiteDirectory); 1456 SetFlag(Py_NoSiteFlag); 1457 SetFlag(Py_IgnoreEnvironmentFlag); 1458 SetFlag(Py_VerboseFlag); 1459 /* SetFlag(saw_unbuffered_flag); */ 1460 /* SetFlag(skipfirstline); */ 1461 SetFlag(Py_BytesWarningFlag); 1462 SetFlag(Py_QuietFlag); 1463 SetFlag(Py_HashRandomizationFlag); 1464 SetFlag(Py_IsolatedFlag); 1465#undef SetFlag 1466 1467 if (PyErr_Occurred()) { 1468 Py_DECREF(seq); 1469 return NULL; 1470 } 1471 return seq; 1472} 1473 1474PyDoc_STRVAR(version_info__doc__, 1475"sys.version_info\n\ 1476\n\ 1477Version information as a named tuple."); 1478 1479static PyTypeObject VersionInfoType; 1480 1481static PyStructSequence_Field version_info_fields[] = { 1482 {"major", "Major release number"}, 1483 {"minor", "Minor release number"}, 1484 {"micro", "Patch release number"}, 1485 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, 1486 {"serial", "Serial release number"}, 1487 {0} 1488}; 1489 1490static PyStructSequence_Desc version_info_desc = { 1491 "sys.version_info", /* name */ 1492 version_info__doc__, /* doc */ 1493 version_info_fields, /* fields */ 1494 5 1495}; 1496 1497static PyObject * 1498make_version_info(void) 1499{ 1500 PyObject *version_info; 1501 char *s; 1502 int pos = 0; 1503 1504 version_info = PyStructSequence_New(&VersionInfoType); 1505 if (version_info == NULL) { 1506 return NULL; 1507 } 1508 1509 /* 1510 * These release level checks are mutually exclusive and cover 1511 * the field, so don't get too fancy with the pre-processor! 1512 */ 1513#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA 1514 s = "alpha"; 1515#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA 1516 s = "beta"; 1517#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA 1518 s = "candidate"; 1519#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL 1520 s = "final"; 1521#endif 1522 1523#define SetIntItem(flag) \ 1524 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) 1525#define SetStrItem(flag) \ 1526 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) 1527 1528 SetIntItem(PY_MAJOR_VERSION); 1529 SetIntItem(PY_MINOR_VERSION); 1530 SetIntItem(PY_MICRO_VERSION); 1531 SetStrItem(s); 1532 SetIntItem(PY_RELEASE_SERIAL); 1533#undef SetIntItem 1534#undef SetStrItem 1535 1536 if (PyErr_Occurred()) { 1537 Py_CLEAR(version_info); 1538 return NULL; 1539 } 1540 return version_info; 1541} 1542 1543/* sys.implementation values */ 1544#define NAME "cpython" 1545const char *_PySys_ImplName = NAME; 1546#define QUOTE(arg) #arg 1547#define STRIFY(name) QUOTE(name) 1548#define MAJOR STRIFY(PY_MAJOR_VERSION) 1549#define MINOR STRIFY(PY_MINOR_VERSION) 1550#define TAG NAME "-" MAJOR MINOR; 1551const char *_PySys_ImplCacheTag = TAG; 1552#undef NAME 1553#undef QUOTE 1554#undef STRIFY 1555#undef MAJOR 1556#undef MINOR 1557#undef TAG 1558 1559static PyObject * 1560make_impl_info(PyObject *version_info) 1561{ 1562 int res; 1563 PyObject *impl_info, *value, *ns; 1564 1565 impl_info = PyDict_New(); 1566 if (impl_info == NULL) 1567 return NULL; 1568 1569 /* populate the dict */ 1570 1571 value = PyUnicode_FromString(_PySys_ImplName); 1572 if (value == NULL) 1573 goto error; 1574 res = PyDict_SetItemString(impl_info, "name", value); 1575 Py_DECREF(value); 1576 if (res < 0) 1577 goto error; 1578 1579 value = PyUnicode_FromString(_PySys_ImplCacheTag); 1580 if (value == NULL) 1581 goto error; 1582 res = PyDict_SetItemString(impl_info, "cache_tag", value); 1583 Py_DECREF(value); 1584 if (res < 0) 1585 goto error; 1586 1587 res = PyDict_SetItemString(impl_info, "version", version_info); 1588 if (res < 0) 1589 goto error; 1590 1591 value = PyLong_FromLong(PY_VERSION_HEX); 1592 if (value == NULL) 1593 goto error; 1594 res = PyDict_SetItemString(impl_info, "hexversion", value); 1595 Py_DECREF(value); 1596 if (res < 0) 1597 goto error; 1598 1599 /* dict ready */ 1600 1601 ns = _PyNamespace_New(impl_info); 1602 Py_DECREF(impl_info); 1603 return ns; 1604 1605error: 1606 Py_CLEAR(impl_info); 1607 return NULL; 1608} 1609 1610static struct PyModuleDef sysmodule = { 1611 PyModuleDef_HEAD_INIT, 1612 "sys", 1613 sys_doc, 1614 -1, /* multiple "initialization" just copies the module dict. */ 1615 sys_methods, 1616 NULL, 1617 NULL, 1618 NULL, 1619 NULL 1620}; 1621 1622PyObject * 1623_PySys_Init(void) 1624{ 1625 PyObject *m, *sysdict, *version_info; 1626 1627 m = PyModule_Create(&sysmodule); 1628 if (m == NULL) 1629 return NULL; 1630 sysdict = PyModule_GetDict(m); 1631#define SET_SYS_FROM_STRING_BORROW(key, value) \ 1632 do { \ 1633 int res; \ 1634 PyObject *v = (value); \ 1635 if (v == NULL) \ 1636 return NULL; \ 1637 res = PyDict_SetItemString(sysdict, key, v); \ 1638 if (res < 0) { \ 1639 return NULL; \ 1640 } \ 1641 } while (0) 1642#define SET_SYS_FROM_STRING(key, value) \ 1643 do { \ 1644 int res; \ 1645 PyObject *v = (value); \ 1646 if (v == NULL) \ 1647 return NULL; \ 1648 res = PyDict_SetItemString(sysdict, key, v); \ 1649 Py_DECREF(v); \ 1650 if (res < 0) { \ 1651 return NULL; \ 1652 } \ 1653 } while (0) 1654 1655 /* Check that stdin is not a directory 1656 Using shell redirection, you can redirect stdin to a directory, 1657 crashing the Python interpreter. Catch this common mistake here 1658 and output a useful error message. Note that under MS Windows, 1659 the shell already prevents that. */ 1660#if !defined(MS_WINDOWS) 1661 { 1662 struct stat sb; 1663 if (fstat(fileno(stdin), &sb) == 0 && 1664 S_ISDIR(sb.st_mode)) { 1665 /* There's nothing more we can do. */ 1666 /* Py_FatalError() will core dump, so just exit. */ 1667 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n"); 1668 exit(EXIT_FAILURE); 1669 } 1670 } 1671#endif 1672 1673 /* stdin/stdout/stderr are now set by pythonrun.c */ 1674 1675 SET_SYS_FROM_STRING_BORROW("__displayhook__", 1676 PyDict_GetItemString(sysdict, "displayhook")); 1677 SET_SYS_FROM_STRING_BORROW("__excepthook__", 1678 PyDict_GetItemString(sysdict, "excepthook")); 1679 SET_SYS_FROM_STRING("version", 1680 PyUnicode_FromString(Py_GetVersion())); 1681 SET_SYS_FROM_STRING("hexversion", 1682 PyLong_FromLong(PY_VERSION_HEX)); 1683 SET_SYS_FROM_STRING("_mercurial", 1684 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(), 1685 _Py_hgversion())); 1686 SET_SYS_FROM_STRING("dont_write_bytecode", 1687 PyBool_FromLong(Py_DontWriteBytecodeFlag)); 1688 SET_SYS_FROM_STRING("api_version", 1689 PyLong_FromLong(PYTHON_API_VERSION)); 1690 SET_SYS_FROM_STRING("copyright", 1691 PyUnicode_FromString(Py_GetCopyright())); 1692 SET_SYS_FROM_STRING("platform", 1693 PyUnicode_FromString(Py_GetPlatform())); 1694 SET_SYS_FROM_STRING("executable", 1695 PyUnicode_FromWideChar( 1696 Py_GetProgramFullPath(), -1)); 1697 SET_SYS_FROM_STRING("prefix", 1698 PyUnicode_FromWideChar(Py_GetPrefix(), -1)); 1699 SET_SYS_FROM_STRING("exec_prefix", 1700 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); 1701 SET_SYS_FROM_STRING("base_prefix", 1702 PyUnicode_FromWideChar(Py_GetPrefix(), -1)); 1703 SET_SYS_FROM_STRING("base_exec_prefix", 1704 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); 1705 SET_SYS_FROM_STRING("maxsize", 1706 PyLong_FromSsize_t(PY_SSIZE_T_MAX)); 1707 SET_SYS_FROM_STRING("float_info", 1708 PyFloat_GetInfo()); 1709 SET_SYS_FROM_STRING("int_info", 1710 PyLong_GetInfo()); 1711 /* initialize hash_info */ 1712 if (Hash_InfoType.tp_name == NULL) { 1713 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) 1714 return NULL; 1715 } 1716 SET_SYS_FROM_STRING("hash_info", 1717 get_hash_info()); 1718 SET_SYS_FROM_STRING("maxunicode", 1719 PyLong_FromLong(0x10FFFF)); 1720 SET_SYS_FROM_STRING("builtin_module_names", 1721 list_builtin_module_names()); 1722#if PY_BIG_ENDIAN 1723 SET_SYS_FROM_STRING("byteorder", 1724 PyUnicode_FromString("big")); 1725#else 1726 SET_SYS_FROM_STRING("byteorder", 1727 PyUnicode_FromString("little")); 1728#endif 1729 1730#ifdef MS_COREDLL 1731 SET_SYS_FROM_STRING("dllhandle", 1732 PyLong_FromVoidPtr(PyWin_DLLhModule)); 1733 SET_SYS_FROM_STRING("winver", 1734 PyUnicode_FromString(PyWin_DLLVersionString)); 1735#endif 1736#ifdef ABIFLAGS 1737 SET_SYS_FROM_STRING("abiflags", 1738 PyUnicode_FromString(ABIFLAGS)); 1739#endif 1740 if (warnoptions == NULL) { 1741 warnoptions = PyList_New(0); 1742 if (warnoptions == NULL) 1743 return NULL; 1744 } 1745 else { 1746 Py_INCREF(warnoptions); 1747 } 1748 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions); 1749 1750 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions()); 1751 1752 /* version_info */ 1753 if (VersionInfoType.tp_name == NULL) { 1754 if (PyStructSequence_InitType2(&VersionInfoType, 1755 &version_info_desc) < 0) 1756 return NULL; 1757 } 1758 version_info = make_version_info(); 1759 SET_SYS_FROM_STRING("version_info", version_info); 1760 /* prevent user from creating new instances */ 1761 VersionInfoType.tp_init = NULL; 1762 VersionInfoType.tp_new = NULL; 1763 1764 /* implementation */ 1765 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info)); 1766 1767 /* flags */ 1768 if (FlagsType.tp_name == 0) { 1769 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) 1770 return NULL; 1771 } 1772 SET_SYS_FROM_STRING("flags", make_flags()); 1773 /* prevent user from creating new instances */ 1774 FlagsType.tp_init = NULL; 1775 FlagsType.tp_new = NULL; 1776 1777 1778#if defined(MS_WINDOWS) 1779 /* getwindowsversion */ 1780 if (WindowsVersionType.tp_name == 0) 1781 if (PyStructSequence_InitType2(&WindowsVersionType, 1782 &windows_version_desc) < 0) 1783 return NULL; 1784 /* prevent user from creating new instances */ 1785 WindowsVersionType.tp_init = NULL; 1786 WindowsVersionType.tp_new = NULL; 1787#endif 1788 1789 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ 1790#ifndef PY_NO_SHORT_FLOAT_REPR 1791 SET_SYS_FROM_STRING("float_repr_style", 1792 PyUnicode_FromString("short")); 1793#else 1794 SET_SYS_FROM_STRING("float_repr_style", 1795 PyUnicode_FromString("legacy")); 1796#endif 1797 1798#ifdef WITH_THREAD 1799 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo()); 1800#endif 1801 1802#undef SET_SYS_FROM_STRING 1803 if (PyErr_Occurred()) 1804 return NULL; 1805 return m; 1806} 1807 1808static PyObject * 1809makepathobject(const wchar_t *path, wchar_t delim) 1810{ 1811 int i, n; 1812 const wchar_t *p; 1813 PyObject *v, *w; 1814 1815 n = 1; 1816 p = path; 1817 while ((p = wcschr(p, delim)) != NULL) { 1818 n++; 1819 p++; 1820 } 1821 v = PyList_New(n); 1822 if (v == NULL) 1823 return NULL; 1824 for (i = 0; ; i++) { 1825 p = wcschr(path, delim); 1826 if (p == NULL) 1827 p = path + wcslen(path); /* End of string */ 1828 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); 1829 if (w == NULL) { 1830 Py_DECREF(v); 1831 return NULL; 1832 } 1833 PyList_SetItem(v, i, w); 1834 if (*p == '\0') 1835 break; 1836 path = p+1; 1837 } 1838 return v; 1839} 1840 1841void 1842PySys_SetPath(const wchar_t *path) 1843{ 1844 PyObject *v; 1845 if ((v = makepathobject(path, DELIM)) == NULL) 1846 Py_FatalError("can't create sys.path"); 1847 if (_PySys_SetObjectId(&PyId_path, v) != 0) 1848 Py_FatalError("can't assign sys.path"); 1849 Py_DECREF(v); 1850} 1851 1852static PyObject * 1853makeargvobject(int argc, wchar_t **argv) 1854{ 1855 PyObject *av; 1856 if (argc <= 0 || argv == NULL) { 1857 /* Ensure at least one (empty) argument is seen */ 1858 static wchar_t *empty_argv[1] = {L""}; 1859 argv = empty_argv; 1860 argc = 1; 1861 } 1862 av = PyList_New(argc); 1863 if (av != NULL) { 1864 int i; 1865 for (i = 0; i < argc; i++) { 1866#ifdef __VMS 1867 PyObject *v; 1868 1869 /* argv[0] is the script pathname if known */ 1870 if (i == 0) { 1871 char* fn = decc$translate_vms(argv[0]); 1872 if ((fn == (char *)0) || fn == (char *)-1) 1873 v = PyUnicode_FromString(argv[0]); 1874 else 1875 v = PyUnicode_FromString( 1876 decc$translate_vms(argv[0])); 1877 } else 1878 v = PyUnicode_FromString(argv[i]); 1879#else 1880 PyObject *v = PyUnicode_FromWideChar(argv[i], -1); 1881#endif 1882 if (v == NULL) { 1883 Py_DECREF(av); 1884 av = NULL; 1885 break; 1886 } 1887 PyList_SetItem(av, i, v); 1888 } 1889 } 1890 return av; 1891} 1892 1893#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \ 1894 (argc > 0 && argv0 != NULL && \ 1895 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0) 1896 1897static void 1898sys_update_path(int argc, wchar_t **argv) 1899{ 1900 wchar_t *argv0; 1901 wchar_t *p = NULL; 1902 Py_ssize_t n = 0; 1903 PyObject *a; 1904 PyObject *path; 1905#ifdef HAVE_READLINK 1906 wchar_t link[MAXPATHLEN+1]; 1907 wchar_t argv0copy[2*MAXPATHLEN+1]; 1908 int nr = 0; 1909#endif 1910#if defined(HAVE_REALPATH) 1911 wchar_t fullpath[MAXPATHLEN]; 1912#elif defined(MS_WINDOWS) && !defined(MS_WINCE) 1913 wchar_t fullpath[MAX_PATH]; 1914#endif 1915 1916 path = _PySys_GetObjectId(&PyId_path); 1917 if (path == NULL) 1918 return; 1919 1920 argv0 = argv[0]; 1921 1922#ifdef HAVE_READLINK 1923 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) 1924 nr = _Py_wreadlink(argv0, link, MAXPATHLEN); 1925 if (nr > 0) { 1926 /* It's a symlink */ 1927 link[nr] = '\0'; 1928 if (link[0] == SEP) 1929 argv0 = link; /* Link to absolute path */ 1930 else if (wcschr(link, SEP) == NULL) 1931 ; /* Link without path */ 1932 else { 1933 /* Must join(dirname(argv0), link) */ 1934 wchar_t *q = wcsrchr(argv0, SEP); 1935 if (q == NULL) 1936 argv0 = link; /* argv0 without path */ 1937 else { 1938 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */ 1939 wcsncpy(argv0copy, argv0, MAXPATHLEN); 1940 q = wcsrchr(argv0copy, SEP); 1941 wcsncpy(q+1, link, MAXPATHLEN); 1942 q[MAXPATHLEN + 1] = L'\0'; 1943 argv0 = argv0copy; 1944 } 1945 } 1946 } 1947#endif /* HAVE_READLINK */ 1948#if SEP == '\\' /* Special case for MS filename syntax */ 1949 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) { 1950 wchar_t *q; 1951#if defined(MS_WINDOWS) && !defined(MS_WINCE) 1952 /* This code here replaces the first element in argv with the full 1953 path that it represents. Under CE, there are no relative paths so 1954 the argument must be the full path anyway. */ 1955 wchar_t *ptemp; 1956 if (GetFullPathNameW(argv0, 1957 Py_ARRAY_LENGTH(fullpath), 1958 fullpath, 1959 &ptemp)) { 1960 argv0 = fullpath; 1961 } 1962#endif 1963 p = wcsrchr(argv0, SEP); 1964 /* Test for alternate separator */ 1965 q = wcsrchr(p ? p : argv0, '/'); 1966 if (q != NULL) 1967 p = q; 1968 if (p != NULL) { 1969 n = p + 1 - argv0; 1970 if (n > 1 && p[-1] != ':') 1971 n--; /* Drop trailing separator */ 1972 } 1973 } 1974#else /* All other filename syntaxes */ 1975 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) { 1976#if defined(HAVE_REALPATH) 1977 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) { 1978 argv0 = fullpath; 1979 } 1980#endif 1981 p = wcsrchr(argv0, SEP); 1982 } 1983 if (p != NULL) { 1984 n = p + 1 - argv0; 1985#if SEP == '/' /* Special case for Unix filename syntax */ 1986 if (n > 1) 1987 n--; /* Drop trailing separator */ 1988#endif /* Unix */ 1989 } 1990#endif /* All others */ 1991 a = PyUnicode_FromWideChar(argv0, n); 1992 if (a == NULL) 1993 Py_FatalError("no mem for sys.path insertion"); 1994 if (PyList_Insert(path, 0, a) < 0) 1995 Py_FatalError("sys.path.insert(0) failed"); 1996 Py_DECREF(a); 1997} 1998 1999void 2000PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) 2001{ 2002 PyObject *av = makeargvobject(argc, argv); 2003 if (av == NULL) 2004 Py_FatalError("no mem for sys.argv"); 2005 if (PySys_SetObject("argv", av) != 0) 2006 Py_FatalError("can't assign sys.argv"); 2007 Py_DECREF(av); 2008 if (updatepath) 2009 sys_update_path(argc, argv); 2010} 2011 2012void 2013PySys_SetArgv(int argc, wchar_t **argv) 2014{ 2015 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0); 2016} 2017 2018/* Reimplementation of PyFile_WriteString() no calling indirectly 2019 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ 2020 2021static int 2022sys_pyfile_write_unicode(PyObject *unicode, PyObject *file) 2023{ 2024 PyObject *writer = NULL, *args = NULL, *result = NULL; 2025 int err; 2026 2027 if (file == NULL) 2028 return -1; 2029 2030 writer = _PyObject_GetAttrId(file, &PyId_write); 2031 if (writer == NULL) 2032 goto error; 2033 2034 args = PyTuple_Pack(1, unicode); 2035 if (args == NULL) 2036 goto error; 2037 2038 result = PyEval_CallObject(writer, args); 2039 if (result == NULL) { 2040 goto error; 2041 } else { 2042 err = 0; 2043 goto finally; 2044 } 2045 2046error: 2047 err = -1; 2048finally: 2049 Py_XDECREF(writer); 2050 Py_XDECREF(args); 2051 Py_XDECREF(result); 2052 return err; 2053} 2054 2055static int 2056sys_pyfile_write(const char *text, PyObject *file) 2057{ 2058 PyObject *unicode = NULL; 2059 int err; 2060 2061 if (file == NULL) 2062 return -1; 2063 2064 unicode = PyUnicode_FromString(text); 2065 if (unicode == NULL) 2066 return -1; 2067 2068 err = sys_pyfile_write_unicode(unicode, file); 2069 Py_DECREF(unicode); 2070 return err; 2071} 2072 2073/* APIs to write to sys.stdout or sys.stderr using a printf-like interface. 2074 Adapted from code submitted by Just van Rossum. 2075 2076 PySys_WriteStdout(format, ...) 2077 PySys_WriteStderr(format, ...) 2078 2079 The first function writes to sys.stdout; the second to sys.stderr. When 2080 there is a problem, they write to the real (C level) stdout or stderr; 2081 no exceptions are raised. 2082 2083 PyErr_CheckSignals() is not called to avoid the execution of the Python 2084 signal handlers: they may raise a new exception whereas sys_write() 2085 ignores all exceptions. 2086 2087 Both take a printf-style format string as their first argument followed 2088 by a variable length argument list determined by the format string. 2089 2090 *** WARNING *** 2091 2092 The format should limit the total size of the formatted output string to 2093 1000 bytes. In particular, this means that no unrestricted "%s" formats 2094 should occur; these should be limited using "%.<N>s where <N> is a 2095 decimal number calculated so that <N> plus the maximum size of other 2096 formatted text does not exceed 1000 bytes. Also watch out for "%f", 2097 which can print hundreds of digits for very large numbers. 2098 2099 */ 2100 2101static void 2102sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va) 2103{ 2104 PyObject *file; 2105 PyObject *error_type, *error_value, *error_traceback; 2106 char buffer[1001]; 2107 int written; 2108 2109 PyErr_Fetch(&error_type, &error_value, &error_traceback); 2110 file = _PySys_GetObjectId(key); 2111 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); 2112 if (sys_pyfile_write(buffer, file) != 0) { 2113 PyErr_Clear(); 2114 fputs(buffer, fp); 2115 } 2116 if (written < 0 || (size_t)written >= sizeof(buffer)) { 2117 const char *truncated = "... truncated"; 2118 if (sys_pyfile_write(truncated, file) != 0) 2119 fputs(truncated, fp); 2120 } 2121 PyErr_Restore(error_type, error_value, error_traceback); 2122} 2123 2124void 2125PySys_WriteStdout(const char *format, ...) 2126{ 2127 va_list va; 2128 2129 va_start(va, format); 2130 sys_write(&PyId_stdout, stdout, format, va); 2131 va_end(va); 2132} 2133 2134void 2135PySys_WriteStderr(const char *format, ...) 2136{ 2137 va_list va; 2138 2139 va_start(va, format); 2140 sys_write(&PyId_stderr, stderr, format, va); 2141 va_end(va); 2142} 2143 2144static void 2145sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va) 2146{ 2147 PyObject *file, *message; 2148 PyObject *error_type, *error_value, *error_traceback; 2149 char *utf8; 2150 2151 PyErr_Fetch(&error_type, &error_value, &error_traceback); 2152 file = _PySys_GetObjectId(key); 2153 message = PyUnicode_FromFormatV(format, va); 2154 if (message != NULL) { 2155 if (sys_pyfile_write_unicode(message, file) != 0) { 2156 PyErr_Clear(); 2157 utf8 = _PyUnicode_AsString(message); 2158 if (utf8 != NULL) 2159 fputs(utf8, fp); 2160 } 2161 Py_DECREF(message); 2162 } 2163 PyErr_Restore(error_type, error_value, error_traceback); 2164} 2165 2166void 2167PySys_FormatStdout(const char *format, ...) 2168{ 2169 va_list va; 2170 2171 va_start(va, format); 2172 sys_format(&PyId_stdout, stdout, format, va); 2173 va_end(va); 2174} 2175 2176void 2177PySys_FormatStderr(const char *format, ...) 2178{ 2179 va_list va; 2180 2181 va_start(va, format); 2182 sys_format(&PyId_stderr, stderr, format, va); 2183 va_end(va); 2184} 2185