Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'sys' is not defined" occurs when we use the
module without importing it first. To solve the error, import the
before using it -
Here is an example of how the error occurs.
print('before') # ⛔️ NameError: name 'sys' is not defined print(sys.version) print(sys.exit()) print('after')
To solve the error, we have to import the sys module.
# 👇️ import sys first import sys print('before') print(sys.version) print(sys.exit()) print('after')
Even though the
sys module is in the Python standard library, we still have to
import it before using it.
sysbecause module names are case-sensitive.
Also, make sure you haven't imported
sys in a nested scope, e.g. a function.
Import the module at the top level to be able to use it throughout your code.
An alternative to importing the entire
sys module is to import only the
functions and constants that your code uses.
from sys import version, exit print('before') print(version) print(exit()) print('after')
The example shows how to import the
exit() function and the
Instead of accessing the members on the module, e.g.
sys.exit(), we now access
This should be your preferred approach because it makes your code easier to read.
import sys, it is much harder to see which functions from the
sysmodule are being used in the file.
Conversely, when we import specific functions, it is much easier to see which
functions from the
sys module are being used.
sys module provides access to variables used by the Python interpreter and
to functions that interact with the interpreter.
You can view all of the functions and constants the
sys module provides by
visiting the official docs.