5 Various bits of information used by the interpreter are collected in
8 - exit(sts): raise SystemExit
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)
19 #include "frameobject.h"
28 extern void *PyWin_DLLhModule
;
29 /* A string loaded from the DLL at startup: */
30 extern const char *PyWin_DLLVersionString
;
34 PySys_GetObject(char *name
)
36 PyThreadState
*tstate
= PyThreadState_Get();
37 PyObject
*sd
= tstate
->interp
->sysdict
;
40 return PyDict_GetItemString(sd
, name
);
44 PySys_GetFile(char *name
, FILE *def
)
47 PyObject
*v
= PySys_GetObject(name
);
48 if (v
!= NULL
&& PyFile_Check(v
))
49 fp
= PyFile_AsFile(v
);
56 PySys_SetObject(char *name
, PyObject
*v
)
58 PyThreadState
*tstate
= PyThreadState_Get();
59 PyObject
*sd
= tstate
->interp
->sysdict
;
61 if (PyDict_GetItemString(sd
, name
) == NULL
)
64 return PyDict_DelItemString(sd
, name
);
67 return PyDict_SetItemString(sd
, name
, v
);
71 sys_displayhook(PyObject
*self
, PyObject
*args
)
74 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
75 PyObject
*modules
= interp
->modules
;
76 PyObject
*builtins
= PyDict_GetItemString(modules
, "__builtin__");
79 if (!PyArg_ParseTuple(args
, "O:displayhook", &o
))
82 /* Print value except if None */
83 /* After printing, also assign to '_' */
84 /* Before, set '_' to None to avoid recursion */
89 if (PyObject_SetAttrString(builtins
, "_", Py_None
) != 0)
91 if (Py_FlushLine() != 0)
93 outf
= PySys_GetObject("stdout");
95 PyErr_SetString(PyExc_RuntimeError
, "lost sys.stdout");
98 if (PyFile_WriteObject(o
, outf
, 0) != 0)
100 PyFile_SoftSpace(outf
, 1);
101 if (Py_FlushLine() != 0)
103 if (PyObject_SetAttrString(builtins
, "_", o
) != 0)
109 static char displayhook_doc
[] =
110 "displayhook(object) -> None\n"
112 "Print an object to sys.stdout and also save it in __builtin__._\n";
115 sys_excepthook(PyObject
* self
, PyObject
* args
)
117 PyObject
*exc
, *value
, *tb
;
118 if (!PyArg_ParseTuple(args
, "OOO:excepthook", &exc
, &value
, &tb
))
120 PyErr_Display(exc
, value
, tb
);
125 static char excepthook_doc
[] =
126 "excepthook(exctype, value, traceback) -> None\n"
128 "Handle an exception by displaying it with a traceback on sys.stderr.\n";
131 sys_exc_info(PyObject
*self
, PyObject
*args
)
133 PyThreadState
*tstate
;
134 if (!PyArg_ParseTuple(args
, ":exc_info"))
136 tstate
= PyThreadState_Get();
137 return Py_BuildValue(
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
);
145 static char exc_info_doc
[] =
146 "exc_info() -> (type, value, traceback)\n\
148 Return information about the exception that is currently being handled.\n\
149 This should be called from inside an except clause only.";
152 sys_exit(PyObject
*self
, PyObject
*args
)
154 /* Raise SystemExit so callers may catch it or clean up. */
155 PyErr_SetObject(PyExc_SystemExit
, args
);
159 static char exit_doc
[] =
162 Exit the interpreter by raising SystemExit(status).\n\
163 If the status is omitted or None, it defaults to zero (i.e., success).\n\
164 If the status numeric, it will be used as the system exit status.\n\
165 If it is another kind of object, it will be printed and the system\n\
166 exit status will be one (i.e., failure).";
169 sys_getdefaultencoding(PyObject
*self
, PyObject
*args
)
171 if (!PyArg_ParseTuple(args
, ":getdefaultencoding"))
173 return PyString_FromString(PyUnicode_GetDefaultEncoding());
176 static char getdefaultencoding_doc
[] =
177 "getdefaultencoding() -> string\n\
179 Return the current default string encoding used by the Unicode \n\
183 sys_setdefaultencoding(PyObject
*self
, PyObject
*args
)
186 if (!PyArg_ParseTuple(args
, "s:setdefaultencoding", &encoding
))
188 if (PyUnicode_SetDefaultEncoding(encoding
))
194 static char setdefaultencoding_doc
[] =
195 "setdefaultencoding(encoding)\n\
197 Set the current default string encoding used by the Unicode implementation.";
200 * Cached interned string objects used for calling the profile and
201 * trace functions. Initialized by trace_init().
203 static PyObject
*whatstrings
[4] = {NULL
, NULL
, NULL
, NULL
};
208 static char *whatnames
[4] = {"call", "exception", "line", "return"};
211 for (i
= 0; i
< 4; ++i
) {
212 if (whatstrings
[i
] == NULL
) {
213 name
= PyString_InternFromString(whatnames
[i
]);
216 whatstrings
[i
] = name
;
224 call_trampoline(PyThreadState
*tstate
, PyObject
* callback
,
225 PyFrameObject
*frame
, int what
, PyObject
*arg
)
227 PyObject
*args
= PyTuple_New(3);
234 whatstr
= whatstrings
[what
];
239 PyTuple_SET_ITEM(args
, 0, (PyObject
*)frame
);
240 PyTuple_SET_ITEM(args
, 1, whatstr
);
241 PyTuple_SET_ITEM(args
, 2, arg
);
243 /* call the Python-level function */
244 PyFrame_FastToLocals(frame
);
245 result
= PyEval_CallObject(callback
, args
);
246 PyFrame_LocalsToFast(frame
, 1);
248 PyTraceBack_Here(frame
);
256 profile_trampoline(PyObject
*self
, PyFrameObject
*frame
,
257 int what
, PyObject
*arg
)
259 PyThreadState
*tstate
= frame
->f_tstate
;
262 result
= call_trampoline(tstate
, self
, frame
, what
, arg
);
263 if (result
== NULL
) {
264 PyEval_SetProfile(NULL
, NULL
);
272 trace_trampoline(PyObject
*self
, PyFrameObject
*frame
,
273 int what
, PyObject
*arg
)
275 PyThreadState
*tstate
= frame
->f_tstate
;
279 if (what
== PyTrace_CALL
)
282 callback
= frame
->f_trace
;
283 if (callback
== NULL
)
285 result
= call_trampoline(tstate
, callback
, frame
, what
, arg
);
286 if (result
== NULL
) {
287 PyEval_SetTrace(NULL
, NULL
);
288 Py_XDECREF(frame
->f_trace
);
289 frame
->f_trace
= NULL
;
292 if (result
!= Py_None
) {
293 PyObject
*temp
= frame
->f_trace
;
294 frame
->f_trace
= NULL
;
296 frame
->f_trace
= result
;
305 sys_settrace(PyObject
*self
, PyObject
*args
)
307 if (trace_init() == -1)
310 PyEval_SetTrace(NULL
, NULL
);
312 PyEval_SetTrace(trace_trampoline
, args
);
317 static char settrace_doc
[] =
318 "settrace(function)\n\
320 Set the global debug tracing function. It will be called on each\n\
321 function call. See the debugger chapter in the library manual.";
324 sys_setprofile(PyObject
*self
, PyObject
*args
)
326 if (trace_init() == -1)
329 PyEval_SetProfile(NULL
, NULL
);
331 PyEval_SetProfile(profile_trampoline
, args
);
336 static char setprofile_doc
[] =
337 "setprofile(function)\n\
339 Set the profiling function. It will be called on each function call\n\
340 and return. See the profiler chapter in the library manual.";
343 sys_setcheckinterval(PyObject
*self
, PyObject
*args
)
345 PyThreadState
*tstate
= PyThreadState_Get();
346 if (!PyArg_ParseTuple(args
, "i:setcheckinterval", &tstate
->interp
->checkinterval
))
352 static char setcheckinterval_doc
[] =
353 "setcheckinterval(n)\n\
355 Tell the Python interpreter to check for asynchronous events every\n\
356 n instructions. This also affects how often thread switches occur.";
359 sys_setrecursionlimit(PyObject
*self
, PyObject
*args
)
362 if (!PyArg_ParseTuple(args
, "i:setrecursionlimit", &new_limit
))
364 if (new_limit
<= 0) {
365 PyErr_SetString(PyExc_ValueError
,
366 "recursion limit must be positive");
369 Py_SetRecursionLimit(new_limit
);
374 static char setrecursionlimit_doc
[] =
375 "setrecursionlimit(n)\n\
377 Set the maximum depth of the Python interpreter stack to n. This\n\
378 limit prevents infinite recursion from causing an overflow of the C\n\
379 stack and crashing Python. The highest possible limit is platform-\n\
383 sys_getrecursionlimit(PyObject
*self
, PyObject
*args
)
385 if (!PyArg_ParseTuple(args
, ":getrecursionlimit"))
387 return PyInt_FromLong(Py_GetRecursionLimit());
390 static char getrecursionlimit_doc
[] =
391 "getrecursionlimit()\n\
393 Return the current value of the recursion limit, the maximum depth\n\
394 of the Python interpreter stack. This limit prevents infinite\n\
395 recursion from causing an overflow of the C stack and crashing Python.";
398 /* Link with -lmalloc (or -lmpc) on an SGI */
402 sys_mdebug(PyObject
*self
, PyObject
*args
)
405 if (!PyArg_ParseTuple(args
, "i:mdebug", &flag
))
407 mallopt(M_DEBUG
, flag
);
411 #endif /* USE_MALLOPT */
414 sys_getrefcount(PyObject
*self
, PyObject
*args
)
417 if (!PyArg_ParseTuple(args
, "O:getrefcount", &arg
))
419 return PyInt_FromLong(arg
->ob_refcnt
);
424 sys_gettotalrefcount(PyObject
*self
, PyObject
*args
)
426 extern long _Py_RefTotal
;
427 if (!PyArg_ParseTuple(args
, ":gettotalrefcount"))
429 return PyInt_FromLong(_Py_RefTotal
);
432 #endif /* Py_TRACE_REFS */
434 static char getrefcount_doc
[] =
435 "getrefcount(object) -> integer\n\
437 Return the current reference count for the object. This includes the\n\
438 temporary reference in the argument list, so it is at least 2.";
442 sys_getcounts(PyObject
*self
, PyObject
*args
)
444 extern PyObject
*get_counts(void);
446 if (!PyArg_ParseTuple(args
, ":getcounts"))
452 static char getframe_doc
[] =
453 "_getframe([depth]) -> frameobject\n\
455 Return a frame object from the call stack. If optional integer depth is\n\
456 given, return the frame object that many calls below the top of the stack.\n\
457 If that is deeper than the call stack, ValueError is raised. The default\n\
458 for depth is zero, returning the frame at the top of the call stack.\n\
460 This function should be used for internal and specialized\n\
464 sys_getframe(PyObject
*self
, PyObject
*args
)
466 PyFrameObject
*f
= PyThreadState_Get()->frame
;
469 if (!PyArg_ParseTuple(args
, "|i:_getframe", &depth
))
472 while (depth
> 0 && f
!= NULL
) {
477 PyErr_SetString(PyExc_ValueError
,
478 "call stack is not deep enough");
487 /* Defined in objects.c because it uses static globals if that file */
488 extern PyObject
*_Py_GetObjects(PyObject
*, PyObject
*);
491 #ifdef DYNAMIC_EXECUTION_PROFILE
492 /* Defined in ceval.c because it uses static globals if that file */
493 extern PyObject
*_Py_GetDXProfile(PyObject
*, PyObject
*);
496 static PyMethodDef sys_methods
[] = {
497 /* Might as well keep this in alphabetic order */
498 {"displayhook", sys_displayhook
, 1, displayhook_doc
},
499 {"exc_info", sys_exc_info
, 1, exc_info_doc
},
500 {"excepthook", sys_excepthook
, 1, excepthook_doc
},
501 {"exit", sys_exit
, 0, exit_doc
},
502 {"getdefaultencoding", sys_getdefaultencoding
, 1,
503 getdefaultencoding_doc
},
505 {"getcounts", sys_getcounts
, 1},
507 #ifdef DYNAMIC_EXECUTION_PROFILE
508 {"getdxp", _Py_GetDXProfile
, 1},
511 {"getobjects", _Py_GetObjects
, 1},
512 {"gettotalrefcount", sys_gettotalrefcount
, 1},
514 {"getrefcount", sys_getrefcount
, 1, getrefcount_doc
},
515 {"getrecursionlimit", sys_getrecursionlimit
, 1,
516 getrecursionlimit_doc
},
517 {"_getframe", sys_getframe
, 1, getframe_doc
},
519 {"mdebug", sys_mdebug
, 1},
521 {"setdefaultencoding", sys_setdefaultencoding
, 1,
522 setdefaultencoding_doc
},
523 {"setcheckinterval", sys_setcheckinterval
, 1,
524 setcheckinterval_doc
},
525 {"setprofile", sys_setprofile
, 0, setprofile_doc
},
526 {"setrecursionlimit", sys_setrecursionlimit
, 1,
527 setrecursionlimit_doc
},
528 {"settrace", sys_settrace
, 0, settrace_doc
},
529 {NULL
, NULL
} /* sentinel */
533 list_builtin_module_names(void)
535 PyObject
*list
= PyList_New(0);
539 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
540 PyObject
*name
= PyString_FromString(
541 PyImport_Inittab
[i
].name
);
544 PyList_Append(list
, name
);
547 if (PyList_Sort(list
) != 0) {
552 PyObject
*v
= PyList_AsTuple(list
);
559 static PyObject
*warnoptions
= NULL
;
562 PySys_ResetWarnOptions(void)
564 if (warnoptions
== NULL
|| !PyList_Check(warnoptions
))
566 PyList_SetSlice(warnoptions
, 0, PyList_GET_SIZE(warnoptions
), NULL
);
570 PySys_AddWarnOption(char *s
)
574 if (warnoptions
== NULL
|| !PyList_Check(warnoptions
)) {
575 Py_XDECREF(warnoptions
);
576 warnoptions
= PyList_New(0);
577 if (warnoptions
== NULL
)
580 str
= PyString_FromString(s
);
582 PyList_Append(warnoptions
, str
);
587 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
588 Two literals concatenated works just fine. If you have a K&R compiler
589 or other abomination that however *does* understand longer strings,
590 get rid of the !!! comment in the middle and the quotes that surround it. */
591 static char sys_doc
[] =
592 "This module provides access to some objects used or maintained by the\n\
593 interpreter and to functions that interact strongly with the interpreter.\n\
597 argv -- command line arguments; argv[0] is the script pathname if known\n\
598 path -- module search path; path[0] is the script directory, else ''\n\
599 modules -- dictionary of loaded modules\n\
601 displayhook -- called to show results in an interactive session\n\
602 excepthook -- called to handle any uncaught exception other than SystemExit\n\
603 To customize printing in an interactive session or to install a custom\n\
604 top-level exception handler, assign other functions to replace these.\n\
606 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
607 Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
609 stdin -- standard input file object; used by raw_input() and input()\n\
610 stdout -- standard output file object; used by the print statement\n\
611 stderr -- standard error object; used for error messages\n\
612 By assigning other file objects (or objects that behave like files)\n\
613 to these, it is possible to redirect all of the interpreter's I/O.\n\
615 last_type -- type of last uncaught exception\n\
616 last_value -- value of last uncaught exception\n\
617 last_traceback -- traceback of last uncaught exception\n\
618 These three are only available in an interactive session after a\n\
619 traceback has been printed.\n\
621 exc_type -- type of exception currently being handled\n\
622 exc_value -- value of exception currently being handled\n\
623 exc_traceback -- traceback of exception currently being handled\n\
624 The function exc_info() should be used instead of these three,\n\
625 because it is thread-safe.\n\
628 /* concatenating string here */
632 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
633 maxunicode -- the largest supported character\n\
634 builtin_module_names -- tuple of module names built into this intepreter\n\
635 version -- the version of this interpreter as a string\n\
636 version_info -- version information as a tuple\n\
637 hexversion -- version information encoded as a single integer\n\
638 copyright -- copyright notice pertaining to this interpreter\n\
639 platform -- platform identifier\n\
640 executable -- pathname of this Python interpreter\n\
641 prefix -- prefix used to find the Python library\n\
642 exec_prefix -- prefix used to find the machine-specific Python library\n\
645 /* concatenating string here */
646 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
647 winver -- [Windows only] version number of the Python DLL\n\
649 #endif /* MS_WINDOWS */
650 "__stdin__ -- the original stdin; don't touch!\n\
651 __stdout__ -- the original stdout; don't touch!\n\
652 __stderr__ -- the original stderr; don't touch!\n\
653 __displayhook__ -- the original displayhook; don't touch!\n\
654 __excepthook__ -- the original excepthook; don't touch!\n\
658 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
659 excepthook() -- print an exception and its traceback to sys.stderr\n\
660 exc_info() -- return thread-safe information about the current exception\n\
661 exit() -- exit the interpreter by raising SystemExit\n\
662 getrefcount() -- return the reference count for an object (plus one :-)\n\
663 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
664 setcheckinterval() -- control how often the interpreter checks for events\n\
665 setprofile() -- set the global profiling function\n\
666 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
667 settrace() -- set the global debug tracing function\n\
669 #endif /* MS_WIN16 */
670 /* end of sys_doc */ ;
675 PyObject
*m
, *v
, *sysdict
;
676 PyObject
*sysin
, *sysout
, *syserr
;
679 m
= Py_InitModule3("sys", sys_methods
, sys_doc
);
680 sysdict
= PyModule_GetDict(m
);
682 sysin
= PyFile_FromFile(stdin
, "<stdin>", "r", NULL
);
683 sysout
= PyFile_FromFile(stdout
, "<stdout>", "w", NULL
);
684 syserr
= PyFile_FromFile(stderr
, "<stderr>", "w", NULL
);
685 if (PyErr_Occurred())
687 PyDict_SetItemString(sysdict
, "stdin", sysin
);
688 PyDict_SetItemString(sysdict
, "stdout", sysout
);
689 PyDict_SetItemString(sysdict
, "stderr", syserr
);
690 /* Make backup copies for cleanup */
691 PyDict_SetItemString(sysdict
, "__stdin__", sysin
);
692 PyDict_SetItemString(sysdict
, "__stdout__", sysout
);
693 PyDict_SetItemString(sysdict
, "__stderr__", syserr
);
694 PyDict_SetItemString(sysdict
, "__displayhook__",
695 PyDict_GetItemString(sysdict
, "displayhook"));
696 PyDict_SetItemString(sysdict
, "__excepthook__",
697 PyDict_GetItemString(sysdict
, "excepthook"));
701 PyDict_SetItemString(sysdict
, "version",
702 v
= PyString_FromString(Py_GetVersion()));
704 PyDict_SetItemString(sysdict
, "hexversion",
705 v
= PyInt_FromLong(PY_VERSION_HEX
));
708 * These release level checks are mutually exclusive and cover
709 * the field, so don't get too fancy with the pre-processor!
711 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
713 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
715 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
717 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
720 PyDict_SetItemString(sysdict
, "version_info",
721 v
= Py_BuildValue("iiisi", PY_MAJOR_VERSION
,
726 PyDict_SetItemString(sysdict
, "copyright",
727 v
= PyString_FromString(Py_GetCopyright()));
729 PyDict_SetItemString(sysdict
, "platform",
730 v
= PyString_FromString(Py_GetPlatform()));
732 PyDict_SetItemString(sysdict
, "executable",
733 v
= PyString_FromString(Py_GetProgramFullPath()));
735 PyDict_SetItemString(sysdict
, "prefix",
736 v
= PyString_FromString(Py_GetPrefix()));
738 PyDict_SetItemString(sysdict
, "exec_prefix",
739 v
= PyString_FromString(Py_GetExecPrefix()));
741 PyDict_SetItemString(sysdict
, "maxint",
742 v
= PyInt_FromLong(PyInt_GetMax()));
744 PyDict_SetItemString(sysdict
, "maxunicode",
745 v
= PyInt_FromLong(PyUnicode_GetMax()));
747 PyDict_SetItemString(sysdict
, "builtin_module_names",
748 v
= list_builtin_module_names());
751 /* Assumes that longs are at least 2 bytes long.
753 unsigned long number
= 1;
756 s
= (char *) &number
;
761 PyDict_SetItemString(sysdict
, "byteorder",
762 v
= PyString_FromString(value
));
766 PyDict_SetItemString(sysdict
, "dllhandle",
767 v
= PyLong_FromVoidPtr(PyWin_DLLhModule
));
769 PyDict_SetItemString(sysdict
, "winver",
770 v
= PyString_FromString(PyWin_DLLVersionString
));
773 if (warnoptions
== NULL
) {
774 warnoptions
= PyList_New(0);
777 Py_INCREF(warnoptions
);
779 if (warnoptions
!= NULL
) {
780 PyDict_SetItemString(sysdict
, "warnoptions", warnoptions
);
783 if (PyErr_Occurred())
789 makepathobject(char *path
, int delim
)
797 while ((p
= strchr(p
, delim
)) != NULL
) {
805 p
= strchr(path
, delim
);
807 p
= strchr(path
, '\0'); /* End of string */
808 w
= PyString_FromStringAndSize(path
, (int) (p
- path
));
813 PyList_SetItem(v
, i
, w
);
822 PySys_SetPath(char *path
)
825 if ((v
= makepathobject(path
, DELIM
)) == NULL
)
826 Py_FatalError("can't create sys.path");
827 if (PySys_SetObject("path", v
) != 0)
828 Py_FatalError("can't assign sys.path");
833 makeargvobject(int argc
, char **argv
)
836 if (argc
<= 0 || argv
== NULL
) {
837 /* Ensure at least one (empty) argument is seen */
838 static char *empty_argv
[1] = {""};
842 av
= PyList_New(argc
);
845 for (i
= 0; i
< argc
; i
++) {
846 PyObject
*v
= PyString_FromString(argv
[i
]);
852 PyList_SetItem(av
, i
, v
);
859 PySys_SetArgv(int argc
, char **argv
)
861 PyObject
*av
= makeargvobject(argc
, argv
);
862 PyObject
*path
= PySys_GetObject("path");
864 Py_FatalError("no mem for sys.argv");
865 if (PySys_SetObject("argv", av
) != 0)
866 Py_FatalError("can't assign sys.argv");
868 char *argv0
= argv
[0];
873 char link
[MAXPATHLEN
+1];
874 char argv0copy
[2*MAXPATHLEN
+1];
876 if (argc
> 0 && argv0
!= NULL
)
877 nr
= readlink(argv0
, link
, MAXPATHLEN
);
882 argv0
= link
; /* Link to absolute path */
883 else if (strchr(link
, SEP
) == NULL
)
884 ; /* Link without path */
886 /* Must join(dirname(argv0), link) */
887 char *q
= strrchr(argv0
, SEP
);
889 argv0
= link
; /* argv0 without path */
891 /* Must make a copy */
892 strcpy(argv0copy
, argv0
);
893 q
= strrchr(argv0copy
, SEP
);
899 #endif /* HAVE_READLINK */
900 #if SEP == '\\' /* Special case for MS filename syntax */
901 if (argc
> 0 && argv0
!= NULL
) {
903 p
= strrchr(argv0
, SEP
);
904 /* Test for alternate separator */
905 q
= strrchr(p
? p
: argv0
, '/');
910 if (n
> 1 && p
[-1] != ':')
911 n
--; /* Drop trailing separator */
914 #else /* All other filename syntaxes */
915 if (argc
> 0 && argv0
!= NULL
)
916 p
= strrchr(argv0
, SEP
);
920 #else /* don't include trailing separator */
923 #if SEP == '/' /* Special case for Unix filename syntax */
925 n
--; /* Drop trailing separator */
928 #endif /* All others */
929 a
= PyString_FromStringAndSize(argv0
, n
);
931 Py_FatalError("no mem for sys.path insertion");
932 if (PyList_Insert(path
, 0, a
) < 0)
933 Py_FatalError("sys.path.insert(0) failed");
940 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
941 Adapted from code submitted by Just van Rossum.
943 PySys_WriteStdout(format, ...)
944 PySys_WriteStderr(format, ...)
946 The first function writes to sys.stdout; the second to sys.stderr. When
947 there is a problem, they write to the real (C level) stdout or stderr;
948 no exceptions are raised.
950 Both take a printf-style format string as their first argument followed
951 by a variable length argument list determined by the format string.
955 The format should limit the total size of the formatted output string to
956 1000 bytes. In particular, this means that no unrestricted "%s" formats
957 should occur; these should be limited using "%.<N>s where <N> is a
958 decimal number calculated so that <N> plus the maximum size of other
959 formatted text does not exceed 1000 bytes. Also watch out for "%f",
960 which can print hundreds of digits for very large numbers.
965 mywrite(char *name
, FILE *fp
, const char *format
, va_list va
)
968 PyObject
*error_type
, *error_value
, *error_traceback
;
970 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
971 file
= PySys_GetObject(name
);
972 if (file
== NULL
|| PyFile_AsFile(file
) == fp
)
973 vfprintf(fp
, format
, va
);
976 if (vsprintf(buffer
, format
, va
) >= sizeof(buffer
))
977 Py_FatalError("PySys_WriteStdout/err: buffer overrun");
978 if (PyFile_WriteString(buffer
, file
) != 0) {
983 PyErr_Restore(error_type
, error_value
, error_traceback
);
987 PySys_WriteStdout(const char *format
, ...)
991 va_start(va
, format
);
992 mywrite("stdout", stdout
, format
, va
);
997 PySys_WriteStderr(const char *format
, ...)
1001 va_start(va
, format
);
1002 mywrite("stderr", stderr
, format
, va
);