NameError: name 'argv' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'argv' is not defined in Python #

The Python "NameError: name 'argv' is not defined" occurs when we use the argv list without importing it from the sys module first. To solve the error, import argv before using it - from sys import argv.

nameerror name argv is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'argv' is not defined print(argv) print(argv[0]) print(argv[1:])

To solve the error, we have to import the argv list from the sys module.

main.py
# ✅ import argv list from sys first from sys import argv print(argv) print(argv[0]) print(argv[1:])

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 misspelled anything in the import statement because names of variables and modules are case-sensitive.

Also, make sure you haven't imported argv 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 argv list directly is to import the sys module and access argv as sys.argv.

main.py
# ✅ import entire sys module import sys print(sys.argv) print(sys.argv[0]) print(sys.argv[1:])

In general it is better to import only the functions, variables and classes your code uses rather than importing the entire module.

For example, when we use an import such as import sys, it is much harder to see which functions and variables from the sys module are being used in the file.

Conversely, when we import specific functions and variables, it is much easier to see which are being used.

The argv variable is a list of command line arguments that are passed to the Python script.

The first item in the list (argv[0]) is the name of the script.

You can view all of the functions and constants the sys module provides by visiting the official docs.

Conclusion #

The Python "NameError: name 'argv' is not defined" occurs when we use the argv list without importing it from the sys module first. To solve the error, import argv before using it - from sys import argv.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.