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