简体   繁体   中英

What does it mean that the sys module is built into every python interpreter?

I am going through the official Python tutorial, and it says

One particular module deserves some attention: sys, which is built into every Python interpreter.

However, if I start the python interpreter and type, for example, sys.path , I get a NameError: name sys is not defined .

Thus, I need to import sys if I want to have access to it.

So what does it mean that it is 'built into every python interpreter' ?

It simply means that

import sys

will succeed, regardless of which version of Python you're using. It comes with every Python installation. In contrast, eg,

import mpmath

will fail unless you've installed the mpmath package yourself, or it came bundled with the specific Python installation you're using.

So what does it mean that it is 'built into every python interpreter' ?

The sys module is written in C and compiled into the Python interpreter itself. Depending on the version of the interpreter, there may be more modules of this kind — sys.builtin_module_names lists them all.
As you have noticed, a built-in module still needs to be import ed like any other extension.

>>> import sys
>>> sys.builtin_module_names
('_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale', '_operator', '_signal', '_sre', '_stat', '_string', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'atexit', 'builtins', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 'time', 'xxsubtype', 'zipimport')

The sys module is written in C and compiled into >the Python interpreter itself. Depending on the >version of the interpreter, there may be more >modules of this kind — sys.builtin_module_names >lists them all.

It is worthy to emphasize this, the "sys" module is built into the Python interpreter, CPython or JPython or others.

You will not find a "sys.py" like normal modules.

Help(sys) will show below info

Help on built-in module sys:
NAME
    sys
FILE
    *(built-in)*

By contrast: help(os)

Help on module os:
NAME
    os - OS routines for Mac, NT, or Posix depending on what system we're on.
FILE
    */usr/lib64/python2.7/os.py*

Comparing with C, "sys" could be somewhat treated as a part of LIBC("libc.so.7").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM