1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
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
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 ******************************************************************/
35 Various bits of information used by the interpreter are collected in
38 - exit(sts): raise SystemExit
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)
56 extern void *PyWin_DLLhModule
;
57 /* A string loaded from the DLL at startup: */
58 extern const char *PyWin_DLLVersionString
;
65 PyThreadState
*tstate
= PyThreadState_Get();
66 PyObject
*sd
= tstate
->interp
->sysdict
;
67 return PyDict_GetItemString(sd
, name
);
71 PySys_GetFile(name
, def
)
76 PyObject
*v
= PySys_GetObject(name
);
77 if (v
!= NULL
&& PyFile_Check(v
))
78 fp
= PyFile_AsFile(v
);
85 PySys_SetObject(name
, v
)
89 PyThreadState
*tstate
= PyThreadState_Get();
90 PyObject
*sd
= tstate
->interp
->sysdict
;
92 if (PyDict_GetItemString(sd
, name
) == NULL
)
95 return PyDict_DelItemString(sd
, name
);
98 return PyDict_SetItemString(sd
, name
, v
);
102 sys_exc_info(self
, args
)
106 PyThreadState
*tstate
;
107 if (!PyArg_Parse(args
, ""))
109 tstate
= PyThreadState_Get();
110 return Py_BuildValue(
112 tstate
->exc_type
!= NULL
? tstate
->exc_type
: Py_None
,
113 tstate
->exc_value
!= NULL
? tstate
->exc_value
: Py_None
,
114 tstate
->exc_traceback
!= NULL
?
115 tstate
->exc_traceback
: Py_None
);
118 static char exc_info_doc
[] =
119 "exc_info() -> (type, value, traceback)\n\
121 Return information about the exception that is currently being handled.\n\
122 This should be called from inside an except clause only.";
129 /* Raise SystemExit so callers may catch it or clean up. */
130 PyErr_SetObject(PyExc_SystemExit
, args
);
134 static char exit_doc
[] =
137 Exit the interpreter by raising SystemExit(status).\n\
138 If the status is omitted or None, it defaults to zero (i.e., success).\n\
139 If the status numeric, it will be used as the system exit status.\n\
140 If it is another kind of object, it will be printed and the system\n\
141 exit status will be one (i.e., failure).";
144 sys_settrace(self
, args
)
148 PyThreadState
*tstate
= PyThreadState_Get();
153 Py_XDECREF(tstate
->sys_tracefunc
);
154 tstate
->sys_tracefunc
= args
;
159 static char settrace_doc
[] =
160 "settrace(function)\n\
162 Set the global debug tracing function. It will be called on each\n\
163 function call. See the debugger chapter in the library manual.";
166 sys_setprofile(self
, args
)
170 PyThreadState
*tstate
= PyThreadState_Get();
175 Py_XDECREF(tstate
->sys_profilefunc
);
176 tstate
->sys_profilefunc
= args
;
181 static char setprofile_doc
[] =
182 "setprofile(function)\n\
184 Set the profiling function. It will be called on each function call\n\
185 and return. See the profiler chapter in the library manual.";
188 sys_setcheckinterval(self
, args
)
192 PyThreadState
*tstate
= PyThreadState_Get();
193 if (!PyArg_ParseTuple(args
, "i", &tstate
->interp
->checkinterval
))
199 static char setcheckinterval_doc
[] =
200 "setcheckinterval(n)\n\
202 Tell the Python interpreter to check for asynchronous events every\n\
203 n instructions. This also affects how often thread switches occur.";
206 /* Link with -lmalloc (or -lmpc) on an SGI */
210 sys_mdebug(self
, args
)
215 if (!PyArg_Parse(args
, "i", &flag
))
217 mallopt(M_DEBUG
, flag
);
221 #endif /* USE_MALLOPT */
224 sys_getrefcount(self
, args
)
229 if (!PyArg_Parse(args
, "O", &arg
))
231 return PyInt_FromLong((long) arg
->ob_refcnt
);
234 static char getrefcount_doc
[] =
235 "getrefcount(object) -> integer\n\
237 Return the current reference count for the object. This includes the\n\
238 temporary reference in the argument list, so it is at least 2.";
242 sys_getcounts(self
, args
)
243 PyObject
*self
, *args
;
245 extern PyObject
*get_counts
Py_PROTO((void));
247 if (!PyArg_Parse(args
, ""))
254 /* Defined in objects.c because it uses static globals if that file */
255 extern PyObject
*_Py_GetObjects
Py_PROTO((PyObject
*, PyObject
*));
258 #ifdef DYNAMIC_EXECUTION_PROFILE
259 /* Defined in ceval.c because it uses static globals if that file */
260 extern PyObject
*_Py_GetDXProfile
Py_PROTO((PyObject
*, PyObject
*));
263 static PyMethodDef sys_methods
[] = {
264 /* Might as well keep this in alphabetic order */
265 {"exc_info", sys_exc_info
, 0, exc_info_doc
},
266 {"exit", sys_exit
, 0, exit_doc
},
268 {"getcounts", sys_getcounts
, 0},
270 #ifdef DYNAMIC_EXECUTION_PROFILE
271 {"getdxp", _Py_GetDXProfile
, 1},
274 {"getobjects", _Py_GetObjects
, 1},
276 {"getrefcount", sys_getrefcount
, 0, getrefcount_doc
},
278 {"mdebug", sys_mdebug
, 0},
280 {"setcheckinterval", sys_setcheckinterval
, 1, setcheckinterval_doc
},
281 {"setprofile", sys_setprofile
, 0, setprofile_doc
},
282 {"settrace", sys_settrace
, 0, settrace_doc
},
283 {NULL
, NULL
} /* sentinel */
287 list_builtin_module_names()
289 PyObject
*list
= PyList_New(0);
293 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
294 PyObject
*name
= PyString_FromString(
295 PyImport_Inittab
[i
].name
);
298 PyList_Append(list
, name
);
301 if (PyList_Sort(list
) != 0) {
306 PyObject
*v
= PyList_AsTuple(list
);
313 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
314 Two literals concatenated works just fine. If you have a K&R compiler
315 or other abomination that however *does* understand longer strings,
316 get rid of the !!! comment in the middle and the quotes that surround it. */
317 static char sys_doc
[] =
318 "This module provides access to some objects used or maintained by the\n\
319 interpreter and to functions that interact strongly with the interpreter.\n\
323 argv -- command line arguments; argv[0] is the script pathname if known\n\
324 path -- module search path; path[0] is the script directory, else ''\n\
325 modules -- dictionary of loaded modules\n\
326 exitfunc -- you may set this to a function to be called when Python exits\n\
328 stdin -- standard input file object; used by raw_input() and input()\n\
329 stdout -- standard output file object; used by the print statement\n\
330 stderr -- standard error object; used for error messages\n\
331 By assigning another file object (or an object that behaves like a file)\n\
332 to one of these, it is possible to redirect all of the interpreter's I/O.\n\
334 last_type -- type of last uncaught exception\n\
335 last_value -- value of last uncaught exception\n\
336 last_traceback -- traceback of last uncaught exception\n\
337 These three are only available in an interactive session after a\n\
338 traceback has been printed.\n\
340 exc_type -- type of exception currently being handled\n\
341 exc_value -- value of exception currently being handled\n\
342 exc_traceback -- traceback of exception currently being handled\n\
343 The function exc_info() should be used instead of these three,\n\
344 because it is thread-safe.\n\
347 /* Concatenating string here */
351 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
352 builtin_module_names -- tuple of module names built into this intepreter\n\
353 version -- the version of this interpreter\n\
354 copyright -- copyright notice pertaining to this interpreter\n\
355 platform -- platform identifier\n\
356 executable -- pathname of this Python interpreter\n\
357 prefix -- prefix used to find the Python library\n\
358 exec_prefix -- prefix used to find the machine-specific Python library\n\
359 dllhandle -- [Windows only] integer handle of the Python DLL\n\
360 winver -- [Windows only] version number of the Python DLL\n\
361 __stdin__ -- the original stdin; don't use!\n\
362 __stdout__ -- the original stdout; don't use!\n\
363 __stderr__ -- the original stderr; don't use!\n\
367 exc_info() -- return thread-safe information about the current exception\n\
368 exit() -- exit the interpreter by raising SystemExit\n\
369 getrefcount() -- return the reference count for an object (plus one :-)\n\
370 setcheckinterval() -- control how often the interpreter checks for events\n\
371 setprofile() -- set the global profiling function\n\
372 settrace() -- set the global debug tracing function\n\
379 extern int fclose
Py_PROTO((FILE *));
380 PyObject
*m
, *v
, *sysdict
;
381 PyObject
*sysin
, *sysout
, *syserr
;
383 m
= Py_InitModule3("sys", sys_methods
, sys_doc
);
384 sysdict
= PyModule_GetDict(m
);
386 sysin
= PyFile_FromFile(stdin
, "<stdin>", "r", NULL
);
387 sysout
= PyFile_FromFile(stdout
, "<stdout>", "w", NULL
);
388 syserr
= PyFile_FromFile(stderr
, "<stderr>", "w", NULL
);
389 if (PyErr_Occurred())
391 PyDict_SetItemString(sysdict
, "stdin", sysin
);
392 PyDict_SetItemString(sysdict
, "stdout", sysout
);
393 PyDict_SetItemString(sysdict
, "stderr", syserr
);
394 /* Make backup copies for cleanup */
395 PyDict_SetItemString(sysdict
, "__stdin__", sysin
);
396 PyDict_SetItemString(sysdict
, "__stdout__", sysout
);
397 PyDict_SetItemString(sysdict
, "__stderr__", syserr
);
401 PyDict_SetItemString(sysdict
, "version",
402 v
= PyString_FromString(Py_GetVersion()));
404 PyDict_SetItemString(sysdict
, "hexversion",
405 v
= PyInt_FromLong(PY_VERSION_HEX
));
407 PyDict_SetItemString(sysdict
, "copyright",
408 v
= PyString_FromString(Py_GetCopyright()));
410 PyDict_SetItemString(sysdict
, "platform",
411 v
= PyString_FromString(Py_GetPlatform()));
413 PyDict_SetItemString(sysdict
, "executable",
414 v
= PyString_FromString(Py_GetProgramFullPath()));
416 PyDict_SetItemString(sysdict
, "prefix",
417 v
= PyString_FromString(Py_GetPrefix()));
419 PyDict_SetItemString(sysdict
, "exec_prefix",
420 v
= PyString_FromString(Py_GetExecPrefix()));
422 PyDict_SetItemString(sysdict
, "maxint",
423 v
= PyInt_FromLong(PyInt_GetMax()));
425 PyDict_SetItemString(sysdict
, "builtin_module_names",
426 v
= list_builtin_module_names());
429 PyDict_SetItemString(sysdict
, "dllhandle",
430 v
= PyInt_FromLong((int)PyWin_DLLhModule
));
432 PyDict_SetItemString(sysdict
, "winver",
433 v
= PyString_FromString(PyWin_DLLVersionString
));
436 if (PyErr_Occurred())
442 makepathobject(path
, delim
)
452 while ((p
= strchr(p
, delim
)) != NULL
) {
460 p
= strchr(path
, delim
);
462 p
= strchr(path
, '\0'); /* End of string */
463 w
= PyString_FromStringAndSize(path
, (int) (p
- path
));
468 PyList_SetItem(v
, i
, w
);
481 if ((v
= makepathobject(path
, DELIM
)) == NULL
)
482 Py_FatalError("can't create sys.path");
483 if (PySys_SetObject("path", v
) != 0)
484 Py_FatalError("can't assign sys.path");
489 makeargvobject(argc
, argv
)
494 if (argc
<= 0 || argv
== NULL
) {
495 /* Ensure at least one (empty) argument is seen */
496 static char *empty_argv
[1] = {""};
500 av
= PyList_New(argc
);
503 for (i
= 0; i
< argc
; i
++) {
504 PyObject
*v
= PyString_FromString(argv
[i
]);
510 PyList_SetItem(av
, i
, v
);
517 PySys_SetArgv(argc
, argv
)
521 PyObject
*av
= makeargvobject(argc
, argv
);
522 PyObject
*path
= PySys_GetObject("path");
524 Py_FatalError("no mem for sys.argv");
525 if (PySys_SetObject("argv", av
) != 0)
526 Py_FatalError("can't assign sys.argv");
528 char *argv0
= argv
[0];
533 char link
[MAXPATHLEN
+1];
534 char argv0copy
[2*MAXPATHLEN
+1];
536 if (argc
> 0 && argv0
!= NULL
)
537 nr
= readlink(argv0
, link
, MAXPATHLEN
);
542 argv0
= link
; /* Link to absolute path */
543 else if (strchr(link
, SEP
) == NULL
)
544 ; /* Link without path */
546 /* Must join(dirname(argv0), link) */
547 char *q
= strrchr(argv0
, SEP
);
549 argv0
= link
; /* argv0 without path */
551 /* Must make a copy */
552 strcpy(argv0copy
, argv0
);
553 q
= strrchr(argv0copy
, SEP
);
559 #endif /* HAVE_READLINK */
560 #if SEP == '\\' /* Special case for MS filename syntax */
561 if (argc
> 0 && argv0
!= NULL
) {
563 p
= strrchr(argv0
, SEP
);
564 /* Test for alternate separator */
565 q
= strrchr(p
? p
: argv0
, '/');
570 if (n
> 1 && p
[-1] != ':')
571 n
--; /* Drop trailing separator */
574 #else /* All other filename syntaxes */
575 if (argc
> 0 && argv0
!= NULL
)
576 p
= strrchr(argv0
, SEP
);
579 #if SEP == '/' /* Special case for Unix filename syntax */
581 n
--; /* Drop trailing separator */
584 #endif /* All others */
585 a
= PyString_FromStringAndSize(argv0
, n
);
587 Py_FatalError("no mem for sys.path insertion");
588 if (PyList_Insert(path
, 0, a
) < 0)
589 Py_FatalError("sys.path.insert(0) failed");
596 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
597 Adapted from code submitted by Just van Rossum.
599 PySys_WriteStdout(format, ...)
600 PySys_WriteStderr(format, ...)
602 The first function writes to sys.stdout; the second to sys.stderr. When
603 there is a problem, they write to the real (C level) stdout or stderr;
604 no exceptions are raised.
606 Both take a printf-style format string as their first argument followed
607 by a variable length argument list determined by the format string.
611 The format should limit the total size of the formatted output string to
612 1000 bytes. In particular, this means that no unrestricted "%s" formats
613 should occur; these should be limited using "%.<N>s where <N> is a
614 decimal number calculated so that <N> plus the maximum size of other
615 formatted text does not exceed 1000 bytes. Also watch out for "%f",
616 which can print hundreds of digits for very large numbers.
621 mywrite(name
, fp
, format
, va
)
628 PyObject
*error_type
, *error_value
, *error_traceback
;
630 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
631 file
= PySys_GetObject(name
);
632 if (file
== NULL
|| PyFile_AsFile(file
) == fp
)
633 vfprintf(fp
, format
, va
);
636 if (vsprintf(buffer
, format
, va
) >= sizeof(buffer
))
637 Py_FatalError("PySys_WriteStdout/err: buffer overrun");
638 if (PyFile_WriteString(buffer
, file
) != 0) {
643 PyErr_Restore(error_type
, error_value
, error_traceback
);
647 #ifdef HAVE_STDARG_PROTOTYPES
648 PySys_WriteStdout(const char *format
, ...)
650 PySys_WriteStdout(va_alist
)
656 #ifdef HAVE_STDARG_PROTOTYPES
657 va_start(va
, format
);
661 format
= va_arg(va
, char *);
663 mywrite("stdout", stdout
, format
, va
);
668 #ifdef HAVE_STDARG_PROTOTYPES
669 PySys_WriteStderr(const char *format
, ...)
671 PySys_WriteStderr(va_alist
)
677 #ifdef HAVE_STDARG_PROTOTYPES
678 va_start(va
, format
);
682 format
= va_arg(va
, char *);
684 mywrite("stderr", stderr
, format
, va
);