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