Fix - NameError: name 'sys' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 'sys' is not defined in Python #

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.

nameerror name sys is not defined

Here is an example of how the error occurs.

main.py
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.

main.py
# 👇️ 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.

Make sure you haven't used a capital letter s when importing sys because 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.

main.py
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.

For example, when we use an import such as 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.