/* System module */ /* Various bits of information used by the interpreter are collected in module 'sys'. Function member: - exit(sts): raise SystemExit Data members: - stdin, stdout, stderr: standard file objects - modules: the table of modules (dictionary) - path: module search path (list of strings) - argv: script arguments (list of strings) - ps1, ps2: optional primary and secondary prompts (strings) */ #include "Python.h" #include "pycore_audit.h" // _Py_AuditHookEntry #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_ceval.h" // _PyEval_SetAsyncGenFinalizer() #include "pycore_dict.h" // _PyDict_GetItemWithError() #include "pycore_frame.h" // _PyInterpreterFrame #include "pycore_initconfig.h" // _PyStatus_EXCEPTION() #include "pycore_long.h" // _PY_LONG_MAX_STR_DIGITS_THRESHOLD #include "pycore_modsupport.h" // _PyModule_CreateInitialized() #include "pycore_namespace.h" // _PyNamespace_New() #include "pycore_object.h" // _PyObject_DebugTypeStats() #include "pycore_pathconfig.h" // _PyPathConfig_ComputeSysPath0() #include "pycore_pyerrors.h" // _PyErr_GetRaisedException() #include "pycore_pylifecycle.h" // _PyErr_WriteUnraisableDefaultHook() #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR #include "pycore_pymem.h" // _PyMem_SetDefaultAllocator() #include "pycore_pystate.h" // _PyThreadState_GET() #include "pycore_pystats.h" // _Py_PrintSpecializationStats() #include "pycore_structseq.h" // _PyStructSequence_InitBuiltinWithFlags() #include "pycore_sysmodule.h" // export _PySys_GetSizeOf() #include "pycore_tuple.h" // _PyTuple_FromArray() #include "pydtrace.h" // PyDTrace_AUDIT() #include "osdefs.h" // DELIM #include "stdlib_module_names.h" // _Py_stdlib_module_names #ifdef HAVE_UNISTD_H # include <unistd.h> // getpid() #endif #ifdef MS_WINDOWS #define WIN32_LEAN_AND_MEAN # include <windows.h> #endif /* MS_WINDOWS */ #ifdef MS_COREDLL extern void *PyWin_DLLhModule; /* A string loaded from the DLL at startup: */ extern const char *PyWin_DLLVersionString; #endif #ifdef __EMSCRIPTEN__ # include <emscripten.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif /*[clinic input] module sys [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/ #include "clinic/sysmodule.c.h" PyObject * _PySys_GetAttr(PyThreadState *tstate, PyObject *name) { … } static PyObject * _PySys_GetObject(PyInterpreterState *interp, const char *name) { … } PyObject * PySys_GetObject(const char *name) { … } static int sys_set_object(PyInterpreterState *interp, PyObject *key, PyObject *v) { … } int _PySys_SetAttr(PyObject *key, PyObject *v) { … } static int sys_set_object_str(PyInterpreterState *interp, const char *name, PyObject *v) { … } int PySys_SetObject(const char *name, PyObject *v) { … } int _PySys_ClearAttrString(PyInterpreterState *interp, const char *name, int verbose) { … } static int should_audit(PyInterpreterState *interp) { … } static int sys_audit_tstate(PyThreadState *ts, const char *event, const char *argFormat, va_list vargs) { … } int _PySys_Audit(PyThreadState *tstate, const char *event, const char *argFormat, ...) { … } int PySys_Audit(const char *event, const char *argFormat, ...) { … } int PySys_AuditTuple(const char *event, PyObject *args) { … } /* We expose this function primarily for our own cleanup during * finalization. In general, it should not need to be called, * and as such the function is not exported. * * Must be finalizing to clear hooks */ void _PySys_ClearAuditHooks(PyThreadState *ts) { … } static void add_audit_hook_entry_unlocked(_PyRuntimeState *runtime, _Py_AuditHookEntry *entry) { … } int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData) { … } /*[clinic input] sys.addaudithook hook: object Adds a new audit hook callback. [clinic start generated code]*/ static PyObject * sys_addaudithook_impl(PyObject *module, PyObject *hook) /*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/ { … } /*[clinic input] sys.audit event: str / *args: tuple Passes the event to any audit hooks that are attached. [clinic start generated code]*/ static PyObject * sys_audit_impl(PyObject *module, const char *event, PyObject *args) /*[clinic end generated code: output=1d0fc82da768f49d input=ec3b688527945109]*/ { … } static PyObject * sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords) { … } PyDoc_STRVAR(breakpointhook_doc, "breakpointhook($module, /, *args, **kwargs)\n" "--\n" "\n" "This hook function is called by built-in breakpoint().\n" ); /* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace' error handler. If sys.stdout has a buffer attribute, use sys.stdout.buffer.write(encoded), otherwise redecode the string and use sys.stdout.write(redecoded). Helper function for sys_displayhook(). */ static int sys_displayhook_unencodable(PyObject *outf, PyObject *o) { … } /*[clinic input] sys.displayhook object as o: object / Print an object to sys.stdout and also save it in builtins._ [clinic start generated code]*/ static PyObject * sys_displayhook(PyObject *module, PyObject *o) /*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/ { … } /*[clinic input] sys.excepthook exctype: object value: object traceback: object / Handle an exception by displaying it with a traceback on sys.stderr. [clinic start generated code]*/ static PyObject * sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value, PyObject *traceback) /*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/ { … } /*[clinic input] sys.exception Return the current exception. Return the most recent exception caught by an except clause in the current stack frame or in an older stack frame, or None if no such exception exists. [clinic start generated code]*/ static PyObject * sys_exception_impl(PyObject *module) /*[clinic end generated code: output=2381ee2f25953e40 input=c88fbb94b6287431]*/ { … } /*[clinic input] sys.exc_info Return current exception information: (type, value, traceback). Return information about the most recent exception caught by an except clause in the current stack frame or in an older stack frame. [clinic start generated code]*/ static PyObject * sys_exc_info_impl(PyObject *module) /*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/ { … } /*[clinic input] sys.unraisablehook unraisable: object / Handle an unraisable exception. The unraisable argument has the following attributes: * exc_type: Exception type. * exc_value: Exception value, can be None. * exc_traceback: Exception traceback, can be None. * err_msg: Error message, can be None. * object: Object causing the exception, can be None. [clinic start generated code]*/ static PyObject * sys_unraisablehook(PyObject *module, PyObject *unraisable) /*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/ { … } /*[clinic input] sys.exit status: object = None / Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). [clinic start generated code]*/ static PyObject * sys_exit_impl(PyObject *module, PyObject *status) /*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/ { … } static PyObject * get_utf8_unicode(void) { … } /*[clinic input] sys.getdefaultencoding Return the current default encoding used by the Unicode implementation. [clinic start generated code]*/ static PyObject * sys_getdefaultencoding_impl(PyObject *module) /*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/ { … } /*[clinic input] sys.getfilesystemencoding Return the encoding used to convert Unicode filenames to OS filenames. [clinic start generated code]*/ static PyObject * sys_getfilesystemencoding_impl(PyObject *module) /*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/ { … } /*[clinic input] sys.getfilesystemencodeerrors Return the error mode used Unicode to OS filename conversion. [clinic start generated code]*/ static PyObject * sys_getfilesystemencodeerrors_impl(PyObject *module) /*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/ { … } /*[clinic input] sys.intern string as s: unicode / ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. [clinic start generated code]*/ static PyObject * sys_intern_impl(PyObject *module, PyObject *s) /*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/ { … } /*[clinic input] sys._is_interned -> bool string: unicode / Return True if the given string is "interned". [clinic start generated code]*/ static int sys__is_interned_impl(PyObject *module, PyObject *string) /*[clinic end generated code: output=c3678267b4e9d7ed input=039843e17883b606]*/ { … } /* * Cached interned string objects used for calling the profile and * trace functions. */ static PyObject *whatstrings[8] = …; static PyObject * call_trampoline(PyThreadState *tstate, PyObject* callback, PyFrameObject *frame, int what, PyObject *arg) { … } static int profile_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) { … } static int trace_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) { … } /*[clinic input] sys.settrace function: object / Set the global debug tracing function. It will be called on each function call. See the debugger chapter in the library manual. [clinic start generated code]*/ static PyObject * sys_settrace(PyObject *module, PyObject *function) /*[clinic end generated code: output=999d12e9d6ec4678 input=8107feb01c5f1c4e]*/ { … } /*[clinic input] sys._settraceallthreads function as arg: object / Set the global debug tracing function in all running threads belonging to the current interpreter. It will be called on each function call. See the debugger chapter in the library manual. [clinic start generated code]*/ static PyObject * sys__settraceallthreads(PyObject *module, PyObject *arg) /*[clinic end generated code: output=161cca30207bf3ca input=d4bde1f810d73675]*/ { … } /*[clinic input] sys.gettrace Return the global debug tracing function set with sys.settrace. See the debugger chapter in the library manual. [clinic start generated code]*/ static PyObject * sys_gettrace_impl(PyObject *module) /*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/ { … } /*[clinic input] sys.setprofile function: object / Set the profiling function. It will be called on each function call and return. See the profiler chapter in the library manual. [clinic start generated code]*/ static PyObject * sys_setprofile(PyObject *module, PyObject *function) /*[clinic end generated code: output=1c3503105939db9c input=055d0d7961413a62]*/ { … } /*[clinic input] sys._setprofileallthreads function as arg: object / Set the profiling function in all running threads belonging to the current interpreter. It will be called on each function call and return. See the profiler chapter in the library manual. [clinic start generated code]*/ static PyObject * sys__setprofileallthreads(PyObject *module, PyObject *arg) /*[clinic end generated code: output=2d61319e27b309fe input=a10589439ba20cee]*/ { … } /*[clinic input] sys.getprofile Return the profiling function set with sys.setprofile. See the profiler chapter in the library manual. [clinic start generated code]*/ static PyObject * sys_getprofile_impl(PyObject *module) /*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/ { … } /*[clinic input] sys.setswitchinterval interval: double / Set the ideal thread switching delay inside the Python interpreter. The actual frequency of switching threads can be lower if the interpreter executes long sequences of uninterruptible code (this is implementation-specific and workload-dependent). The parameter must represent the desired switching delay in seconds A typical value is 0.005 (5 milliseconds). [clinic start generated code]*/ static PyObject * sys_setswitchinterval_impl(PyObject *module, double interval) /*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/ { … } /*[clinic input] sys.getswitchinterval -> double Return the current thread switch interval; see sys.setswitchinterval(). [clinic start generated code]*/ static double sys_getswitchinterval_impl(PyObject *module) /*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/ { … } /*[clinic input] sys.setrecursionlimit limit as new_limit: int / Set the maximum depth of the Python interpreter stack to n. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform- dependent. [clinic start generated code]*/ static PyObject * sys_setrecursionlimit_impl(PyObject *module, int new_limit) /*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/ { … } /*[clinic input] sys.set_coroutine_origin_tracking_depth depth: int Enable or disable origin tracking for coroutine objects in this thread. Coroutine objects will track 'depth' frames of traceback information about where they came from, available in their cr_origin attribute. Set a depth of 0 to disable. [clinic start generated code]*/ static PyObject * sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth) /*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/ { … } /*[clinic input] sys.get_coroutine_origin_tracking_depth -> int Check status of origin tracking for coroutine objects in this thread. [clinic start generated code]*/ static int sys_get_coroutine_origin_tracking_depth_impl(PyObject *module) /*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/ { … } static PyTypeObject AsyncGenHooksType; PyDoc_STRVAR(asyncgen_hooks_doc, "asyncgen_hooks\n\ \n\ A named tuple providing information about asynchronous\n\ generators hooks. The attributes are read only."); static PyStructSequence_Field asyncgen_hooks_fields[] = …; static PyStructSequence_Desc asyncgen_hooks_desc = …; static PyObject * sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw) { … } PyDoc_STRVAR(set_asyncgen_hooks_doc, "set_asyncgen_hooks([firstiter] [, finalizer])\n\ \n\ Set a finalizer for async generators objects." ); /*[clinic input] sys.get_asyncgen_hooks Return the installed asynchronous generators hooks. This returns a namedtuple of the form (firstiter, finalizer). [clinic start generated code]*/ static PyObject * sys_get_asyncgen_hooks_impl(PyObject *module) /*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/ { … } static PyTypeObject Hash_InfoType; PyDoc_STRVAR(hash_info_doc, "hash_info\n\ \n\ A named tuple providing parameters used for computing\n\ hashes. The attributes are read only."); static PyStructSequence_Field hash_info_fields[] = …; static PyStructSequence_Desc hash_info_desc = …; static PyObject * get_hash_info(PyThreadState *tstate) { … } /*[clinic input] sys.getrecursionlimit Return the current value of the recursion limit. The recursion limit is the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. [clinic start generated code]*/ static PyObject * sys_getrecursionlimit_impl(PyObject *module) /*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/ { … } #ifdef MS_WINDOWS static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0}; static PyStructSequence_Field windows_version_fields[] = { {"major", "Major version number"}, {"minor", "Minor version number"}, {"build", "Build number"}, {"platform", "Operating system platform"}, {"service_pack", "Latest Service Pack installed on the system"}, {"service_pack_major", "Service Pack major version number"}, {"service_pack_minor", "Service Pack minor version number"}, {"suite_mask", "Bit mask identifying available product suites"}, {"product_type", "System product type"}, {"platform_version", "Diagnostic version number"}, {0} }; static PyStructSequence_Desc windows_version_desc = { "sys.getwindowsversion", /* name */ sys_getwindowsversion__doc__, /* doc */ windows_version_fields, /* fields */ 5 /* For backward compatibility, only the first 5 items are accessible via indexing, the rest are name only */ }; static PyObject * _sys_getwindowsversion_from_kernel32(void) { #ifndef MS_WINDOWS_DESKTOP return NULL; #else HANDLE hKernel32; wchar_t kernel32_path[MAX_PATH]; LPVOID verblock; DWORD verblock_size; VS_FIXEDFILEINFO *ffi; UINT ffi_len; DWORD realMajor, realMinor, realBuild; Py_BEGIN_ALLOW_THREADS hKernel32 = GetModuleHandleW(L"kernel32.dll"); Py_END_ALLOW_THREADS if (!hKernel32 || !GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH)) { PyErr_SetFromWindowsErr(0); return NULL; } verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL); if (!verblock_size) { PyErr_SetFromWindowsErr(0); return NULL; } verblock = PyMem_RawMalloc(verblock_size); if (!verblock || !GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) || !VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) { PyErr_SetFromWindowsErr(0); return NULL; } realMajor = HIWORD(ffi->dwProductVersionMS); realMinor = LOWORD(ffi->dwProductVersionMS); realBuild = HIWORD(ffi->dwProductVersionLS); PyMem_RawFree(verblock); return Py_BuildValue("(kkk)", realMajor, realMinor, realBuild); #endif /* !MS_WINDOWS_DESKTOP */ } /* Disable deprecation warnings about GetVersionEx as the result is being passed straight through to the caller, who is responsible for using it correctly. */ #pragma warning(push) #pragma warning(disable:4996) /*[clinic input] sys.getwindowsversion Return info about the running version of Windows as a named tuple. The members are named: major, minor, build, platform, service_pack, service_pack_major, service_pack_minor, suite_mask, product_type and platform_version. For backward compatibility, only the first 5 items are available by indexing. All elements are numbers, except service_pack and platform_type which are strings, and platform_version which is a 3-tuple. Platform is always 2. Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a server. Platform_version is a 3-tuple containing a version number that is intended for identifying the OS rather than feature detection. [clinic start generated code]*/ static PyObject * sys_getwindowsversion_impl(PyObject *module) /*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/ { PyObject *version; int pos = 0; OSVERSIONINFOEXW ver; if (PyObject_GetOptionalAttrString(module, "_cached_windows_version", &version) < 0) { return NULL; }; if (version && PyObject_TypeCheck(version, &WindowsVersionType)) { return version; } Py_XDECREF(version); ver.dwOSVersionInfoSize = sizeof(ver); if (!GetVersionExW((OSVERSIONINFOW*) &ver)) return PyErr_SetFromWindowsErr(0); version = PyStructSequence_New(&WindowsVersionType); if (version == NULL) return NULL; #define SET_VERSION_INFO … SET_VERSION_INFO(PyLong_FromLong(ver.dwMajorVersion)); SET_VERSION_INFO(PyLong_FromLong(ver.dwMinorVersion)); SET_VERSION_INFO(PyLong_FromLong(ver.dwBuildNumber)); SET_VERSION_INFO(PyLong_FromLong(ver.dwPlatformId)); SET_VERSION_INFO(PyUnicode_FromWideChar(ver.szCSDVersion, -1)); SET_VERSION_INFO(PyLong_FromLong(ver.wServicePackMajor)); SET_VERSION_INFO(PyLong_FromLong(ver.wServicePackMinor)); SET_VERSION_INFO(PyLong_FromLong(ver.wSuiteMask)); SET_VERSION_INFO(PyLong_FromLong(ver.wProductType)); // GetVersion will lie if we are running in a compatibility mode. // We need to read the version info from a system file resource // to accurately identify the OS version. If we fail for any reason, // just return whatever GetVersion said. PyObject *realVersion = _sys_getwindowsversion_from_kernel32(); if (!realVersion) { if (!PyErr_ExceptionMatches(PyExc_WindowsError)) { return NULL; } PyErr_Clear(); realVersion = Py_BuildValue("(kkk)", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber ); } SET_VERSION_INFO(realVersion); #undef SET_VERSION_INFO if (PyObject_SetAttrString(module, "_cached_windows_version", version) < 0) { goto error; } return version; error: Py_DECREF(version); return NULL; } #pragma warning(pop) /*[clinic input] sys._enablelegacywindowsfsencoding Changes the default filesystem encoding to mbcs:replace. This is done for consistency with earlier versions of Python. See PEP 529 for more information. This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING environment variable before launching Python. [clinic start generated code]*/ static PyObject * sys__enablelegacywindowsfsencoding_impl(PyObject *module) /*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/ { if (PyErr_WarnEx(PyExc_DeprecationWarning, "sys._enablelegacywindowsfsencoding() is deprecated and will be " "removed in Python 3.16. Use PYTHONLEGACYWINDOWSFSENCODING " "instead.", 1)) { return NULL; } if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) { return NULL; } Py_RETURN_NONE; } #endif /* MS_WINDOWS */ #ifdef HAVE_DLOPEN /*[clinic input] sys.setdlopenflags flags as new_val: int / Set the flags used by the interpreter for dlopen calls. This is used, for example, when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as sys.setdlopenflags(0). To share symbols across extension modules, call as sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY). [clinic start generated code]*/ static PyObject * sys_setdlopenflags_impl(PyObject *module, int new_val) /*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/ { … } /*[clinic input] sys.getdlopenflags Return the current value of the flags that are used for dlopen calls. The flag constants are defined in the os module. [clinic start generated code]*/ static PyObject * sys_getdlopenflags_impl(PyObject *module) /*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/ { … } #endif /* HAVE_DLOPEN */ #ifdef USE_MALLOPT /* Link with -lmalloc (or -lmpc) on an SGI */ #include <malloc.h> /*[clinic input] sys.mdebug flag: int / [clinic start generated code]*/ static PyObject * sys_mdebug_impl(PyObject *module, int flag) /*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/ { int flag; mallopt(M_DEBUG, flag); Py_RETURN_NONE; } #endif /* USE_MALLOPT */ /*[clinic input] sys.get_int_max_str_digits Return the maximum string digits limit for non-binary int<->str conversions. [clinic start generated code]*/ static PyObject * sys_get_int_max_str_digits_impl(PyObject *module) /*[clinic end generated code: output=0042f5e8ae0e8631 input=61bf9f99bc8b112d]*/ { … } /*[clinic input] sys.set_int_max_str_digits maxdigits: int Set the maximum string digits limit for non-binary int<->str conversions. [clinic start generated code]*/ static PyObject * sys_set_int_max_str_digits_impl(PyObject *module, int maxdigits) /*[clinic end generated code: output=734d4c2511f2a56d input=d7e3f325db6910c5]*/ { … } size_t _PySys_GetSizeOf(PyObject *o) { … } static PyObject * sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) { … } PyDoc_STRVAR(getsizeof_doc, "getsizeof(object [, default]) -> int\n\ \n\ Return the size of object in bytes."); /*[clinic input] sys.getrefcount -> Py_ssize_t object: object / Return the reference count of object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). [clinic start generated code]*/ static Py_ssize_t sys_getrefcount_impl(PyObject *module, PyObject *object) /*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/ { … } #ifdef Py_REF_DEBUG /*[clinic input] sys.gettotalrefcount -> Py_ssize_t [clinic start generated code]*/ static Py_ssize_t sys_gettotalrefcount_impl(PyObject *module) /*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/ { /* It may make sense to return the total for the current interpreter or have a second function that does so. */ return _Py_GetGlobalRefTotal(); } #endif /* Py_REF_DEBUG */ /*[clinic input] sys.getallocatedblocks -> Py_ssize_t Return the number of memory blocks currently allocated. [clinic start generated code]*/ static Py_ssize_t sys_getallocatedblocks_impl(PyObject *module) /*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/ { … } /*[clinic input] sys.getunicodeinternedsize -> Py_ssize_t * _only_immortal: bool = False Return the number of elements of the unicode interned dictionary [clinic start generated code]*/ static Py_ssize_t sys_getunicodeinternedsize_impl(PyObject *module, int _only_immortal) /*[clinic end generated code: output=29a6377a94a14f70 input=0330b3408dd5bcc6]*/ { … } /*[clinic input] sys._getframe depth: int = 0 / Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack. This function should be used for internal and specialized purposes only. [clinic start generated code]*/ static PyObject * sys__getframe_impl(PyObject *module, int depth) /*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/ { … } /*[clinic input] sys._current_frames Return a dict mapping each thread's thread id to its current stack frame. This function should be used for specialized purposes only. [clinic start generated code]*/ static PyObject * sys__current_frames_impl(PyObject *module) /*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/ { … } /*[clinic input] sys._current_exceptions Return a dict mapping each thread's identifier to its current raised exception. This function should be used for specialized purposes only. [clinic start generated code]*/ static PyObject * sys__current_exceptions_impl(PyObject *module) /*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/ { … } /*[clinic input] sys.call_tracing func: object args as funcargs: object(subclass_of='&PyTuple_Type') / Call func(*args), while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug some other code. [clinic start generated code]*/ static PyObject * sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs) /*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/ { … } /*[clinic input] sys._debugmallocstats Print summary info to stderr about the state of pymalloc's structures. In Py_DEBUG mode, also perform some expensive internal consistency checks. [clinic start generated code]*/ static PyObject * sys__debugmallocstats_impl(PyObject *module) /*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/ { … } #ifdef Py_TRACE_REFS /* Defined in objects.c because it uses static globals in that file */ extern PyObject *_Py_GetObjects(PyObject *, PyObject *); #endif /*[clinic input] sys._clear_type_cache Clear the internal type lookup cache. [clinic start generated code]*/ static PyObject * sys__clear_type_cache_impl(PyObject *module) /*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/ { … } /*[clinic input] sys._clear_internal_caches Clear all internal performance-related caches. [clinic start generated code]*/ static PyObject * sys__clear_internal_caches_impl(PyObject *module) /*[clinic end generated code: output=0ee128670a4966d6 input=253e741ca744f6e8]*/ { … } /* Note that, for now, we do not have a per-interpreter equivalent for sys.is_finalizing(). */ /*[clinic input] sys.is_finalizing Return True if Python is exiting. [clinic start generated code]*/ static PyObject * sys_is_finalizing_impl(PyObject *module) /*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/ { … } #ifdef Py_STATS /*[clinic input] sys._stats_on Turns on stats gathering (stats gathering is off by default). [clinic start generated code]*/ static PyObject * sys__stats_on_impl(PyObject *module) /*[clinic end generated code: output=aca53eafcbb4d9fe input=43b5bfe145299e55]*/ { _Py_StatsOn(); Py_RETURN_NONE; } /*[clinic input] sys._stats_off Turns off stats gathering (stats gathering is off by default). [clinic start generated code]*/ static PyObject * sys__stats_off_impl(PyObject *module) /*[clinic end generated code: output=1534c1ee63812214 input=d1a84c60c56cbce2]*/ { _Py_StatsOff(); Py_RETURN_NONE; } /*[clinic input] sys._stats_clear Clears the stats. [clinic start generated code]*/ static PyObject * sys__stats_clear_impl(PyObject *module) /*[clinic end generated code: output=fb65a2525ee50604 input=3e03f2654f44da96]*/ { _Py_StatsClear(); Py_RETURN_NONE; } /*[clinic input] sys._stats_dump -> bool Dump stats to file, and clears the stats. Return False if no statistics were not dumped because stats gathering was off. [clinic start generated code]*/ static int sys__stats_dump_impl(PyObject *module) /*[clinic end generated code: output=6e346b4ba0de4489 input=31a489e39418b2a5]*/ { int res = _Py_PrintSpecializationStats(1); _Py_StatsClear(); return res; } #endif // Py_STATS #ifdef ANDROID_API_LEVEL /*[clinic input] sys.getandroidapilevel Return the build time API version of Android as an integer. [clinic start generated code]*/ static PyObject * sys_getandroidapilevel_impl(PyObject *module) /*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/ { return PyLong_FromLong(ANDROID_API_LEVEL); } #endif /* ANDROID_API_LEVEL */ /*[clinic input] sys.activate_stack_trampoline backend: str / Activate stack profiler trampoline *backend*. [clinic start generated code]*/ static PyObject * sys_activate_stack_trampoline_impl(PyObject *module, const char *backend) /*[clinic end generated code: output=5783cdeb51874b43 input=a12df928758a82b4]*/ { … } /*[clinic input] sys.deactivate_stack_trampoline Deactivate the current stack profiler trampoline backend. If no stack profiler is activated, this function has no effect. [clinic start generated code]*/ static PyObject * sys_deactivate_stack_trampoline_impl(PyObject *module) /*[clinic end generated code: output=b50da25465df0ef1 input=9f629a6be9fe7fc8]*/ { … } /*[clinic input] sys.is_stack_trampoline_active Return *True* if a stack profiler trampoline is active. [clinic start generated code]*/ static PyObject * sys_is_stack_trampoline_active_impl(PyObject *module) /*[clinic end generated code: output=ab2746de0ad9d293 input=29616b7bf6a0b703]*/ { … } /*[clinic input] sys._getframemodulename depth: int = 0 Return the name of the module for a calling frame. The default depth returns the module containing the call to this API. A more typical use in a library will pass a depth of 1 to get the user's module rather than the library module. If no frame, module, or name can be found, returns None. [clinic start generated code]*/ static PyObject * sys__getframemodulename_impl(PyObject *module, int depth) /*[clinic end generated code: output=1d70ef691f09d2db input=d4f1a8ed43b8fb46]*/ { … } /*[clinic input] sys._get_cpu_count_config -> int Private function for getting PyConfig.cpu_count [clinic start generated code]*/ static int sys__get_cpu_count_config_impl(PyObject *module) /*[clinic end generated code: output=36611bb5efad16dc input=523e1ade2204084e]*/ { … } /*[clinic input] sys._baserepl Private function for getting the base REPL [clinic start generated code]*/ static PyObject * sys__baserepl_impl(PyObject *module) /*[clinic end generated code: output=f19a36375ebe0a45 input=ade0ebb9fab56f3c]*/ { … } /*[clinic input] sys._is_gil_enabled -> bool Return True if the GIL is currently enabled and False otherwise. [clinic start generated code]*/ static int sys__is_gil_enabled_impl(PyObject *module) /*[clinic end generated code: output=57732cf53f5b9120 input=7e9c47f15a00e809]*/ { … } static PerfMapState perf_map_state; PyAPI_FUNC(int) PyUnstable_PerfMapState_Init(void) { … } PyAPI_FUNC(int) PyUnstable_WritePerfMapEntry( const void *code_addr, unsigned int code_size, const char *entry_name ) { … } PyAPI_FUNC(void) PyUnstable_PerfMapState_Fini(void) { … } PyAPI_FUNC(int) PyUnstable_CopyPerfMapFile(const char* parent_filename) { … } static PyMethodDef sys_methods[] = …; static PyObject * list_builtin_module_names(void) { … } static PyObject * list_stdlib_module_names(void) { … } /* Pre-initialization support for sys.warnoptions and sys._xoptions * * Modern internal code paths: * These APIs get called after _Py_InitializeCore and get to use the * regular CPython list, dict, and unicode APIs. * * Legacy embedding code paths: * The multi-phase initialization API isn't public yet, so embedding * apps still need to be able configure sys.warnoptions and sys._xoptions * before they call Py_Initialize. To support this, we stash copies of * the supplied wchar * sequences in linked lists, and then migrate the * contents of those lists to the sys module in _PyInitializeCore. * */ struct _preinit_entry { … }; _Py_PreInitEntry; static _Py_PreInitEntry _preinit_warnoptions = …; static _Py_PreInitEntry _preinit_xoptions = …; static _Py_PreInitEntry _alloc_preinit_entry(const wchar_t *value) { … } static int _append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value) { … } static void _clear_preinit_entries(_Py_PreInitEntry *optionlist) { … } PyStatus _PySys_ReadPreinitWarnOptions(PyWideStringList *options) { … } PyStatus _PySys_ReadPreinitXOptions(PyConfig *config) { … } static PyObject * get_warnoptions(PyThreadState *tstate) { … } void PySys_ResetWarnOptions(void) { … } static int _PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option) { … } // Removed in Python 3.13 API, but kept for the stable ABI PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *option) { … } // Removed in Python 3.13 API, but kept for the stable ABI PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *s) { … } // Removed in Python 3.13 API, but kept for the stable ABI PyAPI_FUNC(int) PySys_HasWarnOptions(void) { … } static PyObject * get_xoptions(PyThreadState *tstate) { … } static int _PySys_AddXOptionWithError(const wchar_t *s) { … } // Removed in Python 3.13 API, but kept for the stable ABI PyAPI_FUNC(void) PySys_AddXOption(const wchar_t *s) { … } PyObject * PySys_GetXOptions(void) { … } /* XXX This doc string is too long to be a single string literal in VC++ 5.0. Two literals concatenated works just fine. If you have a K&R compiler or other abomination that however *does* understand longer strings, get rid of the !!! comment in the middle and the quotes that surround it. */ PyDoc_VAR(sys_doc) = …) /* concatenating string here */ PyDoc_STR( "\n\ Static objects:\n\ \n\ builtin_module_names -- tuple of module names built into this interpreter\n\ copyright -- copyright notice pertaining to this interpreter\n\ exec_prefix -- prefix used to find the machine-specific Python library\n\ executable -- absolute path of the executable binary of the Python interpreter\n\ float_info -- a named tuple with information about the float implementation.\n\ float_repr_style -- string indicating the style of repr() output for floats\n\ hash_info -- a named tuple with information about the hash algorithm.\n\ hexversion -- version information encoded as a single integer\n\ implementation -- Python implementation information.\n\ int_info -- a named tuple with information about the int implementation.\n\ maxsize -- the largest supported length of containers.\n\ maxunicode -- the value of the largest Unicode code point\n\ platform -- platform identifier\n\ prefix -- prefix used to find the Python library\n\ thread_info -- a named tuple with information about the thread implementation.\n\ version -- the version of this interpreter as a string\n\ version_info -- version information as a named tuple\n\ " ) #ifdef MS_COREDLL /* concatenating string here */ PyDoc_STR( "dllhandle -- [Windows only] integer handle of the Python DLL\n\ winver -- [Windows only] version number of the Python DLL\n\ " ) #endif /* MS_COREDLL */ #ifdef MS_WINDOWS /* concatenating string here */ PyDoc_STR( "_enablelegacywindowsfsencoding -- [Windows only]\n\ " ) #endif PyDoc_STR( "__stdin__ -- the original stdin; don't touch!\n\ __stdout__ -- the original stdout; don't touch!\n\ __stderr__ -- the original stderr; don't touch!\n\ __displayhook__ -- the original displayhook; don't touch!\n\ __excepthook__ -- the original excepthook; don't touch!\n\ \n\ Functions:\n\ \n\ displayhook() -- print an object to the screen, and save it in builtins._\n\ excepthook() -- print an exception and its traceback to sys.stderr\n\ exception() -- return the current thread's active exception\n\ exc_info() -- return information about the current thread's active exception\n\ exit() -- exit the interpreter by raising SystemExit\n\ getdlopenflags() -- returns flags to be used for dlopen() calls\n\ getprofile() -- get the global profiling function\n\ getrefcount() -- return the reference count for an object (plus one :-)\n\ getrecursionlimit() -- return the max recursion depth for the interpreter\n\ getsizeof() -- return the size of an object in bytes\n\ gettrace() -- get the global debug tracing function\n\ setdlopenflags() -- set the flags to be used for dlopen() calls\n\ setprofile() -- set the global profiling function\n\ setrecursionlimit() -- set the max recursion depth for the interpreter\n\ settrace() -- set the global debug tracing function\n\ " ) /* end of sys_doc */ ; PyDoc_STRVAR(flags__doc__, "sys.flags\n\ \n\ Flags provided through command line arguments or environment vars."); static PyTypeObject FlagsType; static PyStructSequence_Field flags_fields[] = …; #define SYS_FLAGS_INT_MAX_STR_DIGITS … static PyStructSequence_Desc flags_desc = …; static void sys_set_flag(PyObject *flags, Py_ssize_t pos, PyObject *value) { … } int _PySys_SetFlagObj(Py_ssize_t pos, PyObject *value) { … } static int _PySys_SetFlagInt(Py_ssize_t pos, int value) { … } static int set_flags_from_config(PyInterpreterState *interp, PyObject *flags) { … } static PyObject* make_flags(PyInterpreterState *interp) { … } PyDoc_STRVAR(version_info__doc__, "sys.version_info\n\ \n\ Version information as a named tuple."); static PyTypeObject VersionInfoType; static PyStructSequence_Field version_info_fields[] = …; static PyStructSequence_Desc version_info_desc = …; static PyObject * make_version_info(PyThreadState *tstate) { … } /* sys.implementation values */ #define NAME … const char *_PySys_ImplName = …; #define MAJOR … #define MINOR … #define TAG … const char *_PySys_ImplCacheTag = …; #undef NAME #undef MAJOR #undef MINOR #undef TAG static PyObject * make_impl_info(PyObject *version_info) { … } #ifdef __EMSCRIPTEN__ PyDoc_STRVAR(emscripten_info__doc__, "sys._emscripten_info\n\ \n\ WebAssembly Emscripten platform information."); static PyTypeObject *EmscriptenInfoType; static PyStructSequence_Field emscripten_info_fields[] = { {"emscripten_version", "Emscripten version (major, minor, micro)"}, {"runtime", "Runtime (Node.JS version, browser user agent)"}, {"pthreads", "pthread support"}, {"shared_memory", "shared memory support"}, {0} }; static PyStructSequence_Desc emscripten_info_desc = { "sys._emscripten_info", /* name */ emscripten_info__doc__ , /* doc */ emscripten_info_fields, /* fields */ 4 }; EM_JS(char *, _Py_emscripten_runtime, (void), { var info; if (typeof navigator == 'object') { info = navigator.userAgent; } else if (typeof process == 'object') { info = "Node.js ".concat(process.version); } else { info = "UNKNOWN"; } var len = lengthBytesUTF8(info) + 1; var res = _malloc(len); if (res) stringToUTF8(info, res, len); #if __wasm64__ return BigInt(res); #else return res; #endif }); static PyObject * make_emscripten_info(void) { PyObject *emscripten_info = NULL; PyObject *version = NULL; char *ua; int pos = 0; emscripten_info = PyStructSequence_New(EmscriptenInfoType); if (emscripten_info == NULL) { return NULL; } version = Py_BuildValue("(iii)", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__); if (version == NULL) { goto error; } PyStructSequence_SET_ITEM(emscripten_info, pos++, version); ua = _Py_emscripten_runtime(); if (ua != NULL) { PyObject *oua = PyUnicode_DecodeUTF8(ua, strlen(ua), "strict"); free(ua); if (oua == NULL) { goto error; } PyStructSequence_SET_ITEM(emscripten_info, pos++, oua); } else { PyStructSequence_SET_ITEM(emscripten_info, pos++, Py_NewRef(Py_None)); } #define SetBoolItem … #ifdef __EMSCRIPTEN_PTHREADS__ SetBoolItem(1); #else SetBoolItem(0); #endif #ifdef __EMSCRIPTEN_SHARED_MEMORY__ SetBoolItem(1); #else SetBoolItem(0); #endif #undef SetBoolItem if (PyErr_Occurred()) { goto error; } return emscripten_info; error: Py_CLEAR(emscripten_info); return NULL; } #endif // __EMSCRIPTEN__ static struct PyModuleDef sysmodule = …; /* Updating the sys namespace, returning NULL pointer on error */ #define SET_SYS … #define SET_SYS_FROM_STRING … static PyStatus _PySys_InitCore(PyThreadState *tstate, PyObject *sysdict) { … } // Update sys attributes for a new PyConfig configuration. // This function also adds attributes that _PySys_InitCore() didn't add. int _PySys_UpdateConfig(PyThreadState *tstate) { … } #undef SET_SYS #undef SET_SYS_FROM_STRING /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. Use UTF-8/backslashreplace and ignore EAGAIN errors. */ static PyStatus _PySys_SetPreliminaryStderr(PyObject *sysdict) { … } PyObject *_Py_CreateMonitoringObject(void); /* Create sys module without all attributes. _PySys_UpdateConfig() should be called later to add remaining attributes. */ PyStatus _PySys_Create(PyThreadState *tstate, PyObject **sysmod_p) { … } void _PySys_FiniTypes(PyInterpreterState *interp) { … } static PyObject * makepathobject(const wchar_t *path, wchar_t delim) { … } // Removed in Python 3.13 API, but kept for the stable ABI PyAPI_FUNC(void) PySys_SetPath(const wchar_t *path) { … } static PyObject * make_sys_argv(int argc, wchar_t * const * argv) { … } void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) { … } void PySys_SetArgv(int argc, wchar_t **argv) { … } /* Reimplementation of PyFile_WriteString() no calling indirectly PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ static int sys_pyfile_write_unicode(PyObject *unicode, PyObject *file) { … } static int sys_pyfile_write(const char *text, PyObject *file) { … } /* APIs to write to sys.stdout or sys.stderr using a printf-like interface. Adapted from code submitted by Just van Rossum. PySys_WriteStdout(format, ...) PySys_WriteStderr(format, ...) The first function writes to sys.stdout; the second to sys.stderr. When there is a problem, they write to the real (C level) stdout or stderr; no exceptions are raised. PyErr_CheckSignals() is not called to avoid the execution of the Python signal handlers: they may raise a new exception whereas sys_write() ignores all exceptions. Both take a printf-style format string as their first argument followed by a variable length argument list determined by the format string. *** WARNING *** The format should limit the total size of the formatted output string to 1000 bytes. In particular, this means that no unrestricted "%s" formats should occur; these should be limited using "%.<N>s where <N> is a decimal number calculated so that <N> plus the maximum size of other formatted text does not exceed 1000 bytes. Also watch out for "%f", which can print hundreds of digits for very large numbers. */ static void sys_write(PyObject *key, FILE *fp, const char *format, va_list va) { … } void PySys_WriteStdout(const char *format, ...) { … } void PySys_WriteStderr(const char *format, ...) { … } static void sys_format(PyObject *key, FILE *fp, const char *format, va_list va) { … } void PySys_FormatStdout(const char *format, ...) { … } void PySys_FormatStderr(const char *format, ...) { … } int _PySys_SetIntMaxStrDigits(int maxdigits) { … }