How do I resolve modulenotfounderror: no module named 'yaml' even though PyYAML is installed?

I’m trying to run a Python script using: python3 env/common_config/add_imagepullsecret.py

But I keep getting this error:

ImportError: No module named 'yaml'

I’ve already installed PyYAML, and running pip3 install pyyaml says:

Requirement already satisfied: pyyaml in /usr/lib64/python3.4/site-packages (3.12)

Still, the script fails with modulenotfounderror: no module named ‘yaml’. I suspect this might be a Python environment or version issue.

How can I fix this and ensure my script finds and imports the PyYAML module correctly?

One possibility is that pip3 installed pyyaml for a different Python version than the one your script is using. It’s especially common on systems with both Python 2.x and 3.x, or multiple 3.x versions installed. Try running:

python3 -m pip install pyyaml

That ensures you’re installing pyyaml into the same environment that python3 uses. Also, double-check the shebang at the top of your script - if it’s #!/usr/bin/python, you might accidentally be using an older Python version that doesn’t have the package.

Given the path /usr/lib64/python3.4/site-packages, it looks like pyyaml is tied to Python 3.4, which is pretty outdated. If your current python3 points to something like 3.8 or 3.10, it won’t see that package. You can confirm with:

python3 --version

If it’s not 3.4, then your PyYAML install isn’t available to that interpreter. Installing it specifically for the version in use should solve the issue:

python3 -m pip install --upgrade pyyaml

Or, if you’re using a virtual environment, activate it first and then run the install inside that context.