- Fix Python NameError: name ‘sys’ is not defined
- Conclusion
- Take your skills to the next level ⚡️
- About
- Search
- Tags
- Python import sys error
- # NameError: name ‘sys’ is not defined in Python
- # Import the sys module before using it
- # Make sure to not import the sys module in a nested scope
- # Make sure to not import the sys module in a try/except statement
- # Importing functions and constants from the sys module
- How to Solve Python NameError: name ‘sys’ is not defined
- Example
- Solution #1: Import sys
- Solution #2: Use the from keyword
- Summary
- Share this:
Fix Python NameError: name ‘sys’ is not defined
Python shows the NameError: name ‘sys’ is not defined error message when you call the sys module without importing it.
To fix this error, you need to import the sys module at the beginning of your script.
The sys module is a built-in Python module that provides access to system-related information, such as the version of your Python interpreter, the OS platform, or the command-line arguments added.
When you try to access the module as shown below:
If you didn’t add an import statement at the top of the file, Python will respond with the following error:
To fix this error, add an import statement at the top of your Python script file as shown below:
Also, please make sure that you are not importing the sys module in a nested scope as shown below:
The example above imports the sys module inside the print_sys_info() function.
When accessing the sys.platform constant outside the function, the error occurs.
This is because importing a module inside a function only makes it available within that function scope. The module won’t be available globally.
If you need the module outside of the function, then place the import statement at the top-level as shown below:
Alternatively, you can import only specific functions and constants you need into your code:
Named imports as shown above give you more clarity as to which part of the module you used in the code.
You also optimize your Python code by importing only specific functions and constants that you need.
You can read all of the functions and constants defined in the sys module on the Python sys documentation page.
Conclusion
To summarize, the Python NameError: name ‘sys’ is not defined error occurs when the sys module is not imported.
To solve this error, make sure to import the sys module at the beginning of your script and use its functions and variables as you need.
Good work solving the error! 👍
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Python import sys error
Last updated: Feb 1, 2023
Reading time · 3 min
# 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 .
Here is an example of how the error occurs.
Copied!print('before') # ⛔️ NameError: name 'sys' is not defined print(sys.version) print(sys.exit()) print('after')
# Import the sys module before using it
To solve the error, we have to import the sys module.
Copied!# 👇️ 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.
# Make sure to not import the sys module in a nested scope
Also, make sure you haven’t imported sys in a nested scope, e.g. a function.
Copied!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.
Copied!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.
# Make sure to not import the sys module in a try/except statement
You also should be importing the sys module in a try/except statement.
Copied!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.
Copied!import sys try: print(sys.version) except ImportError: print(sys.platform) print(sys.platform)
# Importing functions and constants from the sys module
An alternative to importing the entire sys module is to import only the functions and constants that your code uses.
Copied!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.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to Solve Python NameError: name ‘sys’ is not defined
Python raises the NameError when it cannot recognise a name in our program. In other words, the name we are trying to use is not defined in the local or global scope. A name can be related to a built-in function, module, or something we define in our programs, like a variable or a function.
The error typically arises when:
- We misspell a name
- We do not define a variable or function
- We do not import a module
In this tutorial, the source of the error NameError: name ‘sys’ is not defined is usually due to not importing the module. Let’s look at an example.
Example
The sys module in Python provides access to some of the variables used or maintained by the Python interpreter. The module also provides functions to manipulate different aspects of the Python runtime environment.
The sys module is built-in, which means it comes with Python. One of the most used functions is sys.argv() which provides a list containing the command line arguments passed to a Python script. Let’s look at an example:
n = len(sys.argv) print('Total arguments passead: ', n,'\n') print('Name of the Python script: ', sys.argv[0], '\n') print('Arguments passed to script:', end = ' ') for i in range(1, n): print(sys.argv[i], end=' ') sum_val = 0 for i in range(1, n): sum_val += int(sys.argv[i]) print(f'\n\nSum value: ')
In the above code, we use sys.argv to take in several arguments, the first argument is always the name of the Python script. Next, we define a variable called sum_val and incrementally add the numeric arguments to it.
Let’s try to run the script with five integers as arguments:
python sum_script.py 1 2 3 4 5
Traceback (most recent call last): File "sum_script.py", line 1, in n = len(sys.argv) NameError: name 'sys' is not defined
The error occurred because we did not import the sys module. Although sys is a built-in module, we still need to import it.
Solution #1: Import sys
We can import the module by putting an import statement at the top of the program. Let’s look at the updated code:
import sys n = len(sys.argv) print('Total arguments passead: ', n,'\n') print('Name of the Python script: ', sys.argv[0], '\n') print('Arguments passed to script:', end = ' ') for i in range(1, n): print(sys.argv[i], end=' ') sum_val = 0 for i in range(1, n): sum_val += int(sys.argv[i]) print(f'\n\nSum value: ')
Let’s run the code to get the sum of the five numbers:
python sum_script.py 1 2 3 4 5
Total arguments passead: 6 Name of the Python script: sum_script.py Arguments passed to script: 1 2 3 4 5 Sum value: 15
Solution #2: Use the from keyword
We can also use the from keyword to import a specific variable, class or function from a module. In this case, we want to import the argv() function from the sys module.
Using the from keyword means we do not have to specify the module in the rest of the program, we only need the argv() function.
Let’s look at the updated code:
from sys import argv n = len(argv) print('Total arguments passead: ', n,'\n') print('Name of the Python script: ', argv[0], '\n') print('Arguments passed to script:', end = ' ') for i in range(1, n): print(argv[i], end=' ') sum_val = 0 for i in range(1, n): sum_val += int(argv[i]) print(f'\n\nSum value: ')
Let’s run the code to get the sum of the numbers:
python sum_script.py 1 2 3 4 5
Total arguments passead: 6 Name of the Python script: sum_script.py Arguments passed to script: 1 2 3 4 5 Sum value: 15
Summary
Congratulations on reading to the end of this tutorial!
For further reading on NameErrors, go to the articles:
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!