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
;
69 return PyDict_GetItemString(sd
, name
);
73 PySys_GetFile(name
, def
)
78 PyObject
*v
= PySys_GetObject(name
);
79 if (v
!= NULL
&& PyFile_Check(v
))
80 fp
= PyFile_AsFile(v
);
87 PySys_SetObject(name
, v
)
91 PyThreadState
*tstate
= PyThreadState_Get();
92 PyObject
*sd
= tstate
->interp
->sysdict
;
94 if (PyDict_GetItemString(sd
, name
) == NULL
)
97 return PyDict_DelItemString(sd
, name
);
100 return PyDict_SetItemString(sd
, name
, v
);
104 sys_exc_info(self
, args
)
108 PyThreadState
*tstate
;
109 if (!PyArg_Parse(args
, ""))
111 tstate
= PyThreadState_Get();
112 return Py_BuildValue(
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.";
131 /* Raise SystemExit so callers may catch it or clean up. */
132 PyErr_SetObject(PyExc_SystemExit
, args
);
136 static char exit_doc
[] =
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).";
146 sys_settrace(self
, args
)
150 PyThreadState
*tstate
= PyThreadState_Get();
155 Py_XDECREF(tstate
->sys_tracefunc
);
156 tstate
->sys_tracefunc
= args
;
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.";
168 sys_setprofile(self
, args
)
172 PyThreadState
*tstate
= PyThreadState_Get();
177 Py_XDECREF(tstate
->sys_profilefunc
);
178 tstate
->sys_profilefunc
= args
;
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.";
190 sys_setcheckinterval(self
, args
)
194 PyThreadState
*tstate
= PyThreadState_Get();
195 if (!PyArg_ParseTuple(args
, "i", &tstate
->interp
->checkinterval
))
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.";
208 /* Link with -lmalloc (or -lmpc) on an SGI */
212 sys_mdebug(self
, args
)
217 if (!PyArg_Parse(args
, "i", &flag
))
219 mallopt(M_DEBUG
, flag
);
223 #endif /* USE_MALLOPT */
226 sys_getrefcount(self
, args
)
231 if (!PyArg_Parse(args
, "O", &arg
))
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.";
244 sys_getcounts(self
, args
)
245 PyObject
*self
, *args
;
247 extern PyObject
*get_counts
Py_PROTO((void));
249 if (!PyArg_Parse(args
, ""))
256 /* Defined in objects.c because it uses static globals if that file */
257 extern PyObject
*_Py_GetObjects
Py_PROTO((PyObject
*, PyObject
*));
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
*));
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
},
270 {"getcounts", sys_getcounts
, 0},
272 #ifdef DYNAMIC_EXECUTION_PROFILE
273 {"getdxp", _Py_GetDXProfile
, 1},
276 {"getobjects", _Py_GetObjects
, 1},
278 {"getrefcount", sys_getrefcount
, 0, getrefcount_doc
},
280 {"mdebug", sys_mdebug
, 0},
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 */
289 list_builtin_module_names()
291 PyObject
*list
= PyList_New(0);
295 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
296 PyObject
*name
= PyString_FromString(
297 PyImport_Inittab
[i
].name
);
300 PyList_Append(list
, name
);
303 if (PyList_Sort(list
) != 0) {
308 PyObject
*v
= PyList_AsTuple(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\
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\
349 /* Concatenating string here */
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\
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\
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())
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
);
403 PyDict_SetItemString(sysdict
, "version",
404 v
= PyString_FromString(Py_GetVersion()));
406 PyDict_SetItemString(sysdict
, "hexversion",
407 v
= PyInt_FromLong(PY_VERSION_HEX
));
409 PyDict_SetItemString(sysdict
, "copyright",
410 v
= PyString_FromString(Py_GetCopyright()));
412 PyDict_SetItemString(sysdict
, "platform",
413 v
= PyString_FromString(Py_GetPlatform()));
415 PyDict_SetItemString(sysdict
, "executable",
416 v
= PyString_FromString(Py_GetProgramFullPath()));
418 PyDict_SetItemString(sysdict
, "prefix",
419 v
= PyString_FromString(Py_GetPrefix()));
421 PyDict_SetItemString(sysdict
, "exec_prefix",
422 v
= PyString_FromString(Py_GetExecPrefix()));
424 PyDict_SetItemString(sysdict
, "maxint",
425 v
= PyInt_FromLong(PyInt_GetMax()));
427 PyDict_SetItemString(sysdict
, "builtin_module_names",
428 v
= list_builtin_module_names());
431 PyDict_SetItemString(sysdict
, "dllhandle",
432 v
= PyInt_FromLong((int)PyWin_DLLhModule
));
434 PyDict_SetItemString(sysdict
, "winver",
435 v
= PyString_FromString(PyWin_DLLVersionString
));
438 if (PyErr_Occurred())
444 makepathobject(path
, delim
)
454 while ((p
= strchr(p
, delim
)) != NULL
) {
462 p
= strchr(path
, delim
);
464 p
= strchr(path
, '\0'); /* End of string */
465 w
= PyString_FromStringAndSize(path
, (int) (p
- path
));
470 PyList_SetItem(v
, i
, w
);
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");
491 makeargvobject(argc
, argv
)
496 if (argc
<= 0 || argv
== NULL
) {
497 /* Ensure at least one (empty) argument is seen */
498 static char *empty_argv
[1] = {""};
502 av
= PyList_New(argc
);
505 for (i
= 0; i
< argc
; i
++) {
506 PyObject
*v
= PyString_FromString(argv
[i
]);
512 PyList_SetItem(av
, i
, v
);
519 PySys_SetArgv(argc
, argv
)
523 PyObject
*av
= makeargvobject(argc
, argv
);
524 PyObject
*path
= PySys_GetObject("path");
526 Py_FatalError("no mem for sys.argv");
527 if (PySys_SetObject("argv", av
) != 0)
528 Py_FatalError("can't assign sys.argv");
530 char *argv0
= argv
[0];
535 char link
[MAXPATHLEN
+1];
536 char argv0copy
[2*MAXPATHLEN
+1];
538 if (argc
> 0 && argv0
!= NULL
)
539 nr
= readlink(argv0
, link
, MAXPATHLEN
);
544 argv0
= link
; /* Link to absolute path */
545 else if (strchr(link
, SEP
) == NULL
)
546 ; /* Link without path */
548 /* Must join(dirname(argv0), link) */
549 char *q
= strrchr(argv0
, SEP
);
551 argv0
= link
; /* argv0 without path */
553 /* Must make a copy */
554 strcpy(argv0copy
, argv0
);
555 q
= strrchr(argv0copy
, SEP
);
561 #endif /* HAVE_READLINK */
562 #if SEP == '\\' /* Special case for MS filename syntax */
563 if (argc
> 0 && argv0
!= NULL
) {
565 p
= strrchr(argv0
, SEP
);
566 /* Test for alternate separator */
567 q
= strrchr(p
? p
: 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
);
581 #if SEP == '/' /* Special case for Unix filename syntax */
583 n
--; /* Drop trailing separator */
586 #endif /* All others */
587 a
= PyString_FromStringAndSize(argv0
, n
);
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");
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.
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.
623 mywrite(name
, fp
, format
, va
)
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
);
638 if (vsprintf(buffer
, format
, va
) >= sizeof(buffer
))
639 Py_FatalError("PySys_WriteStdout/err: buffer overrun");
640 if (PyFile_WriteString(buffer
, file
) != 0) {
645 PyErr_Restore(error_type
, error_value
, error_traceback
);
649 #ifdef HAVE_STDARG_PROTOTYPES
650 PySys_WriteStdout(const char *format
, ...)
652 PySys_WriteStdout(va_alist
)
658 #ifdef HAVE_STDARG_PROTOTYPES
659 va_start(va
, format
);
663 format
= va_arg(va
, char *);
665 mywrite("stdout", stdout
, format
, va
);
670 #ifdef HAVE_STDARG_PROTOTYPES
671 PySys_WriteStderr(const char *format
, ...)
673 PySys_WriteStderr(va_alist
)
679 #ifdef HAVE_STDARG_PROTOTYPES
680 va_start(va
, format
);
684 format
= va_arg(va
, char *);
686 mywrite("stderr", stderr
, format
, va
);