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