blob: 7a1933d994bfa63edcb8fcdbc314bf39345fef97 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020020#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossume2437a11992-03-23 18:20:18 +000022#include "osdefs.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Mark Hammond8696ebc2002-10-08 02:44:31 +000024#ifdef MS_WINDOWS
25#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000026#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000027#endif /* MS_WINDOWS */
28
Guido van Rossum9b38a141996-09-11 23:12:24 +000029#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000030extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000031/* A string loaded from the DLL at startup: */
32extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000033#endif
34
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +000035#ifdef __VMS
36#include <unixlib.h>
37#endif
38
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000039#ifdef HAVE_LANGINFO_H
40#include <locale.h>
41#include <langinfo.h>
42#endif
43
Guido van Rossum65bf9f21997-04-29 18:33:38 +000044PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000045PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 PyThreadState *tstate = PyThreadState_GET();
48 PyObject *sd = tstate->interp->sysdict;
49 if (sd == NULL)
50 return NULL;
51 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000052}
53
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054int
Neal Norwitzf3081322007-08-25 00:32:45 +000055PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 PyThreadState *tstate = PyThreadState_GET();
58 PyObject *sd = tstate->interp->sysdict;
59 if (v == NULL) {
60 if (PyDict_GetItemString(sd, name) == NULL)
61 return 0;
62 else
63 return PyDict_DelItemString(sd, name);
64 }
65 else
66 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067}
68
Victor Stinner13d49ee2010-12-04 17:24:33 +000069/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
70 error handler. If sys.stdout has a buffer attribute, use
71 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
72 sys.stdout.write(redecoded).
73
74 Helper function for sys_displayhook(). */
75static int
76sys_displayhook_unencodable(PyObject *outf, PyObject *o)
77{
78 PyObject *stdout_encoding = NULL;
79 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
80 char *stdout_encoding_str;
81 int ret;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020082 _Py_IDENTIFIER(encoding);
83 _Py_IDENTIFIER(buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +000084
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +020085 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +000086 if (stdout_encoding == NULL)
87 goto error;
88 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
89 if (stdout_encoding_str == NULL)
90 goto error;
91
92 repr_str = PyObject_Repr(o);
93 if (repr_str == NULL)
94 goto error;
95 encoded = PyUnicode_AsEncodedString(repr_str,
96 stdout_encoding_str,
97 "backslashreplace");
98 Py_DECREF(repr_str);
99 if (encoded == NULL)
100 goto error;
101
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200102 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000103 if (buffer) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200104 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200105 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000106 Py_DECREF(buffer);
107 Py_DECREF(encoded);
108 if (result == NULL)
109 goto error;
110 Py_DECREF(result);
111 }
112 else {
113 PyErr_Clear();
114 escaped_str = PyUnicode_FromEncodedObject(encoded,
115 stdout_encoding_str,
116 "strict");
117 Py_DECREF(encoded);
118 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
119 Py_DECREF(escaped_str);
120 goto error;
121 }
122 Py_DECREF(escaped_str);
123 }
124 ret = 0;
125 goto finally;
126
127error:
128 ret = -1;
129finally:
130 Py_XDECREF(stdout_encoding);
131 return ret;
132}
133
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000134static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000135sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyObject *outf;
138 PyInterpreterState *interp = PyThreadState_GET()->interp;
139 PyObject *modules = interp->modules;
140 PyObject *builtins = PyDict_GetItemString(modules, "builtins");
Victor Stinner13d49ee2010-12-04 17:24:33 +0000141 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (builtins == NULL) {
144 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
145 return NULL;
146 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 /* Print value except if None */
149 /* After printing, also assign to '_' */
150 /* Before, set '_' to None to avoid recursion */
151 if (o == Py_None) {
152 Py_INCREF(Py_None);
153 return Py_None;
154 }
155 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
156 return NULL;
157 outf = PySys_GetObject("stdout");
158 if (outf == NULL || outf == Py_None) {
159 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
160 return NULL;
161 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000162 if (PyFile_WriteObject(o, outf, 0) != 0) {
163 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
164 /* repr(o) is not encodable to sys.stdout.encoding with
165 * sys.stdout.errors error handler (which is probably 'strict') */
166 PyErr_Clear();
167 err = sys_displayhook_unencodable(outf, o);
168 if (err)
169 return NULL;
170 }
171 else {
172 return NULL;
173 }
174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (PyFile_WriteString("\n", outf) != 0)
176 return NULL;
177 if (PyObject_SetAttrString(builtins, "_", o) != 0)
178 return NULL;
179 Py_INCREF(Py_None);
180 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000181}
182
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000183PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000184"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000185"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000186"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000187);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000188
189static PyObject *
190sys_excepthook(PyObject* self, PyObject* args)
191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyObject *exc, *value, *tb;
193 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
194 return NULL;
195 PyErr_Display(exc, value, tb);
196 Py_INCREF(Py_None);
197 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000198}
199
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000200PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000201"excepthook(exctype, value, traceback) -> None\n"
202"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000203"Handle an exception by displaying it with a traceback on sys.stderr.\n"
204);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000205
206static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000207sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 PyThreadState *tstate;
210 tstate = PyThreadState_GET();
211 return Py_BuildValue(
212 "(OOO)",
213 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
214 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
215 tstate->exc_traceback != NULL ?
216 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000217}
218
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000219PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000220"exc_info() -> (type, value, traceback)\n\
221\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000222Return information about the most recent exception caught by an except\n\
223clause in the current stack frame or in an older stack frame."
224);
225
226static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000227sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyObject *exit_code = 0;
230 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
231 return NULL;
232 /* Raise SystemExit so callers may catch it or clean up. */
233 PyErr_SetObject(PyExc_SystemExit, exit_code);
234 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235}
236
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000237PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000238"exit([status])\n\
239\n\
240Exit the interpreter by raising SystemExit(status).\n\
241If the status is omitted or None, it defaults to zero (i.e., success).\n\
Neil Schemenauer0f2103f2002-03-23 20:46:35 +0000242If the status is numeric, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000243If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000244exit status will be one (i.e., failure)."
245);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000246
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000247
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000248static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000249sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000252}
253
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000254PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000255"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000256\n\
257Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000258implementation."
259);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000260
261static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000262sys_getfilesystemencoding(PyObject *self)
263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (Py_FileSystemDefaultEncoding)
265 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200266 PyErr_SetString(PyExc_RuntimeError,
267 "filesystem encoding is not initialized");
268 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000269}
270
271PyDoc_STRVAR(getfilesystemencoding_doc,
272"getfilesystemencoding() -> string\n\
273\n\
274Return the encoding used to convert Unicode filenames in\n\
275operating system filenames."
276);
277
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000278static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000279sys_intern(PyObject *self, PyObject *args)
280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *s;
282 if (!PyArg_ParseTuple(args, "U:intern", &s))
283 return NULL;
284 if (PyUnicode_CheckExact(s)) {
285 Py_INCREF(s);
286 PyUnicode_InternInPlace(&s);
287 return s;
288 }
289 else {
290 PyErr_Format(PyExc_TypeError,
291 "can't intern %.400s", s->ob_type->tp_name);
292 return NULL;
293 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000294}
295
296PyDoc_STRVAR(intern_doc,
297"intern(string) -> string\n\
298\n\
299``Intern'' the given string. This enters the string in the (global)\n\
300table of interned strings whose purpose is to speed up dictionary lookups.\n\
301Return the string itself or the previously interned string object with the\n\
302same value.");
303
304
Fred Drake5755ce62001-06-27 19:19:46 +0000305/*
306 * Cached interned string objects used for calling the profile and
307 * trace functions. Initialized by trace_init().
308 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000309static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000310
311static int
312trace_init(void)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 static char *whatnames[7] = {"call", "exception", "line", "return",
315 "c_call", "c_exception", "c_return"};
316 PyObject *name;
317 int i;
318 for (i = 0; i < 7; ++i) {
319 if (whatstrings[i] == NULL) {
320 name = PyUnicode_InternFromString(whatnames[i]);
321 if (name == NULL)
322 return -1;
323 whatstrings[i] = name;
324 }
325 }
326 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000327}
328
329
330static PyObject *
331call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *args = PyTuple_New(3);
335 PyObject *whatstr;
336 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (args == NULL)
339 return NULL;
340 Py_INCREF(frame);
341 whatstr = whatstrings[what];
342 Py_INCREF(whatstr);
343 if (arg == NULL)
344 arg = Py_None;
345 Py_INCREF(arg);
346 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
347 PyTuple_SET_ITEM(args, 1, whatstr);
348 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 /* call the Python-level function */
351 PyFrame_FastToLocals(frame);
352 result = PyEval_CallObject(callback, args);
353 PyFrame_LocalsToFast(frame, 1);
354 if (result == NULL)
355 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 /* cleanup */
358 Py_DECREF(args);
359 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000360}
361
362static int
363profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 PyThreadState *tstate = frame->f_tstate;
367 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (arg == NULL)
370 arg = Py_None;
371 result = call_trampoline(tstate, self, frame, what, arg);
372 if (result == NULL) {
373 PyEval_SetProfile(NULL, NULL);
374 return -1;
375 }
376 Py_DECREF(result);
377 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000378}
379
380static int
381trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyThreadState *tstate = frame->f_tstate;
385 PyObject *callback;
386 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (what == PyTrace_CALL)
389 callback = self;
390 else
391 callback = frame->f_trace;
392 if (callback == NULL)
393 return 0;
394 result = call_trampoline(tstate, callback, frame, what, arg);
395 if (result == NULL) {
396 PyEval_SetTrace(NULL, NULL);
397 Py_XDECREF(frame->f_trace);
398 frame->f_trace = NULL;
399 return -1;
400 }
401 if (result != Py_None) {
402 PyObject *temp = frame->f_trace;
403 frame->f_trace = NULL;
404 Py_XDECREF(temp);
405 frame->f_trace = result;
406 }
407 else {
408 Py_DECREF(result);
409 }
410 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000411}
Fred Draked0838392001-06-16 21:02:31 +0000412
Fred Drake8b4d01d2000-05-09 19:57:01 +0000413static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000414sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (trace_init() == -1)
417 return NULL;
418 if (args == Py_None)
419 PyEval_SetTrace(NULL, NULL);
420 else
421 PyEval_SetTrace(trace_trampoline, args);
422 Py_INCREF(Py_None);
423 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000424}
425
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000426PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000427"settrace(function)\n\
428\n\
429Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000430function call. See the debugger chapter in the library manual."
431);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000432
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000433static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000434sys_gettrace(PyObject *self, PyObject *args)
435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyThreadState *tstate = PyThreadState_GET();
437 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (temp == NULL)
440 temp = Py_None;
441 Py_INCREF(temp);
442 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000443}
444
445PyDoc_STRVAR(gettrace_doc,
446"gettrace()\n\
447\n\
448Return the global debug tracing function set with sys.settrace.\n\
449See the debugger chapter in the library manual."
450);
451
452static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000453sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (trace_init() == -1)
456 return NULL;
457 if (args == Py_None)
458 PyEval_SetProfile(NULL, NULL);
459 else
460 PyEval_SetProfile(profile_trampoline, args);
461 Py_INCREF(Py_None);
462 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000463}
464
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000465PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000466"setprofile(function)\n\
467\n\
468Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000469and return. See the profiler chapter in the library manual."
470);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000471
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000472static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000473sys_getprofile(PyObject *self, PyObject *args)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyThreadState *tstate = PyThreadState_GET();
476 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (temp == NULL)
479 temp = Py_None;
480 Py_INCREF(temp);
481 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000482}
483
484PyDoc_STRVAR(getprofile_doc,
485"getprofile()\n\
486\n\
487Return the profiling function set with sys.setprofile.\n\
488See the profiler chapter in the library manual."
489);
490
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000491static int _check_interval = 100;
492
Christian Heimes9bd667a2008-01-20 15:14:11 +0000493static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000494sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (PyErr_WarnEx(PyExc_DeprecationWarning,
497 "sys.getcheckinterval() and sys.setcheckinterval() "
498 "are deprecated. Use sys.setswitchinterval() "
499 "instead.", 1) < 0)
500 return NULL;
501 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
502 return NULL;
503 Py_INCREF(Py_None);
504 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000505}
506
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000507PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508"setcheckinterval(n)\n\
509\n\
510Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000511n instructions. This also affects how often thread switches occur."
512);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000513
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000514static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000515sys_getcheckinterval(PyObject *self, PyObject *args)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (PyErr_WarnEx(PyExc_DeprecationWarning,
518 "sys.getcheckinterval() and sys.setcheckinterval() "
519 "are deprecated. Use sys.getswitchinterval() "
520 "instead.", 1) < 0)
521 return NULL;
522 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000523}
524
525PyDoc_STRVAR(getcheckinterval_doc,
526"getcheckinterval() -> current check interval; see setcheckinterval()."
527);
528
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000529#ifdef WITH_THREAD
530static PyObject *
531sys_setswitchinterval(PyObject *self, PyObject *args)
532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 double d;
534 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
535 return NULL;
536 if (d <= 0.0) {
537 PyErr_SetString(PyExc_ValueError,
538 "switch interval must be strictly positive");
539 return NULL;
540 }
541 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
542 Py_INCREF(Py_None);
543 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000544}
545
546PyDoc_STRVAR(setswitchinterval_doc,
547"setswitchinterval(n)\n\
548\n\
549Set the ideal thread switching delay inside the Python interpreter\n\
550The actual frequency of switching threads can be lower if the\n\
551interpreter executes long sequences of uninterruptible code\n\
552(this is implementation-specific and workload-dependent).\n\
553\n\
554The parameter must represent the desired switching delay in seconds\n\
555A typical value is 0.005 (5 milliseconds)."
556);
557
558static PyObject *
559sys_getswitchinterval(PyObject *self, PyObject *args)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000562}
563
564PyDoc_STRVAR(getswitchinterval_doc,
565"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
566);
567
568#endif /* WITH_THREAD */
569
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000570#ifdef WITH_TSC
571static PyObject *
572sys_settscdump(PyObject *self, PyObject *args)
573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 int bool;
575 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
578 return NULL;
579 if (bool)
580 tstate->interp->tscdump = 1;
581 else
582 tstate->interp->tscdump = 0;
583 Py_INCREF(Py_None);
584 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000585
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000586}
587
Tim Peters216b78b2006-01-06 02:40:53 +0000588PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000589"settscdump(bool)\n\
590\n\
591If true, tell the Python interpreter to dump VM measurements to\n\
592stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000593processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000594);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000595#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000596
Tim Peterse5e065b2003-07-06 18:36:54 +0000597static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000598sys_setrecursionlimit(PyObject *self, PyObject *args)
599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 int new_limit;
601 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
602 return NULL;
603 if (new_limit <= 0) {
604 PyErr_SetString(PyExc_ValueError,
605 "recursion limit must be positive");
606 return NULL;
607 }
608 Py_SetRecursionLimit(new_limit);
609 Py_INCREF(Py_None);
610 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000611}
612
Mark Dickinsondc787d22010-05-23 13:33:13 +0000613static PyTypeObject Hash_InfoType;
614
615PyDoc_STRVAR(hash_info_doc,
616"hash_info\n\
617\n\
618A struct sequence providing parameters used for computing\n\
619numeric hashes. The attributes are read only.");
620
621static PyStructSequence_Field hash_info_fields[] = {
622 {"width", "width of the type used for hashing, in bits"},
623 {"modulus", "prime number giving the modulus on which the hash "
624 "function is based"},
625 {"inf", "value to be used for hash of a positive infinity"},
626 {"nan", "value to be used for hash of a nan"},
627 {"imag", "multiplier used for the imaginary part of a complex number"},
628 {NULL, NULL}
629};
630
631static PyStructSequence_Desc hash_info_desc = {
632 "sys.hash_info",
633 hash_info_doc,
634 hash_info_fields,
635 5,
636};
637
Matthias Klosed885e952010-07-06 10:53:30 +0000638static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000639get_hash_info(void)
640{
641 PyObject *hash_info;
642 int field = 0;
643 hash_info = PyStructSequence_New(&Hash_InfoType);
644 if (hash_info == NULL)
645 return NULL;
646 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000647 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000648 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000649 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000650 PyStructSequence_SET_ITEM(hash_info, field++,
651 PyLong_FromLong(_PyHASH_INF));
652 PyStructSequence_SET_ITEM(hash_info, field++,
653 PyLong_FromLong(_PyHASH_NAN));
654 PyStructSequence_SET_ITEM(hash_info, field++,
655 PyLong_FromLong(_PyHASH_IMAG));
656 if (PyErr_Occurred()) {
657 Py_CLEAR(hash_info);
658 return NULL;
659 }
660 return hash_info;
661}
662
663
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000664PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000665"setrecursionlimit(n)\n\
666\n\
667Set the maximum depth of the Python interpreter stack to n. This\n\
668limit prevents infinite recursion from causing an overflow of the C\n\
669stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000670dependent."
671);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000672
673static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000674sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000677}
678
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000679PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000680"getrecursionlimit()\n\
681\n\
682Return the current value of the recursion limit, the maximum depth\n\
683of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000684recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000685);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000686
Mark Hammond8696ebc2002-10-08 02:44:31 +0000687#ifdef MS_WINDOWS
688PyDoc_STRVAR(getwindowsversion_doc,
689"getwindowsversion()\n\
690\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000691Return information about the running version of Windows as a named tuple.\n\
692The members are named: major, minor, build, platform, service_pack,\n\
693service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200694backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000695All elements are numbers, except service_pack which is a string. Platform\n\
696may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6973 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
698controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000699);
700
Eric Smithf7bb5782010-01-27 00:44:57 +0000701static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
702
703static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 {"major", "Major version number"},
705 {"minor", "Minor version number"},
706 {"build", "Build number"},
707 {"platform", "Operating system platform"},
708 {"service_pack", "Latest Service Pack installed on the system"},
709 {"service_pack_major", "Service Pack major version number"},
710 {"service_pack_minor", "Service Pack minor version number"},
711 {"suite_mask", "Bit mask identifying available product suites"},
712 {"product_type", "System product type"},
713 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000714};
715
716static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 "sys.getwindowsversion", /* name */
718 getwindowsversion_doc, /* doc */
719 windows_version_fields, /* fields */
720 5 /* For backward compatibility,
721 only the first 5 items are accessible
722 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000723};
724
Mark Hammond8696ebc2002-10-08 02:44:31 +0000725static PyObject *
726sys_getwindowsversion(PyObject *self)
727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyObject *version;
729 int pos = 0;
730 OSVERSIONINFOEX ver;
731 ver.dwOSVersionInfoSize = sizeof(ver);
732 if (!GetVersionEx((OSVERSIONINFO*) &ver))
733 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 version = PyStructSequence_New(&WindowsVersionType);
736 if (version == NULL)
737 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
740 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
741 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
742 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
743 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
744 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
745 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
746 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
747 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000750}
751
752#endif /* MS_WINDOWS */
753
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000754#ifdef HAVE_DLOPEN
755static PyObject *
756sys_setdlopenflags(PyObject *self, PyObject *args)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 int new_val;
759 PyThreadState *tstate = PyThreadState_GET();
760 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
761 return NULL;
762 if (!tstate)
763 return NULL;
764 tstate->interp->dlopenflags = new_val;
765 Py_INCREF(Py_None);
766 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000767}
768
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000769PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000770"setdlopenflags(n) -> None\n\
771\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000772Set the flags used by the interpreter for dlopen calls, such as when the\n\
773interpreter loads extension modules. Among other things, this will enable\n\
774a lazy resolving of symbols when importing a module, if called as\n\
775sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
776sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
777can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
778is not available, it can be generated from /usr/include/dlfcn.h using the\n\
779h2py script.");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000780
781static PyObject *
782sys_getdlopenflags(PyObject *self, PyObject *args)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyThreadState *tstate = PyThreadState_GET();
785 if (!tstate)
786 return NULL;
787 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000788}
789
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000790PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000791"getdlopenflags() -> int\n\
792\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000793Return the current value of the flags that are used for dlopen calls.\n\
794The flag constants are defined in the ctypes and DLFCN modules.");
795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000797
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000798#ifdef USE_MALLOPT
799/* Link with -lmalloc (or -lmpc) on an SGI */
800#include <malloc.h>
801
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000802static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000803sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 int flag;
806 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
807 return NULL;
808 mallopt(M_DEBUG, flag);
809 Py_INCREF(Py_None);
810 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000811}
812#endif /* USE_MALLOPT */
813
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000814static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000815sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject *res = NULL;
818 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
819 static char *kwlist[] = {"object", "default", 0};
820 PyObject *o, *dflt = NULL;
821 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
824 kwlist, &o, &dflt))
825 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Initialize static variable for GC head size */
828 if (gc_head_size == NULL) {
829 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
830 if (gc_head_size == NULL)
831 return NULL;
832 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* Make sure the type is initialized. float gets initialized late */
835 if (PyType_Ready(Py_TYPE(o)) < 0)
836 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 method = _PyObject_LookupSpecial(o, "__sizeof__",
839 &str__sizeof__);
840 if (method == NULL) {
841 if (!PyErr_Occurred())
842 PyErr_Format(PyExc_TypeError,
843 "Type %.100s doesn't define __sizeof__",
844 Py_TYPE(o)->tp_name);
845 }
846 else {
847 res = PyObject_CallFunctionObjArgs(method, NULL);
848 Py_DECREF(method);
849 }
850
851 /* Has a default value been given */
852 if ((res == NULL) && (dflt != NULL) &&
853 PyErr_ExceptionMatches(PyExc_TypeError))
854 {
855 PyErr_Clear();
856 Py_INCREF(dflt);
857 return dflt;
858 }
859 else if (res == NULL)
860 return res;
861
862 /* add gc_head size */
863 if (PyObject_IS_GC(o)) {
864 PyObject *tmp = res;
865 res = PyNumber_Add(tmp, gc_head_size);
866 Py_DECREF(tmp);
867 }
868 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000869}
870
871PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000872"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000873\n\
874Return the size of object in bytes.");
875
876static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000877sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000880}
881
Tim Peters4be93d02002-07-07 19:59:50 +0000882#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000883static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000884sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000887}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000888#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000889
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000890PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000891"getrefcount(object) -> integer\n\
892\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000893Return the reference count of object. The count returned is generally\n\
894one higher than you might expect, because it includes the (temporary)\n\
895reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000896);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000897
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000898#ifdef COUNT_ALLOCS
899static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000900sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000905}
906#endif
907
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000908PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000909"_getframe([depth]) -> frameobject\n\
910\n\
911Return a frame object from the call stack. If optional integer depth is\n\
912given, return the frame object that many calls below the top of the stack.\n\
913If that is deeper than the call stack, ValueError is raised. The default\n\
914for depth is zero, returning the frame at the top of the call stack.\n\
915\n\
916This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000917purposes only."
918);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000919
920static PyObject *
921sys_getframe(PyObject *self, PyObject *args)
922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyFrameObject *f = PyThreadState_GET()->frame;
924 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
927 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 while (depth > 0 && f != NULL) {
930 f = f->f_back;
931 --depth;
932 }
933 if (f == NULL) {
934 PyErr_SetString(PyExc_ValueError,
935 "call stack is not deep enough");
936 return NULL;
937 }
938 Py_INCREF(f);
939 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000940}
941
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000942PyDoc_STRVAR(current_frames_doc,
943"_current_frames() -> dictionary\n\
944\n\
945Return a dictionary mapping each current thread T's thread id to T's\n\
946current stack frame.\n\
947\n\
948This function should be used for specialized purposes only."
949);
950
951static PyObject *
952sys_current_frames(PyObject *self, PyObject *noargs)
953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000955}
956
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000957PyDoc_STRVAR(call_tracing_doc,
958"call_tracing(func, args) -> object\n\
959\n\
960Call func(*args), while tracing is enabled. The tracing state is\n\
961saved, and restored afterwards. This is intended to be called from\n\
962a debugger from a checkpoint, to recursively debug some other code."
963);
964
965static PyObject *
966sys_call_tracing(PyObject *self, PyObject *args)
967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyObject *func, *funcargs;
969 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
970 return NULL;
971 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000972}
973
Jeremy Hylton985eba52003-02-05 23:13:00 +0000974PyDoc_STRVAR(callstats_doc,
975"callstats() -> tuple of integers\n\
976\n\
977Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
978when Python was built. Otherwise, return None.\n\
979\n\
980When enabled, this function returns detailed, implementation-specific\n\
981details about the number of function calls executed. The return value is\n\
982a 11-tuple where the entries in the tuple are counts of:\n\
9830. all function calls\n\
9841. calls to PyFunction_Type objects\n\
9852. PyFunction calls that do not create an argument tuple\n\
9863. PyFunction calls that do not create an argument tuple\n\
987 and bypass PyEval_EvalCodeEx()\n\
9884. PyMethod calls\n\
9895. PyMethod calls on bound methods\n\
9906. PyType calls\n\
9917. PyCFunction calls\n\
9928. generator calls\n\
9939. All other calls\n\
99410. Number of stack pops performed by call_function()"
995);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000996
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000997#ifdef __cplusplus
998extern "C" {
999#endif
1000
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001001#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001002/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001003extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001004#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001005
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001006#ifdef DYNAMIC_EXECUTION_PROFILE
1007/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001008extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001009#endif
1010
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001011#ifdef __cplusplus
1012}
1013#endif
1014
Christian Heimes15ebc882008-02-04 18:48:49 +00001015static PyObject *
1016sys_clear_type_cache(PyObject* self, PyObject* args)
1017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyType_ClearCache();
1019 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001020}
1021
1022PyDoc_STRVAR(sys_clear_type_cache__doc__,
1023"_clear_type_cache() -> None\n\
1024Clear the internal type lookup cache.");
1025
1026
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001027static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Might as well keep this in alphabetic order */
1029 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1030 callstats_doc},
1031 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1032 sys_clear_type_cache__doc__},
1033 {"_current_frames", sys_current_frames, METH_NOARGS,
1034 current_frames_doc},
1035 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1036 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1037 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1038 {"exit", sys_exit, METH_VARARGS, exit_doc},
1039 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1040 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001041#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1043 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001044#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001045#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001047#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001048#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001050#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1052 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001053#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001055#endif
1056#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001058#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1060 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1061 getrecursionlimit_doc},
1062 {"getsizeof", (PyCFunction)sys_getsizeof,
1063 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1064 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001065#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1067 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001068#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001070#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001072#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1074 setcheckinterval_doc},
1075 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1076 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001077#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1079 setswitchinterval_doc},
1080 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1081 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001082#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001083#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1085 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001086#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1088 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1089 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1090 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001091#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001093#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 {"settrace", sys_settrace, METH_O, settrace_doc},
1095 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1096 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1097 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001098};
1099
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001100static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001101list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 PyObject *list = PyList_New(0);
1104 int i;
1105 if (list == NULL)
1106 return NULL;
1107 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1108 PyObject *name = PyUnicode_FromString(
1109 PyImport_Inittab[i].name);
1110 if (name == NULL)
1111 break;
1112 PyList_Append(list, name);
1113 Py_DECREF(name);
1114 }
1115 if (PyList_Sort(list) != 0) {
1116 Py_DECREF(list);
1117 list = NULL;
1118 }
1119 if (list) {
1120 PyObject *v = PyList_AsTuple(list);
1121 Py_DECREF(list);
1122 list = v;
1123 }
1124 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001125}
1126
Guido van Rossum23fff912000-12-15 22:02:05 +00001127static PyObject *warnoptions = NULL;
1128
1129void
1130PySys_ResetWarnOptions(void)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (warnoptions == NULL || !PyList_Check(warnoptions))
1133 return;
1134 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001135}
1136
1137void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001138PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1141 Py_XDECREF(warnoptions);
1142 warnoptions = PyList_New(0);
1143 if (warnoptions == NULL)
1144 return;
1145 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001146 PyList_Append(warnoptions, unicode);
1147}
1148
1149void
1150PySys_AddWarnOption(const wchar_t *s)
1151{
1152 PyObject *unicode;
1153 unicode = PyUnicode_FromWideChar(s, -1);
1154 if (unicode == NULL)
1155 return;
1156 PySys_AddWarnOptionUnicode(unicode);
1157 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001158}
1159
Christian Heimes33fe8092008-04-13 13:53:33 +00001160int
1161PySys_HasWarnOptions(void)
1162{
1163 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1164}
1165
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001166static PyObject *xoptions = NULL;
1167
1168static PyObject *
1169get_xoptions(void)
1170{
1171 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1172 Py_XDECREF(xoptions);
1173 xoptions = PyDict_New();
1174 }
1175 return xoptions;
1176}
1177
1178void
1179PySys_AddXOption(const wchar_t *s)
1180{
1181 PyObject *opts;
1182 PyObject *name = NULL, *value = NULL;
1183 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001184
1185 opts = get_xoptions();
1186 if (opts == NULL)
1187 goto error;
1188
1189 name_end = wcschr(s, L'=');
1190 if (!name_end) {
1191 name = PyUnicode_FromWideChar(s, -1);
1192 value = Py_True;
1193 Py_INCREF(value);
1194 }
1195 else {
1196 name = PyUnicode_FromWideChar(s, name_end - s);
1197 value = PyUnicode_FromWideChar(name_end + 1, -1);
1198 }
1199 if (name == NULL || value == NULL)
1200 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001201 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001202 Py_DECREF(name);
1203 Py_DECREF(value);
1204 return;
1205
1206error:
1207 Py_XDECREF(name);
1208 Py_XDECREF(value);
1209 /* No return value, therefore clear error state if possible */
1210 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1211 PyErr_Clear();
1212}
1213
1214PyObject *
1215PySys_GetXOptions(void)
1216{
1217 return get_xoptions();
1218}
1219
Guido van Rossum40552d01998-08-06 03:34:39 +00001220/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1221 Two literals concatenated works just fine. If you have a K&R compiler
1222 or other abomination that however *does* understand longer strings,
1223 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001224PyDoc_VAR(sys_doc) =
1225PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001226"This module provides access to some objects used or maintained by the\n\
1227interpreter and to functions that interact strongly with the interpreter.\n\
1228\n\
1229Dynamic objects:\n\
1230\n\
1231argv -- command line arguments; argv[0] is the script pathname if known\n\
1232path -- module search path; path[0] is the script directory, else ''\n\
1233modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001234\n\
1235displayhook -- called to show results in an interactive session\n\
1236excepthook -- called to handle any uncaught exception other than SystemExit\n\
1237 To customize printing in an interactive session or to install a custom\n\
1238 top-level exception handler, assign other functions to replace these.\n\
1239\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001240stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001241stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001242stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001243 By assigning other file objects (or objects that behave like files)\n\
1244 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001245\n\
1246last_type -- type of last uncaught exception\n\
1247last_value -- value of last uncaught exception\n\
1248last_traceback -- traceback of last uncaught exception\n\
1249 These three are only available in an interactive session after a\n\
1250 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001251"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001252)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001253/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001254PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001255"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001256Static objects:\n\
1257\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001258builtin_module_names -- tuple of module names built into this interpreter\n\
1259copyright -- copyright notice pertaining to this interpreter\n\
1260exec_prefix -- prefix used to find the machine-specific Python library\n\
1261executable -- pathname of this Python interpreter\n\
1262float_info -- a struct sequence with information about the float implementation.\n\
1263float_repr_style -- string indicating the style of repr() output for floats\n\
1264hexversion -- version information encoded as a single integer\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001265int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001266maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001267maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001268platform -- platform identifier\n\
1269prefix -- prefix used to find the Python library\n\
1270thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001271version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001272version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001273"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001274)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001275#ifdef MS_WINDOWS
1276/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001277PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001278"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001279winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001280"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001281)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001282#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001283PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001284"__stdin__ -- the original stdin; don't touch!\n\
1285__stdout__ -- the original stdout; don't touch!\n\
1286__stderr__ -- the original stderr; don't touch!\n\
1287__displayhook__ -- the original displayhook; don't touch!\n\
1288__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001289\n\
1290Functions:\n\
1291\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001292displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001293excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001294exc_info() -- return thread-safe information about the current exception\n\
1295exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001296getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001297getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001298getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001299getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001300getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001301gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001302setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001303setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001304setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001305setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001306settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001307"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001308)
Fred Drakeccede592000-08-14 20:59:57 +00001309/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001310
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001311
1312PyDoc_STRVAR(flags__doc__,
1313"sys.flags\n\
1314\n\
1315Flags provided through command line arguments or environment vars.");
1316
1317static PyTypeObject FlagsType;
1318
1319static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 {"inspect", "-i"},
1322 {"interactive", "-i"},
1323 {"optimize", "-O or -OO"},
1324 {"dont_write_bytecode", "-B"},
1325 {"no_user_site", "-s"},
1326 {"no_site", "-S"},
1327 {"ignore_environment", "-E"},
1328 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001329#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001331#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* {"unbuffered", "-u"}, */
1333 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001334 {"bytes_warning", "-b"},
1335 {"quiet", "-q"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001337};
1338
1339static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 "sys.flags", /* name */
1341 flags__doc__, /* doc */
1342 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001343#ifdef RISCOS
Raymond Hettinger90e8f8c2011-01-05 20:08:25 +00001344 12
Éric Araujobe3bd572011-03-26 01:55:15 +01001345#else
1346 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001347#endif
1348};
1349
1350static PyObject*
1351make_flags(void)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 int pos = 0;
1354 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 seq = PyStructSequence_New(&FlagsType);
1357 if (seq == NULL)
1358 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001359
1360#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 SetFlag(Py_InspectFlag);
1365 SetFlag(Py_InteractiveFlag);
1366 SetFlag(Py_OptimizeFlag);
1367 SetFlag(Py_DontWriteBytecodeFlag);
1368 SetFlag(Py_NoUserSiteDirectory);
1369 SetFlag(Py_NoSiteFlag);
1370 SetFlag(Py_IgnoreEnvironmentFlag);
1371 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001372#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001374#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* SetFlag(saw_unbuffered_flag); */
1376 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001377 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001378 SetFlag(Py_QuietFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001379#undef SetFlag
1380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (PyErr_Occurred()) {
1382 return NULL;
1383 }
1384 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001385}
1386
Eric Smith0e5b5622009-02-06 01:32:42 +00001387PyDoc_STRVAR(version_info__doc__,
1388"sys.version_info\n\
1389\n\
1390Version information as a named tuple.");
1391
1392static PyTypeObject VersionInfoType;
1393
1394static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 {"major", "Major release number"},
1396 {"minor", "Minor release number"},
1397 {"micro", "Patch release number"},
1398 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1399 {"serial", "Serial release number"},
1400 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001401};
1402
1403static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 "sys.version_info", /* name */
1405 version_info__doc__, /* doc */
1406 version_info_fields, /* fields */
1407 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001408};
1409
1410static PyObject *
1411make_version_info(void)
1412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 PyObject *version_info;
1414 char *s;
1415 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 version_info = PyStructSequence_New(&VersionInfoType);
1418 if (version_info == NULL) {
1419 return NULL;
1420 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /*
1423 * These release level checks are mutually exclusive and cover
1424 * the field, so don't get too fancy with the pre-processor!
1425 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001426#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001428#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001430#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001432#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001434#endif
1435
1436#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001438#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 SetIntItem(PY_MAJOR_VERSION);
1442 SetIntItem(PY_MINOR_VERSION);
1443 SetIntItem(PY_MICRO_VERSION);
1444 SetStrItem(s);
1445 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001446#undef SetIntItem
1447#undef SetStrItem
1448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (PyErr_Occurred()) {
1450 Py_CLEAR(version_info);
1451 return NULL;
1452 }
1453 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001454}
1455
Martin v. Löwis1a214512008-06-11 05:26:20 +00001456static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyModuleDef_HEAD_INIT,
1458 "sys",
1459 sys_doc,
1460 -1, /* multiple "initialization" just copies the module dict. */
1461 sys_methods,
1462 NULL,
1463 NULL,
1464 NULL,
1465 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001466};
1467
Guido van Rossum25ce5661997-08-02 03:10:38 +00001468PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001469_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyObject *m, *v, *sysdict;
1472 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 m = PyModule_Create(&sysmodule);
1475 if (m == NULL)
1476 return NULL;
1477 sysdict = PyModule_GetDict(m);
1478#define SET_SYS_FROM_STRING(key, value) \
1479 v = value; \
1480 if (v != NULL) \
1481 PyDict_SetItemString(sysdict, key, v); \
1482 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 /* Check that stdin is not a directory
1485 Using shell redirection, you can redirect stdin to a directory,
1486 crashing the Python interpreter. Catch this common mistake here
1487 and output a useful error message. Note that under MS Windows,
1488 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001489#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 {
1491 struct stat sb;
1492 if (fstat(fileno(stdin), &sb) == 0 &&
1493 S_ISDIR(sb.st_mode)) {
1494 /* There's nothing more we can do. */
1495 /* Py_FatalError() will core dump, so just exit. */
1496 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1497 exit(EXIT_FAILURE);
1498 }
1499 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001500#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyDict_SetItemString(sysdict, "__displayhook__",
1505 PyDict_GetItemString(sysdict, "displayhook"));
1506 PyDict_SetItemString(sysdict, "__excepthook__",
1507 PyDict_GetItemString(sysdict, "excepthook"));
1508 SET_SYS_FROM_STRING("version",
1509 PyUnicode_FromString(Py_GetVersion()));
1510 SET_SYS_FROM_STRING("hexversion",
1511 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001512 SET_SYS_FROM_STRING("_mercurial",
1513 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1514 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 SET_SYS_FROM_STRING("dont_write_bytecode",
1516 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1517 SET_SYS_FROM_STRING("api_version",
1518 PyLong_FromLong(PYTHON_API_VERSION));
1519 SET_SYS_FROM_STRING("copyright",
1520 PyUnicode_FromString(Py_GetCopyright()));
1521 SET_SYS_FROM_STRING("platform",
1522 PyUnicode_FromString(Py_GetPlatform()));
1523 SET_SYS_FROM_STRING("executable",
1524 PyUnicode_FromWideChar(
1525 Py_GetProgramFullPath(), -1));
1526 SET_SYS_FROM_STRING("prefix",
1527 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1528 SET_SYS_FROM_STRING("exec_prefix",
1529 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1530 SET_SYS_FROM_STRING("maxsize",
1531 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1532 SET_SYS_FROM_STRING("float_info",
1533 PyFloat_GetInfo());
1534 SET_SYS_FROM_STRING("int_info",
1535 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001536 /* initialize hash_info */
1537 if (Hash_InfoType.tp_name == 0)
1538 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1539 SET_SYS_FROM_STRING("hash_info",
1540 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001542 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 SET_SYS_FROM_STRING("builtin_module_names",
1544 list_builtin_module_names());
1545 {
1546 /* Assumes that longs are at least 2 bytes long.
1547 Should be safe! */
1548 unsigned long number = 1;
1549 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 s = (char *) &number;
1552 if (s[0] == 0)
1553 value = "big";
1554 else
1555 value = "little";
1556 SET_SYS_FROM_STRING("byteorder",
1557 PyUnicode_FromString(value));
1558 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001559#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 SET_SYS_FROM_STRING("dllhandle",
1561 PyLong_FromVoidPtr(PyWin_DLLhModule));
1562 SET_SYS_FROM_STRING("winver",
1563 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001564#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001565#ifdef ABIFLAGS
1566 SET_SYS_FROM_STRING("abiflags",
1567 PyUnicode_FromString(ABIFLAGS));
1568#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (warnoptions == NULL) {
1570 warnoptions = PyList_New(0);
1571 }
1572 else {
1573 Py_INCREF(warnoptions);
1574 }
1575 if (warnoptions != NULL) {
1576 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1577 }
Tim Peters216b78b2006-01-06 02:40:53 +00001578
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001579 v = get_xoptions();
1580 if (v != NULL) {
1581 PyDict_SetItemString(sysdict, "_xoptions", v);
1582 }
1583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* version_info */
1585 if (VersionInfoType.tp_name == 0)
1586 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1587 SET_SYS_FROM_STRING("version_info", make_version_info());
1588 /* prevent user from creating new instances */
1589 VersionInfoType.tp_init = NULL;
1590 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 /* flags */
1593 if (FlagsType.tp_name == 0)
1594 PyStructSequence_InitType(&FlagsType, &flags_desc);
1595 SET_SYS_FROM_STRING("flags", make_flags());
1596 /* prevent user from creating new instances */
1597 FlagsType.tp_init = NULL;
1598 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001599
Eric Smithf7bb5782010-01-27 00:44:57 +00001600
1601#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 /* getwindowsversion */
1603 if (WindowsVersionType.tp_name == 0)
1604 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1605 /* prevent user from creating new instances */
1606 WindowsVersionType.tp_init = NULL;
1607 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001608#endif
1609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001611#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 SET_SYS_FROM_STRING("float_repr_style",
1613 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001614#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 SET_SYS_FROM_STRING("float_repr_style",
1616 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001617#endif
1618
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001619#ifdef WITH_THREAD
1620 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1621#endif
1622
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001623#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (PyErr_Occurred())
1625 return NULL;
1626 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001627}
1628
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001629static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001630makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 int i, n;
1633 const wchar_t *p;
1634 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 n = 1;
1637 p = path;
1638 while ((p = wcschr(p, delim)) != NULL) {
1639 n++;
1640 p++;
1641 }
1642 v = PyList_New(n);
1643 if (v == NULL)
1644 return NULL;
1645 for (i = 0; ; i++) {
1646 p = wcschr(path, delim);
1647 if (p == NULL)
1648 p = path + wcslen(path); /* End of string */
1649 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1650 if (w == NULL) {
1651 Py_DECREF(v);
1652 return NULL;
1653 }
1654 PyList_SetItem(v, i, w);
1655 if (*p == '\0')
1656 break;
1657 path = p+1;
1658 }
1659 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001660}
1661
1662void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001663PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyObject *v;
1666 if ((v = makepathobject(path, DELIM)) == NULL)
1667 Py_FatalError("can't create sys.path");
1668 if (PySys_SetObject("path", v) != 0)
1669 Py_FatalError("can't assign sys.path");
1670 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001671}
1672
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001673static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001674makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 PyObject *av;
1677 if (argc <= 0 || argv == NULL) {
1678 /* Ensure at least one (empty) argument is seen */
1679 static wchar_t *empty_argv[1] = {L""};
1680 argv = empty_argv;
1681 argc = 1;
1682 }
1683 av = PyList_New(argc);
1684 if (av != NULL) {
1685 int i;
1686 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001687#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* argv[0] is the script pathname if known */
1691 if (i == 0) {
1692 char* fn = decc$translate_vms(argv[0]);
1693 if ((fn == (char *)0) || fn == (char *)-1)
1694 v = PyUnicode_FromString(argv[0]);
1695 else
1696 v = PyUnicode_FromString(
1697 decc$translate_vms(argv[0]));
1698 } else
1699 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001700#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001702#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (v == NULL) {
1704 Py_DECREF(av);
1705 av = NULL;
1706 break;
1707 }
1708 PyList_SetItem(av, i, v);
1709 }
1710 }
1711 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001712}
1713
Nick Coghland26c18a2010-08-17 13:06:11 +00001714#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1715 (argc > 0 && argv0 != NULL && \
1716 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001717
1718static void
1719sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001720{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001721 wchar_t *argv0;
1722 wchar_t *p = NULL;
1723 Py_ssize_t n = 0;
1724 PyObject *a;
1725 PyObject *path;
1726#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001727 wchar_t link[MAXPATHLEN+1];
1728 wchar_t argv0copy[2*MAXPATHLEN+1];
1729 int nr = 0;
1730#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001731#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001733#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001735#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001736
1737 path = PySys_GetObject("path");
1738 if (path == NULL)
1739 return;
1740
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001741 argv0 = argv[0];
1742
1743#ifdef HAVE_READLINK
1744 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1745 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1746 if (nr > 0) {
1747 /* It's a symlink */
1748 link[nr] = '\0';
1749 if (link[0] == SEP)
1750 argv0 = link; /* Link to absolute path */
1751 else if (wcschr(link, SEP) == NULL)
1752 ; /* Link without path */
1753 else {
1754 /* Must join(dirname(argv0), link) */
1755 wchar_t *q = wcsrchr(argv0, SEP);
1756 if (q == NULL)
1757 argv0 = link; /* argv0 without path */
1758 else {
1759 /* Must make a copy */
1760 wcscpy(argv0copy, argv0);
1761 q = wcsrchr(argv0copy, SEP);
1762 wcscpy(q+1, link);
1763 argv0 = argv0copy;
1764 }
1765 }
1766 }
1767#endif /* HAVE_READLINK */
1768#if SEP == '\\' /* Special case for MS filename syntax */
1769 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1770 wchar_t *q;
1771#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1772 /* This code here replaces the first element in argv with the full
1773 path that it represents. Under CE, there are no relative paths so
1774 the argument must be the full path anyway. */
1775 wchar_t *ptemp;
1776 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001777 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001778 fullpath,
1779 &ptemp)) {
1780 argv0 = fullpath;
1781 }
1782#endif
1783 p = wcsrchr(argv0, SEP);
1784 /* Test for alternate separator */
1785 q = wcsrchr(p ? p : argv0, '/');
1786 if (q != NULL)
1787 p = q;
1788 if (p != NULL) {
1789 n = p + 1 - argv0;
1790 if (n > 1 && p[-1] != ':')
1791 n--; /* Drop trailing separator */
1792 }
1793 }
1794#else /* All other filename syntaxes */
1795 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1796#if defined(HAVE_REALPATH)
Victor Stinner015f4d82010-10-07 22:29:53 +00001797 if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001798 argv0 = fullpath;
1799 }
1800#endif
1801 p = wcsrchr(argv0, SEP);
1802 }
1803 if (p != NULL) {
1804 n = p + 1 - argv0;
1805#if SEP == '/' /* Special case for Unix filename syntax */
1806 if (n > 1)
1807 n--; /* Drop trailing separator */
1808#endif /* Unix */
1809 }
1810#endif /* All others */
1811 a = PyUnicode_FromWideChar(argv0, n);
1812 if (a == NULL)
1813 Py_FatalError("no mem for sys.path insertion");
1814 if (PyList_Insert(path, 0, a) < 0)
1815 Py_FatalError("sys.path.insert(0) failed");
1816 Py_DECREF(a);
1817}
1818
1819void
1820PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
1821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (av == NULL)
1824 Py_FatalError("no mem for sys.argv");
1825 if (PySys_SetObject("argv", av) != 0)
1826 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001828 if (updatepath)
1829 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001830}
Guido van Rossuma890e681998-05-12 14:59:24 +00001831
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001832void
1833PySys_SetArgv(int argc, wchar_t **argv)
1834{
1835 PySys_SetArgvEx(argc, argv, 1);
1836}
1837
Victor Stinner14284c22010-04-23 12:02:30 +00001838/* Reimplementation of PyFile_WriteString() no calling indirectly
1839 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1840
1841static int
Victor Stinner79766632010-08-16 17:36:42 +00001842sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001843{
Victor Stinner79766632010-08-16 17:36:42 +00001844 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 int err;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001846 _Py_IDENTIFIER(write);
Victor Stinner14284c22010-04-23 12:02:30 +00001847
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001848 if (file == NULL)
1849 return -1;
1850
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001851 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (writer == NULL)
1853 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 args = PyTuple_Pack(1, unicode);
1856 if (args == NULL)
1857 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 result = PyEval_CallObject(writer, args);
1860 if (result == NULL) {
1861 goto error;
1862 } else {
1863 err = 0;
1864 goto finally;
1865 }
Victor Stinner14284c22010-04-23 12:02:30 +00001866
1867error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001869finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 Py_XDECREF(writer);
1871 Py_XDECREF(args);
1872 Py_XDECREF(result);
1873 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001874}
1875
Victor Stinner79766632010-08-16 17:36:42 +00001876static int
1877sys_pyfile_write(const char *text, PyObject *file)
1878{
1879 PyObject *unicode = NULL;
1880 int err;
1881
1882 if (file == NULL)
1883 return -1;
1884
1885 unicode = PyUnicode_FromString(text);
1886 if (unicode == NULL)
1887 return -1;
1888
1889 err = sys_pyfile_write_unicode(unicode, file);
1890 Py_DECREF(unicode);
1891 return err;
1892}
Guido van Rossuma890e681998-05-12 14:59:24 +00001893
1894/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1895 Adapted from code submitted by Just van Rossum.
1896
1897 PySys_WriteStdout(format, ...)
1898 PySys_WriteStderr(format, ...)
1899
1900 The first function writes to sys.stdout; the second to sys.stderr. When
1901 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00001902 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00001903
Victor Stinner14284c22010-04-23 12:02:30 +00001904 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00001905 signal handlers: they may raise a new exception whereas sys_write()
1906 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00001907
Guido van Rossuma890e681998-05-12 14:59:24 +00001908 Both take a printf-style format string as their first argument followed
1909 by a variable length argument list determined by the format string.
1910
1911 *** WARNING ***
1912
1913 The format should limit the total size of the formatted output string to
1914 1000 bytes. In particular, this means that no unrestricted "%s" formats
1915 should occur; these should be limited using "%.<N>s where <N> is a
1916 decimal number calculated so that <N> plus the maximum size of other
1917 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1918 which can print hundreds of digits for very large numbers.
1919
1920 */
1921
1922static void
Victor Stinner79766632010-08-16 17:36:42 +00001923sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00001924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyObject *file;
1926 PyObject *error_type, *error_value, *error_traceback;
1927 char buffer[1001];
1928 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1931 file = PySys_GetObject(name);
1932 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
1933 if (sys_pyfile_write(buffer, file) != 0) {
1934 PyErr_Clear();
1935 fputs(buffer, fp);
1936 }
1937 if (written < 0 || (size_t)written >= sizeof(buffer)) {
1938 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00001939 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 }
1942 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00001943}
1944
1945void
Guido van Rossuma890e681998-05-12 14:59:24 +00001946PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001951 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00001953}
1954
1955void
Guido van Rossuma890e681998-05-12 14:59:24 +00001956PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001961 sys_write("stderr", stderr, format, va);
1962 va_end(va);
1963}
1964
1965static void
1966sys_format(char *name, FILE *fp, const char *format, va_list va)
1967{
1968 PyObject *file, *message;
1969 PyObject *error_type, *error_value, *error_traceback;
1970 char *utf8;
1971
1972 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1973 file = PySys_GetObject(name);
1974 message = PyUnicode_FromFormatV(format, va);
1975 if (message != NULL) {
1976 if (sys_pyfile_write_unicode(message, file) != 0) {
1977 PyErr_Clear();
1978 utf8 = _PyUnicode_AsString(message);
1979 if (utf8 != NULL)
1980 fputs(utf8, fp);
1981 }
1982 Py_DECREF(message);
1983 }
1984 PyErr_Restore(error_type, error_value, error_traceback);
1985}
1986
1987void
1988PySys_FormatStdout(const char *format, ...)
1989{
1990 va_list va;
1991
1992 va_start(va, format);
1993 sys_format("stdout", stdout, format, va);
1994 va_end(va);
1995}
1996
1997void
1998PySys_FormatStderr(const char *format, ...)
1999{
2000 va_list va;
2001
2002 va_start(va, format);
2003 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002005}