Last updated: Apr 8, 2024
Reading time·3 min
The Python "NameError: name 'sys' is not defined" occurs when we use the sys
module without importing it first.
To solve the error, import the sys
module before using it - import sys
.
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')
sys
module before using itTo 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.
s
when importing sys
because module names are case-sensitive.sys
module in a nested scopeAlso, make sure you haven't imported sys
in a nested scope, e.g. a function.
def get_version(): import sys print(sys.version) # ⛔️ NameError: name 'sys' is not defined print(sys.exit())
We imported the sys
module in a function, so we aren't able to use it outside
of the function.
Import the module at the top level to be able to use it throughout your code.
import sys def get_version(): print(sys.version) get_version() print(sys.exit())
The import statement for the sys
module has to come at the top of the file
before any code that makes use of it.
sys
module in a try/except statementYou also should be importing the sys
module in a
try/except statement.
try: # 👉️ Code here could raise an error import sys print(sys.version) except ImportError: print(sys.platform) print(sys.platform)
The code sample works, however, if the code in the try
statement raises an
error, the sys
module won't get imported successfully.
This would cause the error because we are trying to access properties on the
sys
module in the outer scope and the except
block.
Instead, move the import statement to the top of the file.
import sys try: print(sys.version) except ImportError: print(sys.platform) print(sys.platform)
sys
moduleAn 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 version
constant
from the sys
module.
Instead of accessing the members on the module, e.g. sys.exit()
, we now access
them directly.
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 sys
module 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.
The 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.