The 0.5 release happened on 2/15, not on 2/14. :-)
[python/dscho.git] / Python / sysmodule.c
bloba7a59333ee45fb5ddb123e7aaad6f070755646b1
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
15 permission.
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* System module */
35 Various bits of information used by the interpreter are collected in
36 module 'sys'.
37 Function member:
38 - exit(sts): raise SystemExit
39 Data members:
40 - stdin, stdout, stderr: standard file objects
41 - modules: the table of modules (dictionary)
42 - path: module search path (list of strings)
43 - argv: script arguments (list of strings)
44 - ps1, ps2: optional primary and secondary prompts (strings)
47 #include "Python.h"
49 #include "osdefs.h"
51 #ifdef HAVE_UNISTD_H
52 #include <unistd.h>
53 #endif
55 #ifdef MS_COREDLL
56 extern void *PyWin_DLLhModule;
57 /* A string loaded from the DLL at startup: */
58 extern const char *PyWin_DLLVersionString;
59 #endif
61 PyObject *
62 PySys_GetObject(name)
63 char *name;
65 PyThreadState *tstate = PyThreadState_Get();
66 PyObject *sd = tstate->interp->sysdict;
67 if (sd == NULL)
68 return NULL;
69 return PyDict_GetItemString(sd, name);
72 FILE *
73 PySys_GetFile(name, def)
74 char *name;
75 FILE *def;
77 FILE *fp = NULL;
78 PyObject *v = PySys_GetObject(name);
79 if (v != NULL && PyFile_Check(v))
80 fp = PyFile_AsFile(v);
81 if (fp == NULL)
82 fp = def;
83 return fp;
86 int
87 PySys_SetObject(name, v)
88 char *name;
89 PyObject *v;
91 PyThreadState *tstate = PyThreadState_Get();
92 PyObject *sd = tstate->interp->sysdict;
93 if (v == NULL) {
94 if (PyDict_GetItemString(sd, name) == NULL)
95 return 0;
96 else
97 return PyDict_DelItemString(sd, name);
99 else
100 return PyDict_SetItemString(sd, name, v);
103 static PyObject *
104 sys_exc_info(self, args)
105 PyObject *self;
106 PyObject *args;
108 PyThreadState *tstate;
109 if (!PyArg_Parse(args, ""))
110 return NULL;
111 tstate = PyThreadState_Get();
112 return Py_BuildValue(
113 "(OOO)",
114 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
115 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
116 tstate->exc_traceback != NULL ?
117 tstate->exc_traceback : Py_None);
120 static char exc_info_doc[] =
121 "exc_info() -> (type, value, traceback)\n\
123 Return information about the exception that is currently being handled.\n\
124 This should be called from inside an except clause only.";
126 static PyObject *
127 sys_exit(self, args)
128 PyObject *self;
129 PyObject *args;
131 /* Raise SystemExit so callers may catch it or clean up. */
132 PyErr_SetObject(PyExc_SystemExit, args);
133 return NULL;
136 static char exit_doc[] =
137 "exit([status])\n\
139 Exit the interpreter by raising SystemExit(status).\n\
140 If the status is omitted or None, it defaults to zero (i.e., success).\n\
141 If the status numeric, it will be used as the system exit status.\n\
142 If it is another kind of object, it will be printed and the system\n\
143 exit status will be one (i.e., failure).";
145 static PyObject *
146 sys_settrace(self, args)
147 PyObject *self;
148 PyObject *args;
150 PyThreadState *tstate = PyThreadState_Get();
151 if (args == Py_None)
152 args = NULL;
153 else
154 Py_XINCREF(args);
155 Py_XDECREF(tstate->sys_tracefunc);
156 tstate->sys_tracefunc = args;
157 Py_INCREF(Py_None);
158 return Py_None;
161 static char settrace_doc[] =
162 "settrace(function)\n\
164 Set the global debug tracing function. It will be called on each\n\
165 function call. See the debugger chapter in the library manual.";
167 static PyObject *
168 sys_setprofile(self, args)
169 PyObject *self;
170 PyObject *args;
172 PyThreadState *tstate = PyThreadState_Get();
173 if (args == Py_None)
174 args = NULL;
175 else
176 Py_XINCREF(args);
177 Py_XDECREF(tstate->sys_profilefunc);
178 tstate->sys_profilefunc = args;
179 Py_INCREF(Py_None);
180 return Py_None;
183 static char setprofile_doc[] =
184 "setprofile(function)\n\
186 Set the profiling function. It will be called on each function call\n\
187 and return. See the profiler chapter in the library manual.";
189 static PyObject *
190 sys_setcheckinterval(self, args)
191 PyObject *self;
192 PyObject *args;
194 PyThreadState *tstate = PyThreadState_Get();
195 if (!PyArg_ParseTuple(args, "i", &tstate->interp->checkinterval))
196 return NULL;
197 Py_INCREF(Py_None);
198 return Py_None;
201 static char setcheckinterval_doc[] =
202 "setcheckinterval(n)\n\
204 Tell the Python interpreter to check for asynchronous events every\n\
205 n instructions. This also affects how often thread switches occur.";
207 #ifdef USE_MALLOPT
208 /* Link with -lmalloc (or -lmpc) on an SGI */
209 #include <malloc.h>
211 static PyObject *
212 sys_mdebug(self, args)
213 PyObject *self;
214 PyObject *args;
216 int flag;
217 if (!PyArg_Parse(args, "i", &flag))
218 return NULL;
219 mallopt(M_DEBUG, flag);
220 Py_INCREF(Py_None);
221 return Py_None;
223 #endif /* USE_MALLOPT */
225 static PyObject *
226 sys_getrefcount(self, args)
227 PyObject *self;
228 PyObject *args;
230 PyObject *arg;
231 if (!PyArg_Parse(args, "O", &arg))
232 return NULL;
233 return PyInt_FromLong((long) arg->ob_refcnt);
236 static char getrefcount_doc[] =
237 "getrefcount(object) -> integer\n\
239 Return the current reference count for the object. This includes the\n\
240 temporary reference in the argument list, so it is at least 2.";
242 #ifdef COUNT_ALLOCS
243 static PyObject *
244 sys_getcounts(self, args)
245 PyObject *self, *args;
247 extern PyObject *get_counts Py_PROTO((void));
249 if (!PyArg_Parse(args, ""))
250 return NULL;
251 return get_counts();
253 #endif
255 #ifdef Py_TRACE_REFS
256 /* Defined in objects.c because it uses static globals if that file */
257 extern PyObject *_Py_GetObjects Py_PROTO((PyObject *, PyObject *));
258 #endif
260 #ifdef DYNAMIC_EXECUTION_PROFILE
261 /* Defined in ceval.c because it uses static globals if that file */
262 extern PyObject *_Py_GetDXProfile Py_PROTO((PyObject *, PyObject *));
263 #endif
265 static PyMethodDef sys_methods[] = {
266 /* Might as well keep this in alphabetic order */
267 {"exc_info", sys_exc_info, 0, exc_info_doc},
268 {"exit", sys_exit, 0, exit_doc},
269 #ifdef COUNT_ALLOCS
270 {"getcounts", sys_getcounts, 0},
271 #endif
272 #ifdef DYNAMIC_EXECUTION_PROFILE
273 {"getdxp", _Py_GetDXProfile, 1},
274 #endif
275 #ifdef Py_TRACE_REFS
276 {"getobjects", _Py_GetObjects, 1},
277 #endif
278 {"getrefcount", sys_getrefcount, 0, getrefcount_doc},
279 #ifdef USE_MALLOPT
280 {"mdebug", sys_mdebug, 0},
281 #endif
282 {"setcheckinterval", sys_setcheckinterval, 1, setcheckinterval_doc},
283 {"setprofile", sys_setprofile, 0, setprofile_doc},
284 {"settrace", sys_settrace, 0, settrace_doc},
285 {NULL, NULL} /* sentinel */
288 static PyObject *
289 list_builtin_module_names()
291 PyObject *list = PyList_New(0);
292 int i;
293 if (list == NULL)
294 return NULL;
295 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
296 PyObject *name = PyString_FromString(
297 PyImport_Inittab[i].name);
298 if (name == NULL)
299 break;
300 PyList_Append(list, name);
301 Py_DECREF(name);
303 if (PyList_Sort(list) != 0) {
304 Py_DECREF(list);
305 list = NULL;
307 if (list) {
308 PyObject *v = PyList_AsTuple(list);
309 Py_DECREF(list);
310 list = v;
312 return list;
315 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
316 Two literals concatenated works just fine. If you have a K&R compiler
317 or other abomination that however *does* understand longer strings,
318 get rid of the !!! comment in the middle and the quotes that surround it. */
319 static char sys_doc[] =
320 "This module provides access to some objects used or maintained by the\n\
321 interpreter and to functions that interact strongly with the interpreter.\n\
323 Dynamic objects:\n\
325 argv -- command line arguments; argv[0] is the script pathname if known\n\
326 path -- module search path; path[0] is the script directory, else ''\n\
327 modules -- dictionary of loaded modules\n\
328 exitfunc -- you may set this to a function to be called when Python exits\n\
330 stdin -- standard input file object; used by raw_input() and input()\n\
331 stdout -- standard output file object; used by the print statement\n\
332 stderr -- standard error object; used for error messages\n\
333 By assigning another file object (or an object that behaves like a file)\n\
334 to one of these, it is possible to redirect all of the interpreter's I/O.\n\
336 last_type -- type of last uncaught exception\n\
337 last_value -- value of last uncaught exception\n\
338 last_traceback -- traceback of last uncaught exception\n\
339 These three are only available in an interactive session after a\n\
340 traceback has been printed.\n\
342 exc_type -- type of exception currently being handled\n\
343 exc_value -- value of exception currently being handled\n\
344 exc_traceback -- traceback of exception currently being handled\n\
345 The function exc_info() should be used instead of these three,\n\
346 because it is thread-safe.\n\
348 #ifndef MS_WIN16
349 /* Concatenating string here */
350 "\n\
351 Static objects:\n\
353 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
354 builtin_module_names -- tuple of module names built into this intepreter\n\
355 version -- the version of this interpreter\n\
356 copyright -- copyright notice pertaining to this interpreter\n\
357 platform -- platform identifier\n\
358 executable -- pathname of this Python interpreter\n\
359 prefix -- prefix used to find the Python library\n\
360 exec_prefix -- prefix used to find the machine-specific Python library\n\
361 dllhandle -- [Windows only] integer handle of the Python DLL\n\
362 winver -- [Windows only] version number of the Python DLL\n\
363 __stdin__ -- the original stdin; don't use!\n\
364 __stdout__ -- the original stdout; don't use!\n\
365 __stderr__ -- the original stderr; don't use!\n\
367 Functions:\n\
369 exc_info() -- return thread-safe information about the current exception\n\
370 exit() -- exit the interpreter by raising SystemExit\n\
371 getrefcount() -- return the reference count for an object (plus one :-)\n\
372 setcheckinterval() -- control how often the interpreter checks for events\n\
373 setprofile() -- set the global profiling function\n\
374 settrace() -- set the global debug tracing function\n\
376 #endif
378 PyObject *
379 _PySys_Init()
381 extern int fclose Py_PROTO((FILE *));
382 PyObject *m, *v, *sysdict;
383 PyObject *sysin, *sysout, *syserr;
385 m = Py_InitModule3("sys", sys_methods, sys_doc);
386 sysdict = PyModule_GetDict(m);
388 sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
389 sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
390 syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
391 if (PyErr_Occurred())
392 return NULL;
393 PyDict_SetItemString(sysdict, "stdin", sysin);
394 PyDict_SetItemString(sysdict, "stdout", sysout);
395 PyDict_SetItemString(sysdict, "stderr", syserr);
396 /* Make backup copies for cleanup */
397 PyDict_SetItemString(sysdict, "__stdin__", sysin);
398 PyDict_SetItemString(sysdict, "__stdout__", sysout);
399 PyDict_SetItemString(sysdict, "__stderr__", syserr);
400 Py_XDECREF(sysin);
401 Py_XDECREF(sysout);
402 Py_XDECREF(syserr);
403 PyDict_SetItemString(sysdict, "version",
404 v = PyString_FromString(Py_GetVersion()));
405 Py_XDECREF(v);
406 PyDict_SetItemString(sysdict, "hexversion",
407 v = PyInt_FromLong(PY_VERSION_HEX));
408 Py_XDECREF(v);
409 PyDict_SetItemString(sysdict, "copyright",
410 v = PyString_FromString(Py_GetCopyright()));
411 Py_XDECREF(v);
412 PyDict_SetItemString(sysdict, "platform",
413 v = PyString_FromString(Py_GetPlatform()));
414 Py_XDECREF(v);
415 PyDict_SetItemString(sysdict, "executable",
416 v = PyString_FromString(Py_GetProgramFullPath()));
417 Py_XDECREF(v);
418 PyDict_SetItemString(sysdict, "prefix",
419 v = PyString_FromString(Py_GetPrefix()));
420 Py_XDECREF(v);
421 PyDict_SetItemString(sysdict, "exec_prefix",
422 v = PyString_FromString(Py_GetExecPrefix()));
423 Py_XDECREF(v);
424 PyDict_SetItemString(sysdict, "maxint",
425 v = PyInt_FromLong(PyInt_GetMax()));
426 Py_XDECREF(v);
427 PyDict_SetItemString(sysdict, "builtin_module_names",
428 v = list_builtin_module_names());
429 Py_XDECREF(v);
430 #ifdef MS_COREDLL
431 PyDict_SetItemString(sysdict, "dllhandle",
432 v = PyInt_FromLong((int)PyWin_DLLhModule));
433 Py_XDECREF(v);
434 PyDict_SetItemString(sysdict, "winver",
435 v = PyString_FromString(PyWin_DLLVersionString));
436 Py_XDECREF(v);
437 #endif
438 if (PyErr_Occurred())
439 return NULL;
440 return m;
443 static PyObject *
444 makepathobject(path, delim)
445 char *path;
446 int delim;
448 int i, n;
449 char *p;
450 PyObject *v, *w;
452 n = 1;
453 p = path;
454 while ((p = strchr(p, delim)) != NULL) {
455 n++;
456 p++;
458 v = PyList_New(n);
459 if (v == NULL)
460 return NULL;
461 for (i = 0; ; i++) {
462 p = strchr(path, delim);
463 if (p == NULL)
464 p = strchr(path, '\0'); /* End of string */
465 w = PyString_FromStringAndSize(path, (int) (p - path));
466 if (w == NULL) {
467 Py_DECREF(v);
468 return NULL;
470 PyList_SetItem(v, i, w);
471 if (*p == '\0')
472 break;
473 path = p+1;
475 return v;
478 void
479 PySys_SetPath(path)
480 char *path;
482 PyObject *v;
483 if ((v = makepathobject(path, DELIM)) == NULL)
484 Py_FatalError("can't create sys.path");
485 if (PySys_SetObject("path", v) != 0)
486 Py_FatalError("can't assign sys.path");
487 Py_DECREF(v);
490 static PyObject *
491 makeargvobject(argc, argv)
492 int argc;
493 char **argv;
495 PyObject *av;
496 if (argc <= 0 || argv == NULL) {
497 /* Ensure at least one (empty) argument is seen */
498 static char *empty_argv[1] = {""};
499 argv = empty_argv;
500 argc = 1;
502 av = PyList_New(argc);
503 if (av != NULL) {
504 int i;
505 for (i = 0; i < argc; i++) {
506 PyObject *v = PyString_FromString(argv[i]);
507 if (v == NULL) {
508 Py_DECREF(av);
509 av = NULL;
510 break;
512 PyList_SetItem(av, i, v);
515 return av;
518 void
519 PySys_SetArgv(argc, argv)
520 int argc;
521 char **argv;
523 PyObject *av = makeargvobject(argc, argv);
524 PyObject *path = PySys_GetObject("path");
525 if (av == NULL)
526 Py_FatalError("no mem for sys.argv");
527 if (PySys_SetObject("argv", av) != 0)
528 Py_FatalError("can't assign sys.argv");
529 if (path != NULL) {
530 char *argv0 = argv[0];
531 char *p = NULL;
532 int n = 0;
533 PyObject *a;
534 #ifdef HAVE_READLINK
535 char link[MAXPATHLEN+1];
536 char argv0copy[2*MAXPATHLEN+1];
537 int nr = 0;
538 if (argc > 0 && argv0 != NULL)
539 nr = readlink(argv0, link, MAXPATHLEN);
540 if (nr > 0) {
541 /* It's a symlink */
542 link[nr] = '\0';
543 if (link[0] == SEP)
544 argv0 = link; /* Link to absolute path */
545 else if (strchr(link, SEP) == NULL)
546 ; /* Link without path */
547 else {
548 /* Must join(dirname(argv0), link) */
549 char *q = strrchr(argv0, SEP);
550 if (q == NULL)
551 argv0 = link; /* argv0 without path */
552 else {
553 /* Must make a copy */
554 strcpy(argv0copy, argv0);
555 q = strrchr(argv0copy, SEP);
556 strcpy(q+1, link);
557 argv0 = argv0copy;
561 #endif /* HAVE_READLINK */
562 #if SEP == '\\' /* Special case for MS filename syntax */
563 if (argc > 0 && argv0 != NULL) {
564 char *q;
565 p = strrchr(argv0, SEP);
566 /* Test for alternate separator */
567 q = strrchr(p ? p : argv0, '/');
568 if (q != NULL)
569 p = q;
570 if (p != NULL) {
571 n = p + 1 - argv0;
572 if (n > 1 && p[-1] != ':')
573 n--; /* Drop trailing separator */
576 #else /* All other filename syntaxes */
577 if (argc > 0 && argv0 != NULL)
578 p = strrchr(argv0, SEP);
579 if (p != NULL) {
580 n = p + 1 - argv0;
581 #if SEP == '/' /* Special case for Unix filename syntax */
582 if (n > 1)
583 n--; /* Drop trailing separator */
584 #endif /* Unix */
586 #endif /* All others */
587 a = PyString_FromStringAndSize(argv0, n);
588 if (a == NULL)
589 Py_FatalError("no mem for sys.path insertion");
590 if (PyList_Insert(path, 0, a) < 0)
591 Py_FatalError("sys.path.insert(0) failed");
592 Py_DECREF(a);
594 Py_DECREF(av);
598 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
599 Adapted from code submitted by Just van Rossum.
601 PySys_WriteStdout(format, ...)
602 PySys_WriteStderr(format, ...)
604 The first function writes to sys.stdout; the second to sys.stderr. When
605 there is a problem, they write to the real (C level) stdout or stderr;
606 no exceptions are raised.
608 Both take a printf-style format string as their first argument followed
609 by a variable length argument list determined by the format string.
611 *** WARNING ***
613 The format should limit the total size of the formatted output string to
614 1000 bytes. In particular, this means that no unrestricted "%s" formats
615 should occur; these should be limited using "%.<N>s where <N> is a
616 decimal number calculated so that <N> plus the maximum size of other
617 formatted text does not exceed 1000 bytes. Also watch out for "%f",
618 which can print hundreds of digits for very large numbers.
622 static void
623 mywrite(name, fp, format, va)
624 char *name;
625 FILE *fp;
626 const char *format;
627 va_list va;
629 PyObject *file;
630 PyObject *error_type, *error_value, *error_traceback;
632 PyErr_Fetch(&error_type, &error_value, &error_traceback);
633 file = PySys_GetObject(name);
634 if (file == NULL || PyFile_AsFile(file) == fp)
635 vfprintf(fp, format, va);
636 else {
637 char buffer[1001];
638 if (vsprintf(buffer, format, va) >= sizeof(buffer))
639 Py_FatalError("PySys_WriteStdout/err: buffer overrun");
640 if (PyFile_WriteString(buffer, file) != 0) {
641 PyErr_Clear();
642 fputs(buffer, fp);
645 PyErr_Restore(error_type, error_value, error_traceback);
648 void
649 #ifdef HAVE_STDARG_PROTOTYPES
650 PySys_WriteStdout(const char *format, ...)
651 #else
652 PySys_WriteStdout(va_alist)
653 va_dcl
654 #endif
656 va_list va;
658 #ifdef HAVE_STDARG_PROTOTYPES
659 va_start(va, format);
660 #else
661 char *format;
662 va_start(va);
663 format = va_arg(va, char *);
664 #endif
665 mywrite("stdout", stdout, format, va);
666 va_end(va);
669 void
670 #ifdef HAVE_STDARG_PROTOTYPES
671 PySys_WriteStderr(const char *format, ...)
672 #else
673 PySys_WriteStderr(va_alist)
674 va_dcl
675 #endif
677 va_list va;
679 #ifdef HAVE_STDARG_PROTOTYPES
680 va_start(va, format);
681 #else
682 char *format;
683 va_start(va);
684 format = va_arg(va, char *);
685 #endif
686 mywrite("stderr", stderr, format, va);
687 va_end(va);