sysmodule.c revision d083839fb4f44ff66792d80f7a71863600ca4638
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 "compile.h" 19#include "frameobject.h" 20 21#include "osdefs.h" 22 23#ifdef HAVE_UNISTD_H 24#include <unistd.h> 25#endif 26 27#ifdef MS_COREDLL 28extern void *PyWin_DLLhModule; 29/* A string loaded from the DLL at startup: */ 30extern const char *PyWin_DLLVersionString; 31#endif 32 33PyObject * 34PySys_GetObject(char *name) 35{ 36 PyThreadState *tstate = PyThreadState_Get(); 37 PyObject *sd = tstate->interp->sysdict; 38 if (sd == NULL) 39 return NULL; 40 return PyDict_GetItemString(sd, name); 41} 42 43FILE * 44PySys_GetFile(char *name, FILE *def) 45{ 46 FILE *fp = NULL; 47 PyObject *v = PySys_GetObject(name); 48 if (v != NULL && PyFile_Check(v)) 49 fp = PyFile_AsFile(v); 50 if (fp == NULL) 51 fp = def; 52 return fp; 53} 54 55int 56PySys_SetObject(char *name, PyObject *v) 57{ 58 PyThreadState *tstate = PyThreadState_Get(); 59 PyObject *sd = tstate->interp->sysdict; 60 if (v == NULL) { 61 if (PyDict_GetItemString(sd, name) == NULL) 62 return 0; 63 else 64 return PyDict_DelItemString(sd, name); 65 } 66 else 67 return PyDict_SetItemString(sd, name, v); 68} 69 70static PyObject * 71sys_displayhook(PyObject *self, PyObject *args) 72{ 73 PyObject *o, *outf; 74 PyInterpreterState *interp = PyThreadState_Get()->interp; 75 PyObject *modules = interp->modules; 76 PyObject *builtins = PyDict_GetItemString(modules, "__builtin__"); 77 78 /* parse arguments */ 79 if (!PyArg_ParseTuple(args, "O:displayhook", &o)) 80 return NULL; 81 82 /* Print value except if None */ 83 /* After printing, also assign to '_' */ 84 /* Before, set '_' to None to avoid recursion */ 85 if (o == Py_None) { 86 Py_INCREF(Py_None); 87 return Py_None; 88 } 89 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) 90 return NULL; 91 if (Py_FlushLine() != 0) 92 return NULL; 93 outf = PySys_GetObject("stdout"); 94 if (outf == NULL) { 95 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); 96 return NULL; 97 } 98 if (PyFile_WriteObject(o, outf, 0) != 0) 99 return NULL; 100 PyFile_SoftSpace(outf, 1); 101 if (Py_FlushLine() != 0) 102 return NULL; 103 if (PyObject_SetAttrString(builtins, "_", o) != 0) 104 return NULL; 105 Py_INCREF(Py_None); 106 return Py_None; 107} 108 109static char displayhook_doc[] = 110"displayhook(object) -> None\n" 111"\n" 112"Print an object to sys.stdout and also save it in __builtin__._\n"; 113 114static PyObject * 115sys_excepthook(PyObject* self, PyObject* args) 116{ 117 PyObject *exc, *value, *tb; 118 if (!PyArg_ParseTuple(args, "OOO:excepthook", &exc, &value, &tb)) 119 return NULL; 120 PyErr_Display(exc, value, tb); 121 Py_INCREF(Py_None); 122 return Py_None; 123} 124 125static char excepthook_doc[] = 126"excepthook(exctype, value, traceback) -> None\n" 127"\n" 128"Handle an exception by displaying it with a traceback on sys.stderr.\n"; 129 130static PyObject * 131sys_exc_info(PyObject *self, PyObject *args) 132{ 133 PyThreadState *tstate; 134 if (!PyArg_ParseTuple(args, ":exc_info")) 135 return NULL; 136 tstate = PyThreadState_Get(); 137 return Py_BuildValue( 138 "(OOO)", 139 tstate->exc_type != NULL ? tstate->exc_type : Py_None, 140 tstate->exc_value != NULL ? tstate->exc_value : Py_None, 141 tstate->exc_traceback != NULL ? 142 tstate->exc_traceback : Py_None); 143} 144 145static char exc_info_doc[] = 146"exc_info() -> (type, value, traceback)\n\ 147\n\ 148Return information about the exception that is currently being handled.\n\ 149This should be called from inside an except clause only."; 150 151static PyObject * 152sys_exit(PyObject *self, PyObject *args) 153{ 154 /* Raise SystemExit so callers may catch it or clean up. */ 155 PyErr_SetObject(PyExc_SystemExit, args); 156 return NULL; 157} 158 159static char exit_doc[] = 160"exit([status])\n\ 161\n\ 162Exit the interpreter by raising SystemExit(status).\n\ 163If the status is omitted or None, it defaults to zero (i.e., success).\n\ 164If the status numeric, it will be used as the system exit status.\n\ 165If it is another kind of object, it will be printed and the system\n\ 166exit status will be one (i.e., failure)."; 167 168static PyObject * 169sys_getdefaultencoding(PyObject *self, PyObject *args) 170{ 171 if (!PyArg_ParseTuple(args, ":getdefaultencoding")) 172 return NULL; 173 return PyString_FromString(PyUnicode_GetDefaultEncoding()); 174} 175 176static char getdefaultencoding_doc[] = 177"getdefaultencoding() -> string\n\ 178\n\ 179Return the current default string encoding used by the Unicode \n\ 180implementation."; 181 182static PyObject * 183sys_setdefaultencoding(PyObject *self, PyObject *args) 184{ 185 char *encoding; 186 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) 187 return NULL; 188 if (PyUnicode_SetDefaultEncoding(encoding)) 189 return NULL; 190 Py_INCREF(Py_None); 191 return Py_None; 192} 193 194static char setdefaultencoding_doc[] = 195"setdefaultencoding(encoding)\n\ 196\n\ 197Set the current default string encoding used by the Unicode implementation."; 198 199extern int _PyTrace_Init(void); 200 201static PyObject * 202sys_settrace(PyObject *self, PyObject *args) 203{ 204 PyThreadState *tstate = PyThreadState_Get(); 205 if (_PyTrace_Init() == -1) 206 return NULL; 207 if (args == Py_None) 208 args = NULL; 209 else 210 Py_XINCREF(args); 211 Py_XDECREF(tstate->sys_tracefunc); 212 tstate->sys_tracefunc = args; 213 Py_INCREF(Py_None); 214 return Py_None; 215} 216 217static char settrace_doc[] = 218"settrace(function)\n\ 219\n\ 220Set the global debug tracing function. It will be called on each\n\ 221function call. See the debugger chapter in the library manual."; 222 223static PyObject * 224sys_setprofile(PyObject *self, PyObject *args) 225{ 226 PyThreadState *tstate = PyThreadState_Get(); 227 if (_PyTrace_Init() == -1) 228 return NULL; 229 if (args == Py_None) 230 args = NULL; 231 else 232 Py_XINCREF(args); 233 Py_XDECREF(tstate->sys_profilefunc); 234 tstate->sys_profilefunc = args; 235 Py_INCREF(Py_None); 236 return Py_None; 237} 238 239static char setprofile_doc[] = 240"setprofile(function)\n\ 241\n\ 242Set the profiling function. It will be called on each function call\n\ 243and return. See the profiler chapter in the library manual."; 244 245static PyObject * 246sys_setcheckinterval(PyObject *self, PyObject *args) 247{ 248 PyThreadState *tstate = PyThreadState_Get(); 249 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval)) 250 return NULL; 251 Py_INCREF(Py_None); 252 return Py_None; 253} 254 255static char setcheckinterval_doc[] = 256"setcheckinterval(n)\n\ 257\n\ 258Tell the Python interpreter to check for asynchronous events every\n\ 259n instructions. This also affects how often thread switches occur."; 260 261static PyObject * 262sys_setrecursionlimit(PyObject *self, PyObject *args) 263{ 264 int new_limit; 265 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) 266 return NULL; 267 if (new_limit <= 0) { 268 PyErr_SetString(PyExc_ValueError, 269 "recursion limit must be positive"); 270 return NULL; 271 } 272 Py_SetRecursionLimit(new_limit); 273 Py_INCREF(Py_None); 274 return Py_None; 275} 276 277static char setrecursionlimit_doc[] = 278"setrecursionlimit(n)\n\ 279\n\ 280Set the maximum depth of the Python interpreter stack to n. This\n\ 281limit prevents infinite recursion from causing an overflow of the C\n\ 282stack and crashing Python. The highest possible limit is platform-\n\ 283dependent."; 284 285static PyObject * 286sys_getrecursionlimit(PyObject *self, PyObject *args) 287{ 288 if (!PyArg_ParseTuple(args, ":getrecursionlimit")) 289 return NULL; 290 return PyInt_FromLong(Py_GetRecursionLimit()); 291} 292 293static char getrecursionlimit_doc[] = 294"getrecursionlimit()\n\ 295\n\ 296Return the current value of the recursion limit, the maximum depth\n\ 297of the Python interpreter stack. This limit prevents infinite\n\ 298recursion from causing an overflow of the C stack and crashing Python."; 299 300#ifdef USE_MALLOPT 301/* Link with -lmalloc (or -lmpc) on an SGI */ 302#include <malloc.h> 303 304static PyObject * 305sys_mdebug(PyObject *self, PyObject *args) 306{ 307 int flag; 308 if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) 309 return NULL; 310 mallopt(M_DEBUG, flag); 311 Py_INCREF(Py_None); 312 return Py_None; 313} 314#endif /* USE_MALLOPT */ 315 316static PyObject * 317sys_getrefcount(PyObject *self, PyObject *args) 318{ 319 PyObject *arg; 320 if (!PyArg_ParseTuple(args, "O:getrefcount", &arg)) 321 return NULL; 322 return PyInt_FromLong(arg->ob_refcnt); 323} 324 325#ifdef Py_TRACE_REFS 326static PyObject * 327sys_gettotalrefcount(PyObject *self, PyObject *args) 328{ 329 extern long _Py_RefTotal; 330 if (!PyArg_ParseTuple(args, ":gettotalrefcount")) 331 return NULL; 332 return PyInt_FromLong(_Py_RefTotal); 333} 334 335#endif /* Py_TRACE_REFS */ 336 337static char getrefcount_doc[] = 338"getrefcount(object) -> integer\n\ 339\n\ 340Return the current reference count for the object. This includes the\n\ 341temporary reference in the argument list, so it is at least 2."; 342 343#ifdef COUNT_ALLOCS 344static PyObject * 345sys_getcounts(PyObject *self, PyObject *args) 346{ 347 extern PyObject *get_counts(void); 348 349 if (!PyArg_ParseTuple(args, ":getcounts")) 350 return NULL; 351 return get_counts(); 352} 353#endif 354 355static char getframe_doc[] = 356"_getframe([depth]) -> frameobject\n\ 357\n\ 358Return a frame object from the call stack. If optional integer depth is\n\ 359given, return the frame object that many calls below the top of the stack.\n\ 360If that is deeper than the call stack, ValueError is raised. The default\n\ 361for depth is zero, returning the frame at the top of the call stack.\n\ 362\n\ 363This function should be used for internal and specialized\n\ 364purposes only."; 365 366static PyObject * 367sys_getframe(PyObject *self, PyObject *args) 368{ 369 PyFrameObject *f = PyThreadState_Get()->frame; 370 int depth = -1; 371 372 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) 373 return NULL; 374 375 while (depth > 0 && f != NULL) { 376 f = f->f_back; 377 --depth; 378 } 379 if (f == NULL) { 380 PyErr_SetString(PyExc_ValueError, 381 "call stack is not deep enough"); 382 return NULL; 383 } 384 Py_INCREF(f); 385 return (PyObject*)f; 386} 387 388 389#ifdef Py_TRACE_REFS 390/* Defined in objects.c because it uses static globals if that file */ 391extern PyObject *_Py_GetObjects(PyObject *, PyObject *); 392#endif 393 394#ifdef DYNAMIC_EXECUTION_PROFILE 395/* Defined in ceval.c because it uses static globals if that file */ 396extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *); 397#endif 398 399static PyMethodDef sys_methods[] = { 400 /* Might as well keep this in alphabetic order */ 401 {"displayhook", sys_displayhook, 1, displayhook_doc}, 402 {"exc_info", sys_exc_info, 1, exc_info_doc}, 403 {"excepthook", sys_excepthook, 1, excepthook_doc}, 404 {"exit", sys_exit, 0, exit_doc}, 405 {"getdefaultencoding", sys_getdefaultencoding, 1, 406 getdefaultencoding_doc}, 407#ifdef COUNT_ALLOCS 408 {"getcounts", sys_getcounts, 1}, 409#endif 410#ifdef DYNAMIC_EXECUTION_PROFILE 411 {"getdxp", _Py_GetDXProfile, 1}, 412#endif 413#ifdef Py_TRACE_REFS 414 {"getobjects", _Py_GetObjects, 1}, 415 {"gettotalrefcount", sys_gettotalrefcount, 1}, 416#endif 417 {"getrefcount", sys_getrefcount, 1, getrefcount_doc}, 418 {"getrecursionlimit", sys_getrecursionlimit, 1, 419 getrecursionlimit_doc}, 420 {"_getframe", sys_getframe, 1, getframe_doc}, 421#ifdef USE_MALLOPT 422 {"mdebug", sys_mdebug, 1}, 423#endif 424 {"setdefaultencoding", sys_setdefaultencoding, 1, 425 setdefaultencoding_doc}, 426 {"setcheckinterval", sys_setcheckinterval, 1, 427 setcheckinterval_doc}, 428 {"setprofile", sys_setprofile, 0, setprofile_doc}, 429 {"setrecursionlimit", sys_setrecursionlimit, 1, 430 setrecursionlimit_doc}, 431 {"settrace", sys_settrace, 0, settrace_doc}, 432 {NULL, NULL} /* sentinel */ 433}; 434 435static PyObject * 436list_builtin_module_names(void) 437{ 438 PyObject *list = PyList_New(0); 439 int i; 440 if (list == NULL) 441 return NULL; 442 for (i = 0; PyImport_Inittab[i].name != NULL; i++) { 443 PyObject *name = PyString_FromString( 444 PyImport_Inittab[i].name); 445 if (name == NULL) 446 break; 447 PyList_Append(list, name); 448 Py_DECREF(name); 449 } 450 if (PyList_Sort(list) != 0) { 451 Py_DECREF(list); 452 list = NULL; 453 } 454 if (list) { 455 PyObject *v = PyList_AsTuple(list); 456 Py_DECREF(list); 457 list = v; 458 } 459 return list; 460} 461 462static PyObject *warnoptions = NULL; 463 464void 465PySys_ResetWarnOptions(void) 466{ 467 if (warnoptions == NULL || !PyList_Check(warnoptions)) 468 return; 469 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); 470} 471 472void 473PySys_AddWarnOption(char *s) 474{ 475 PyObject *str; 476 477 if (warnoptions == NULL || !PyList_Check(warnoptions)) { 478 Py_XDECREF(warnoptions); 479 warnoptions = PyList_New(0); 480 if (warnoptions == NULL) 481 return; 482 } 483 str = PyString_FromString(s); 484 if (str != NULL) { 485 PyList_Append(warnoptions, str); 486 Py_DECREF(str); 487 } 488} 489 490/* XXX This doc string is too long to be a single string literal in VC++ 5.0. 491 Two literals concatenated works just fine. If you have a K&R compiler 492 or other abomination that however *does* understand longer strings, 493 get rid of the !!! comment in the middle and the quotes that surround it. */ 494static char sys_doc[] = 495"This module provides access to some objects used or maintained by the\n\ 496interpreter and to functions that interact strongly with the interpreter.\n\ 497\n\ 498Dynamic objects:\n\ 499\n\ 500argv -- command line arguments; argv[0] is the script pathname if known\n\ 501path -- module search path; path[0] is the script directory, else ''\n\ 502modules -- dictionary of loaded modules\n\ 503\n\ 504displayhook -- called to show results in an interactive session\n\ 505excepthook -- called to handle any uncaught exception other than SystemExit\n\ 506 To customize printing in an interactive session or to install a custom\n\ 507 top-level exception handler, assign other functions to replace these.\n\ 508\n\ 509exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\ 510 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\ 511\n\ 512stdin -- standard input file object; used by raw_input() and input()\n\ 513stdout -- standard output file object; used by the print statement\n\ 514stderr -- standard error object; used for error messages\n\ 515 By assigning other file objects (or objects that behave like files)\n\ 516 to these, it is possible to redirect all of the interpreter's I/O.\n\ 517\n\ 518last_type -- type of last uncaught exception\n\ 519last_value -- value of last uncaught exception\n\ 520last_traceback -- traceback of last uncaught exception\n\ 521 These three are only available in an interactive session after a\n\ 522 traceback has been printed.\n\ 523\n\ 524exc_type -- type of exception currently being handled\n\ 525exc_value -- value of exception currently being handled\n\ 526exc_traceback -- traceback of exception currently being handled\n\ 527 The function exc_info() should be used instead of these three,\n\ 528 because it is thread-safe.\n\ 529" 530#ifndef MS_WIN16 531/* concatenating string here */ 532"\n\ 533Static objects:\n\ 534\n\ 535maxint -- the largest supported integer (the smallest is -maxint-1)\n\ 536builtin_module_names -- tuple of module names built into this intepreter\n\ 537version -- the version of this interpreter as a string\n\ 538version_info -- version information as a tuple\n\ 539hexversion -- version information encoded as a single integer\n\ 540copyright -- copyright notice pertaining to this interpreter\n\ 541platform -- platform identifier\n\ 542executable -- pathname of this Python interpreter\n\ 543prefix -- prefix used to find the Python library\n\ 544exec_prefix -- prefix used to find the machine-specific Python library\n\ 545" 546#ifdef MS_WINDOWS 547/* concatenating string here */ 548"dllhandle -- [Windows only] integer handle of the Python DLL\n\ 549winver -- [Windows only] version number of the Python DLL\n\ 550" 551#endif /* MS_WINDOWS */ 552"__stdin__ -- the original stdin; don't touch!\n\ 553__stdout__ -- the original stdout; don't touch!\n\ 554__stderr__ -- the original stderr; don't touch!\n\ 555__displayhook__ -- the original displayhook; don't touch!\n\ 556__excepthook__ -- the original excepthook; don't touch!\n\ 557\n\ 558Functions:\n\ 559\n\ 560displayhook() -- print an object to the screen, and save it in __builtin__._\n\ 561excepthook() -- print an exception and its traceback to sys.stderr\n\ 562exc_info() -- return thread-safe information about the current exception\n\ 563exit() -- exit the interpreter by raising SystemExit\n\ 564getrefcount() -- return the reference count for an object (plus one :-)\n\ 565getrecursionlimit() -- return the max recursion depth for the interpreter\n\ 566setcheckinterval() -- control how often the interpreter checks for events\n\ 567setprofile() -- set the global profiling function\n\ 568setrecursionlimit() -- set the max recursion depth for the interpreter\n\ 569settrace() -- set the global debug tracing function\n\ 570" 571#endif /* MS_WIN16 */ 572/* end of sys_doc */ ; 573 574PyObject * 575_PySys_Init(void) 576{ 577 PyObject *m, *v, *sysdict; 578 PyObject *sysin, *sysout, *syserr; 579 char *s; 580 581 m = Py_InitModule3("sys", sys_methods, sys_doc); 582 sysdict = PyModule_GetDict(m); 583 584 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL); 585 sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL); 586 syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL); 587 if (PyErr_Occurred()) 588 return NULL; 589 PyDict_SetItemString(sysdict, "stdin", sysin); 590 PyDict_SetItemString(sysdict, "stdout", sysout); 591 PyDict_SetItemString(sysdict, "stderr", syserr); 592 /* Make backup copies for cleanup */ 593 PyDict_SetItemString(sysdict, "__stdin__", sysin); 594 PyDict_SetItemString(sysdict, "__stdout__", sysout); 595 PyDict_SetItemString(sysdict, "__stderr__", syserr); 596 PyDict_SetItemString(sysdict, "__displayhook__", 597 PyDict_GetItemString(sysdict, "displayhook")); 598 PyDict_SetItemString(sysdict, "__excepthook__", 599 PyDict_GetItemString(sysdict, "excepthook")); 600 Py_XDECREF(sysin); 601 Py_XDECREF(sysout); 602 Py_XDECREF(syserr); 603 PyDict_SetItemString(sysdict, "version", 604 v = PyString_FromString(Py_GetVersion())); 605 Py_XDECREF(v); 606 PyDict_SetItemString(sysdict, "hexversion", 607 v = PyInt_FromLong(PY_VERSION_HEX)); 608 Py_XDECREF(v); 609 /* 610 * These release level checks are mutually exclusive and cover 611 * the field, so don't get too fancy with the pre-processor! 612 */ 613#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA 614 s = "alpha"; 615#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA 616 s = "beta"; 617#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA 618 s = "candidate"; 619#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL 620 s = "final"; 621#endif 622 PyDict_SetItemString(sysdict, "version_info", 623 v = Py_BuildValue("iiisi", PY_MAJOR_VERSION, 624 PY_MINOR_VERSION, 625 PY_MICRO_VERSION, s, 626 PY_RELEASE_SERIAL)); 627 Py_XDECREF(v); 628 PyDict_SetItemString(sysdict, "copyright", 629 v = PyString_FromString(Py_GetCopyright())); 630 Py_XDECREF(v); 631 PyDict_SetItemString(sysdict, "platform", 632 v = PyString_FromString(Py_GetPlatform())); 633 Py_XDECREF(v); 634 PyDict_SetItemString(sysdict, "executable", 635 v = PyString_FromString(Py_GetProgramFullPath())); 636 Py_XDECREF(v); 637 PyDict_SetItemString(sysdict, "prefix", 638 v = PyString_FromString(Py_GetPrefix())); 639 Py_XDECREF(v); 640 PyDict_SetItemString(sysdict, "exec_prefix", 641 v = PyString_FromString(Py_GetExecPrefix())); 642 Py_XDECREF(v); 643 PyDict_SetItemString(sysdict, "maxint", 644 v = PyInt_FromLong(PyInt_GetMax())); 645 Py_XDECREF(v); 646 PyDict_SetItemString(sysdict, "builtin_module_names", 647 v = list_builtin_module_names()); 648 Py_XDECREF(v); 649 { 650 /* Assumes that longs are at least 2 bytes long. 651 Should be safe! */ 652 unsigned long number = 1; 653 char *value; 654 655 s = (char *) &number; 656 if (s[0] == 0) 657 value = "big"; 658 else 659 value = "little"; 660 PyDict_SetItemString(sysdict, "byteorder", 661 v = PyString_FromString(value)); 662 Py_XDECREF(v); 663 } 664#ifdef MS_COREDLL 665 PyDict_SetItemString(sysdict, "dllhandle", 666 v = PyLong_FromVoidPtr(PyWin_DLLhModule)); 667 Py_XDECREF(v); 668 PyDict_SetItemString(sysdict, "winver", 669 v = PyString_FromString(PyWin_DLLVersionString)); 670 Py_XDECREF(v); 671#endif 672 if (warnoptions == NULL) { 673 warnoptions = PyList_New(0); 674 } 675 else { 676 Py_INCREF(warnoptions); 677 } 678 if (warnoptions != NULL) { 679 PyDict_SetItemString(sysdict, "warnoptions", warnoptions); 680 } 681 682 if (PyErr_Occurred()) 683 return NULL; 684 return m; 685} 686 687static PyObject * 688makepathobject(char *path, int delim) 689{ 690 int i, n; 691 char *p; 692 PyObject *v, *w; 693 694 n = 1; 695 p = path; 696 while ((p = strchr(p, delim)) != NULL) { 697 n++; 698 p++; 699 } 700 v = PyList_New(n); 701 if (v == NULL) 702 return NULL; 703 for (i = 0; ; i++) { 704 p = strchr(path, delim); 705 if (p == NULL) 706 p = strchr(path, '\0'); /* End of string */ 707 w = PyString_FromStringAndSize(path, (int) (p - path)); 708 if (w == NULL) { 709 Py_DECREF(v); 710 return NULL; 711 } 712 PyList_SetItem(v, i, w); 713 if (*p == '\0') 714 break; 715 path = p+1; 716 } 717 return v; 718} 719 720void 721PySys_SetPath(char *path) 722{ 723 PyObject *v; 724 if ((v = makepathobject(path, DELIM)) == NULL) 725 Py_FatalError("can't create sys.path"); 726 if (PySys_SetObject("path", v) != 0) 727 Py_FatalError("can't assign sys.path"); 728 Py_DECREF(v); 729} 730 731static PyObject * 732makeargvobject(int argc, char **argv) 733{ 734 PyObject *av; 735 if (argc <= 0 || argv == NULL) { 736 /* Ensure at least one (empty) argument is seen */ 737 static char *empty_argv[1] = {""}; 738 argv = empty_argv; 739 argc = 1; 740 } 741 av = PyList_New(argc); 742 if (av != NULL) { 743 int i; 744 for (i = 0; i < argc; i++) { 745 PyObject *v = PyString_FromString(argv[i]); 746 if (v == NULL) { 747 Py_DECREF(av); 748 av = NULL; 749 break; 750 } 751 PyList_SetItem(av, i, v); 752 } 753 } 754 return av; 755} 756 757void 758PySys_SetArgv(int argc, char **argv) 759{ 760 PyObject *av = makeargvobject(argc, argv); 761 PyObject *path = PySys_GetObject("path"); 762 if (av == NULL) 763 Py_FatalError("no mem for sys.argv"); 764 if (PySys_SetObject("argv", av) != 0) 765 Py_FatalError("can't assign sys.argv"); 766 if (path != NULL) { 767 char *argv0 = argv[0]; 768 char *p = NULL; 769 int n = 0; 770 PyObject *a; 771#ifdef HAVE_READLINK 772 char link[MAXPATHLEN+1]; 773 char argv0copy[2*MAXPATHLEN+1]; 774 int nr = 0; 775 if (argc > 0 && argv0 != NULL) 776 nr = readlink(argv0, link, MAXPATHLEN); 777 if (nr > 0) { 778 /* It's a symlink */ 779 link[nr] = '\0'; 780 if (link[0] == SEP) 781 argv0 = link; /* Link to absolute path */ 782 else if (strchr(link, SEP) == NULL) 783 ; /* Link without path */ 784 else { 785 /* Must join(dirname(argv0), link) */ 786 char *q = strrchr(argv0, SEP); 787 if (q == NULL) 788 argv0 = link; /* argv0 without path */ 789 else { 790 /* Must make a copy */ 791 strcpy(argv0copy, argv0); 792 q = strrchr(argv0copy, SEP); 793 strcpy(q+1, link); 794 argv0 = argv0copy; 795 } 796 } 797 } 798#endif /* HAVE_READLINK */ 799#if SEP == '\\' /* Special case for MS filename syntax */ 800 if (argc > 0 && argv0 != NULL) { 801 char *q; 802 p = strrchr(argv0, SEP); 803 /* Test for alternate separator */ 804 q = strrchr(p ? p : argv0, '/'); 805 if (q != NULL) 806 p = q; 807 if (p != NULL) { 808 n = p + 1 - argv0; 809 if (n > 1 && p[-1] != ':') 810 n--; /* Drop trailing separator */ 811 } 812 } 813#else /* All other filename syntaxes */ 814 if (argc > 0 && argv0 != NULL) 815 p = strrchr(argv0, SEP); 816 if (p != NULL) { 817#ifndef RISCOS 818 n = p + 1 - argv0; 819#else /* don't include trailing separator */ 820 n = p - argv0; 821#endif /* RISCOS */ 822#if SEP == '/' /* Special case for Unix filename syntax */ 823 if (n > 1) 824 n--; /* Drop trailing separator */ 825#endif /* Unix */ 826 } 827#endif /* All others */ 828 a = PyString_FromStringAndSize(argv0, n); 829 if (a == NULL) 830 Py_FatalError("no mem for sys.path insertion"); 831 if (PyList_Insert(path, 0, a) < 0) 832 Py_FatalError("sys.path.insert(0) failed"); 833 Py_DECREF(a); 834 } 835 Py_DECREF(av); 836} 837 838 839/* APIs to write to sys.stdout or sys.stderr using a printf-like interface. 840 Adapted from code submitted by Just van Rossum. 841 842 PySys_WriteStdout(format, ...) 843 PySys_WriteStderr(format, ...) 844 845 The first function writes to sys.stdout; the second to sys.stderr. When 846 there is a problem, they write to the real (C level) stdout or stderr; 847 no exceptions are raised. 848 849 Both take a printf-style format string as their first argument followed 850 by a variable length argument list determined by the format string. 851 852 *** WARNING *** 853 854 The format should limit the total size of the formatted output string to 855 1000 bytes. In particular, this means that no unrestricted "%s" formats 856 should occur; these should be limited using "%.<N>s where <N> is a 857 decimal number calculated so that <N> plus the maximum size of other 858 formatted text does not exceed 1000 bytes. Also watch out for "%f", 859 which can print hundreds of digits for very large numbers. 860 861 */ 862 863static void 864mywrite(char *name, FILE *fp, const char *format, va_list va) 865{ 866 PyObject *file; 867 PyObject *error_type, *error_value, *error_traceback; 868 869 PyErr_Fetch(&error_type, &error_value, &error_traceback); 870 file = PySys_GetObject(name); 871 if (file == NULL || PyFile_AsFile(file) == fp) 872 vfprintf(fp, format, va); 873 else { 874 char buffer[1001]; 875 if (vsprintf(buffer, format, va) >= sizeof(buffer)) 876 Py_FatalError("PySys_WriteStdout/err: buffer overrun"); 877 if (PyFile_WriteString(buffer, file) != 0) { 878 PyErr_Clear(); 879 fputs(buffer, fp); 880 } 881 } 882 PyErr_Restore(error_type, error_value, error_traceback); 883} 884 885void 886PySys_WriteStdout(const char *format, ...) 887{ 888 va_list va; 889 890 va_start(va, format); 891 mywrite("stdout", stdout, format, va); 892 va_end(va); 893} 894 895void 896PySys_WriteStderr(const char *format, ...) 897{ 898 va_list va; 899 900 va_start(va, format); 901 mywrite("stderr", stderr, format, va); 902 va_end(va); 903} 904