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