NameError: name 'subprocess' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

nameerror name subprocess is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'subprocess' is not defined p = subprocess.Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) print(subprocess.getstatusoutput('ls /bin/ls'))

To solve the error, we have to import the subprocess module.

main.py
# ✅ import subprocess module first import subprocess p = subprocess.Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) print(subprocess.getstatusoutput('ls /bin/ls'))

Even though the subprocess 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 subprocess because module names are case-sensitive.

Also, make sure you haven't imported subprocess 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 subprocess module is to import only the functions and constants that your code uses.

main.py
from subprocess import Popen, getstatusoutput p = Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) print(getstatusoutput('ls /bin/ls'))

The example shows how to only import the Popen class and the getstatusoutput function from the subprocess module.

Instead of accessing the members on the module, e.g. subprocess.Popen, 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 subprocess, it is much harder to see which classes and functions from the subprocess module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which classes and functions from the subprocess module are being used.

The subprocess module enables us to spawn new processes, connect to their input, output and error pipes and obtain their return codes.

You can view all of the classes the subprocess module provides by visiting the official docs.

Conclusion #

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

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.