Cloud Explainers

How to Fix Python ModuleNotFoundError: No Module Named

Python8 min video

Python's ModuleNotFoundError: No module named means the Python that ran your script searched its own list of folders and didn't find that name. On a real Ubuntu PC we fix the common causes: a script whose first line runs the system Python while pip installed into a virtual environment, a new terminal window where the environment isn't active, sudo running the system Python, an install name that isn't the import name (pip install pillow, import PIL), and your own module not found when you run a script from a subfolder (python -m).

Already installed, still not found

Your script stops with ModuleNotFoundError, yet pip says the package is already installed. John keeps his family's recipe site in Python. pip says PyYAML, the package his build script needs to import yaml, is already there. The script says: No module named yaml. So which one is wrong?

Same package, two answers: comparison table of pip says vs Python says, The answer, The project, John typed, Who is right?

In his terminal, the prompt starts with.venv in brackets: his project's virtual environment is active. Installed, then not found. There are four usual reasons, one of them a script that can't find a folder sitting right next to it.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ pip install pyyamlRequirement already satisfied: pyyaml in ./.venv/lib/python3.12/site-packages (6.0.4)
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ ./build.pyTraceback (most recent call last):
  File "/home/john/recipe-site/./build.py", line 6, in <module>
    import yaml
ModuleNotFoundError: No module named 'yaml'

The script's first line picks another Python

The usual fix starts with one question: which Python ran the script? A computer can have several Pythons, each with its own packages. John ran his script as./build.py. When you run a file directly like this, without typing python first, Linux reads its first line to pick the program. head -1 prints that line, called the shebang: /usr/bin/python3, the system's Python. But pip put PyYAML in the.venv. And which python shows that plain python, in this window, is the one inside.venv. So run the script with python build.py instead, and all six recipe pages build.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ head -1 build.py#!/usr/bin/python3
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ which python/home/john/recipe-site/.venv/bin/python
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python build.pyBuilt 6 recipe pages in public/

To fix the file itself, change that line to /usr/bin/env python3. PATH is the list of folders your shell searches for commands, and env runs the first python3 it finds there. John makes that change, and with the environment active,./build.py builds all six pages too.

Let the first line follow your environment: code change of build.py, #!/usr/bin/env python3 (the first python3 on PATH)

Where import looks

The first line is only one way to end up in the wrong Python. To spot the others, you need to know where import looks. ModuleNotFoundError is Python saying: I searched every folder on my list, and that name isn't in any of them. The list goes in order. First, the script's own folder. Then Python's standard library. Then site-packages, where pip puts what it installs. The first match wins. And every Python has its own list. The environment's Python has PyYAML in its site-packages. The system Python never looks in that folder at all.

import yaml: each Python searches only its own folders: diagram of build.py, .venv/bin/python, .venv site-packages, /usr/bin/python3, system packages, Python 1: the project's.venv, Python 2: the system's

Think of a recipe box in each kitchen. A cook only looks in the box in the kitchen they're standing in. Put Grandma's lasagna card in your sister's box, then cook at home, and the card is nowhere to be found, even though it exists.

A recipe box per kitchen, a package folder per Python: comparison table of Kitchens vs Pythons, Where you look, Where it was put, Result

You can print the list. python -m site runs a small built-in tool that shows the folders, in order. The environment's list ends in its own site-packages. Ask the system Python, and its list ends in dist-packages, Ubuntu's name for the same idea. So when pip says installed and import says no, ask the Python itself: the one-liner on screen prints sys.executable, the path of the Python that's running. Then install with that exact Python: python -m pip install. That pip can only put packages where that Python looks.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python -m site | head -7sys.path = [
    '/home/john/recipe-site',
    '/usr/lib/python312.zip',
    '/usr/lib/python3.12',
    '/usr/lib/python3.12/lib-dynload',
    '/home/john/recipe-site/.venv/lib/python3.12/site-packages',
]
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ /usr/bin/python3 -m site | head -8sys.path = [
    '/home/john/recipe-site',
    '/usr/lib/python312.zip',
    '/usr/lib/python3.12',
    '/usr/lib/python3.12/lib-dynload',
    '/usr/local/lib/python3.12/dist-packages',
    '/usr/lib/python3/dist-packages',
]
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python -c 'import sys; print(sys.executable)'/home/john/recipe-site/.venv/bin/python
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python -m pip install pyyamlRequirement already satisfied: pyyaml in ./.venv/lib/python3.12/site-packages (6.0.4)

New window: environment not active

The most common way to hit this: a new terminal window. John opens a second one in the same folder and runs python3 build.py. No module named yaml again. Look at the prompt: no.venv in front of it, so the environment isn't active here, and python3 is the system's. There isn't even a pip command for it on stock Ubuntu. Two fixes: call the environment's Python by its path,.venv/bin/python, or activate the environment in this window first, with source.venv/bin/activate. Both build the site.

John's PC: window B
python3 build.pyTraceback (most recent call last):
  File "/home/john/recipe-site/build.py", line 6, in <module>
    import yaml
ModuleNotFoundError: No module named 'yaml'
John's PC: window B
which python3/usr/bin/python3
John's PC: window B
pip install pyyaml-bash: pip: command not found
John's PC: window B
.venv/bin/python build.pyBuilt 6 recipe pages in public/
John's PC: window B
source .venv/bin/activate && python3 build.pyBuilt 6 recipe pages in public/

sudo's own PATH

Now John wants the pages in the web server's folder, which belongs to root, the system's administrator account. Permission denied, so he reaches for sudo, still in the window where the environment is active. sudo runs a command as root. Guess first: does sudo python3 find yaml? It doesn't. Same error.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python build.py /var/www/recipesTraceback (most recent call last):
  File "/home/john/recipe-site/build.py", line 15, in <module>
    (out / f"{slug(recipe['name'])}.html").write_text(page(recipe))
  File "/usr/lib/python3.12/pathlib.py", line 1049, in write_text
    with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/pathlib.py", line 1015, in open
    return io.open(self, mode, buffering, encoding, errors, newline)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: '/var/www/recipes/apple-crumble.html'
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ sudo python3 build.py /var/www/recipesTraceback (most recent call last):
  File "/home/john/recipe-site/build.py", line 6, in <module>
    import yaml
ModuleNotFoundError: No module named 'yaml'

Ask sudo which Python it ran: /usr/bin/python3. For safety, sudo swaps your PATH for its own short list of folders, called secure path. Your environment isn't on that list. It's cooking in another kitchen. So hand sudo the full path: sudo.venv/bin/python build.py, and the pages land in the web folder. Better still, give John's own account that folder, and skip sudo for Python altogether.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ sudo python3 -c 'import sys; print(sys.executable)'/usr/bin/python3
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ sudo grep secure_path /etc/sudoersDefaults	secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ sudo .venv/bin/python build.py /var/www/recipesBuilt 6 recipe pages in /var/www/recipes/

PIL and pillow

What if the name itself is the problem? Jen, John's sister, sends him her script that makes a small photo for each recipe. It stops on No module named PIL. PIL is the name in her import line. Guess first: does pip install PIL fix it? No. pip can't find anything called PIL.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python tools/thumbs.pyTraceback (most recent call last):
  File "/home/john/recipe-site/tools/thumbs.py", line 4, in <module>
    from PIL import Image
ModuleNotFoundError: No module named 'PIL'
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ pip install PILERROR: Could not find a version that satisfies the requirement PIL (from versions: none)
ERROR: No matching distribution found for PIL

The name you install isn't always the name you import. The package is called Pillow; it keeps the old import name, PIL. PyYAML installs a module called yaml. pip install pillow works, and pip freeze, which lists what's installed, shows the install names. When an import fails, search the web for the import name plus the word pip, and install the name the project's own page gives.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ pip install pillowCollecting pillow
  Downloading pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl.metadata (9.1 kB)
Downloading pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl (6.5 MB)
Installing collected packages: pillow
Successfully installed pillow-13.0.0
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ pip freezepillow==13.0.0
PyYAML==6.0.4

A few common ones are on screen. For example, import cv2 comes from the package opencv-python, and bs4 from beautifulsoup4.

Install name vs import name: cards of import PIL, import yaml, import cv2, import bs4

Your own module, run from a subfolder

Jen's script runs again, and stops one line later: No module named family. But family isn't from pip. It's John's own folder of helper code, and ls, which lists the project folder, shows it right there, next to the tools folder that holds Jen's script. So why can't Python see a folder that's right there?

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python tools/thumbs.pyTraceback (most recent call last):
  File "/home/john/recipe-site/tools/thumbs.py", line 6, in <module>
    from family.render import slug
ModuleNotFoundError: No module named 'family'
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ lsbuild.py  family  photos  public  recipes  tools

Python's tutorial says why. The first folder on the search list is the directory containing the input script. Jen's script is in tools, so Python searches tools, not the project folder John is standing in.

Your own module, run from a subfolder: browser screenshot from the video

The fix: from the project folder, type python -m tools.thumbs. That's a dot where the slash was, and no.py at the end. With -m, Python searches the folder you're in first, so it finds family, and all six thumbnails are made.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python -m tools.thumbsMade 6 thumbnails in public/thumbs/

Keep it from coming back

On a new laptop, or after deleting.venv, every one of these imports would fail again, unless the project remembers its packages. pip freeze writes them down, by install name, into a file called requirements.txt. To prove the file works, John deletes his.venv and makes a fresh one, then installs from the list with the new environment's own pip, using dash r for the file. Then both scripts run. Calling the environment's Python by its full path works even when nothing is activated.

John's PC: window A
(.venv) john@family-pc:~/recipe-site$ python -m pip freeze > requirements.txt; cat requirements.txtpillow==13.0.0
PyYAML==6.0.4
John's PC: window A
(.venv) john@family-pc:~/recipe-site$ deactivate; rm -rf .venv; python3 -m venv .venv; .venv/bin/python -m pip install -r requirements.txtCollecting pillow==13.0.0 (from -r requirements.txt (line 1))
  Using cached pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl.metadata (9.1 kB)
Collecting PyYAML==6.0.4 (from -r requirements.txt (line 2))
  Using cached pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl.metadata (2.3 kB)
Using cached pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl (6.5 MB)
Using cached pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl (814 kB)
Installing collected packages: PyYAML, pillow
Successfully installed PyYAML-6.0.4 pillow-13.0.0
John's PC: window A
.venv/bin/python build.py && .venv/bin/python -m tools.thumbsBuilt 6 recipe pages in public/
Made 6 thumbnails in public/thumbs/

Recap

So, when you see No module named: find which Python ran it, install with that Python's pip, check the install name, and run your own code from the project folder with python -m.

No module named: four checks: cards of Which Python?, Same Python's pip, Install name, Your own code

If this got your script running, subscribing brings more Python fixes, tried on a real machine.

Every command and every error in this video came from a real Ubuntu PC, and the lab files are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: one container on our own Mac standing in for a family PC; the recipe site and its scripts are made up. Every command, error and number was real. Watch the full video on YouTube.

More videos

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index