ModuleNotFoundError: No module named, después de un despliegue
Python buscó en sys.path y no encontró el módulo que importas. Después de un despliegue, eso casi siempre significa que el paquete no está en requirements.txt, que aparece con un nombre distinto del que importas o que el comando de arranque ejecuta un Python en el que no se instalaron los paquetes.
Por El equipo de Livops, las personas que construyen y operan LivopsActualizado el
Así se ve cuando una app o un bot desplegado se detiene por este error:
Traceback (most recent call last):
File "/app/bot.py", line 3, in <module>
from aiogram import Bot, Dispatcher
ModuleNotFoundError: No module named 'aiogram'
Esta página explica qué te está diciendo Python, enumera las causas de la más común a la menos, muestra cómo reproducir en tu máquina el entorno del servidor y cuenta qué hace Livops cuando una app se detiene así.
¿Qué significa el error?
ModuleNotFoundError es la subclase de ImportError que lanza import cuando no se encuentra un módulo[1]. Python busca los módulos en las carpetas que figuran en sys.path, que empieza por el directorio del script que ejecutaste, luego PYTHONPATH y después el site-packages de la instalación[2]. Si el nombre no está en ninguna de ellas, aparece este error.
Así que la pregunta es siempre la misma: ¿en qué entorno instaló el servidor los paquetes, y está ahí el módulo?
Causas, de la más común a la menos
1. El paquete no está en requirements.txt
Lo instalaste con pip install mientras escribías el código y nunca lo anotaste. El servidor solo instala lo que figura en el archivo. Añádelo:
aiogram>=3.4
pip freeze escribe todo lo que está instalado[5]; ejecútalo dentro de un entorno virtual limpio, o también listará todos los paquetes ajenos al proyecto que tengas en tu máquina.
2. El nombre del import no es el nombre del paquete
El nombre que va después de import no siempre es el nombre en PyPI:
| Importas | Pon en requirements.txt |
|---|---|
PIL |
Pillow |
cv2 |
opencv-python-headless |
yaml |
PyYAML |
dotenv |
python-dotenv |
telegram |
python-telegram-bot |
bs4 |
beautifulsoup4 |
sklearn |
scikit-learn |
jwt |
PyJWT |
3. La app se ejecuta con otro Python
Los paquetes se instalaron en un entorno virtual, pero el comando de arranque ejecuta el python del sistema o un gunicorn que está fuera de él. Arranca la app con el intérprete del propio entorno:
.venv/bin/python bot.py
.venv/bin/python -m gunicorn app:app
No subas .venv al repositorio para que esto funcione: un entorno virtual no se puede mover ni copiar, solo recrear allí donde se ejecuta[3].
4. El módulo es una carpeta tuya
No module named 'config' o 'app' tiene que ver con tu código, no con PyPI:
- la carpeta no está en el repositorio: revisa
git ls-files config/y.gitignore; - las mayúsculas no coinciden:
Config.pyen disco eimport configen el código; Linux no los considera iguales; - la app arranca desde otro directorio, así que la carpeta no está junto al script que Python puso en
sys.path. Arranca desde la raíz del proyecto y ejecuta un paquete como módulo:python -m mybot.
5. Está en un archivo solo para desarrollo
El paquete está en requirements-dev.txt, o dependes de un extra (uvicorn[standard]) que el archivo de producción incluye sin él. Muévelo al archivo que instala el servidor.
6. Cambió la versión de Python
Python 3.12 eliminó distutils, imp, asynchat y asyncore de la biblioteca estándar[4]; un paquete antiguo que los importa falla en un Python más nuevo. Actualiza el paquete, instala setuptools (que todavía proporciona distutils)[4] o fija la versión de Python para la que se escribió el código.
Cómo confirmar la solución en local
Recrea lo que hace el servidor: un entorno virtual nuevo con solo requirements.txt instalado.
python3 -m venv /tmp/check
/tmp/check/bin/pip install -r requirements.txt
/tmp/check/bin/python -c "import aiogram"
/tmp/check/bin/python bot.py
Si la línea del import pasa y la app arranca, el servidor también encontrará el módulo. Para tus propias carpetas, git status --ignored lista lo que Git deja fuera.
En Livops
- Un solo entorno, el que usa el comando de arranque. Livops instala las dependencias en el
.venvpropio del proyecto y, cuando toma el comando de arranque de tuProcfile, hace que unpython,gunicorn,uvicorn,celery,flaskopipsin ruta apunte a.venv/bin. Los comandos que escribe él mismo ya empiezan por.venv/bin/. Si escribes un comando de arranque en Settings → Start, pon tú.venv/bin/python. - Una línea Tip que nombra el paquete. Cuando la app se detiene con
No module named 'X', el log incluye una línea Tip:: si es una biblioteca, qué paquete añadir arequirements.txt(traducido para los casos habituales de la tabla de arriba y otros, comotelebotapyTelegramBotAPI), y si es una carpeta tuya, que compruebes que está en el commit con sus archivos. - Un arranque fallido no tumba un sitio. El despliegue falla como
start_failed, y la versión anterior de una app web sigue en ejecución. La versión anterior de un bot se detuvo antes de que arrancara la nueva, así que el bot está caído hasta que un despliegue salga bien. - Versión de Python. Livops ejecuta de Python 3.10 a 3.14; indica la versión en un archivo
.python-versionen la raíz del proyecto. - El asistente explica. El botón junto a un despliegue fallido lee el log y dice qué cambiar. No edita
requirements.txtpor ti; tú haces commit de la solución y vuelves a desplegar.
El mismo caso está en la documentación: Python no encontró un módulo.
Preguntas
¿Por qué funciona en mi ordenador y no en el servidor?
Tu ordenador tiene el paquete instalado, de forma global o en un entorno virtual, y el servidor solo instala lo que figura en requirements.txt. Instala desde requirements.txt en un entorno virtual nuevo y verás el mismo error en local.
El paquete está en requirements.txt. ¿Por qué sigue faltando?
O el nombre que importas no es el que instala pip (import PIL viene de Pillow), o la app se ejecuta con un Python distinto de aquel en el que se instalaron los paquetes. Comprueba que el comando de arranque ejecuta el python del entorno virtual.
¿Debo subir la carpeta .venv al repositorio?
No. Un entorno virtual no se puede mover ni copiar; está pensado para recrearse allí donde se ejecuta. Sube requirements.txt y deja que el servidor construya el suyo.
El módulo que falta es una carpeta mía. ¿Y ahora?
Comprueba que la carpeta está en el commit con sus archivos y que .gitignore no la excluye, que las mayúsculas y minúsculas del nombre coinciden y que la app arranca desde la raíz del proyecto, para que la carpeta esté en sys.path.
¿Me dice Livops qué paquete tengo que añadir?
Sí: con este error, el log incluye una línea Tip con el paquete que hay que poner en requirements.txt, incluidos los casos habituales en los que difiere del nombre del import, como cv2 y opencv-python-headless.
Fuentes
- Python docs — Built-in exceptions (ModuleNotFoundError) (docs.python.org). Consultado el .
- Python docs — Tutorial, Modules (the module search path) (docs.python.org). Consultado el .
- Python docs — venv (docs.python.org). Consultado el .
- Python docs — What's New in Python 3.12 (docs.python.org). Consultado el .
- pip — User Guide (requirements files) (pip.pypa.io). Consultado el .
Pon tu proyecto en línea hoy
Conecta GitHub o sube una carpeta. No se pide tarjeta.
Despliega tu app de PythonRelacionado
- ModuleNotFoundError: No module named 'pkg_resources': how to fix itModuleNotFoundError: No module named 'pkg_resources' means code imported pkg_resources, which is part of setuptools, not the standard library. Python 3.12 stopped pre-installing setuptools in new virtual environments, and setuptools 82.0.0 removed pkg_resources altogether, so installing the latest setuptools no longer brings it back. Upgrade the package that imports it, move your own code to importlib.metadata and importlib.resources, or pin setuptools<82 as a stopgap.
- ModuleNotFoundError: No module named 'imp' on Python 3.12+: how to fix itModuleNotFoundError: No module named 'imp' means code running on Python 3.12 or later imported imp, which was deprecated since Python 3.4 and removed from the standard library in 3.12. It is almost always an old release of a library, or old code of your own. Upgrade that library, replace the imp calls with their importlib equivalents, or pin Python 3.11 with a .python-version file while you upgrade.
- ModuleNotFoundError: No module named 'distutils' on Python 3.12+: how to fix itModuleNotFoundError: No module named 'distutils' means code running on Python 3.12 or later imported distutils, which PEP 632 removed from the standard library in 3.12. It is usually an old package pinned in requirements.txt, built from source or imported at runtime. Upgrade that package to a release that supports your Python, install setuptools for code that still imports distutils, or pin Python 3.11 with a .python-version file while you upgrade.
- ImportError: attempted relative import with no known parent package: how to fix itImportError: attempted relative import with no known parent package means Python ran the file as a script, so it has no package for an import like from .config import X to start from. Run it as a module from the project root with python -m mybot.main, or import absolutely from a start file at the root. Its sibling, attempted relative import beyond top-level package, means the dots climb above the top package, usually because Python was started inside the package folder.
- Gunicorn "Worker failed to boot": what it means and how to fix itGunicorn's worker could not load your application, so the master process shut down. The cause is the Python traceback printed just above the message: most often a missing package or variable, or a wrong module:variable path in the gunicorn command. Fix what the traceback names and the workers boot.
- DisallowedHost: Invalid HTTP_HOST header — Django's 400 Bad RequestDjango received a request for a host name that is not in ALLOWED_HOSTS, so it answered 400 Bad Request. Add the domain the site is served on to ALLOWED_HOSTS, without https:// and without a port, or read the list from an environment variable, and redeploy.
- Conflict: terminated by other getUpdates request: cómo solucionarloTelegram le está diciendo a tu bot que otro proceso llamó a getUpdates con el mismo token y se quedó con la conexión. Hay dos copias del bot haciendo polling a la vez: detén la otra (normalmente la copia que sigue en ejecución en tu ordenador o en un servidor antiguo), o consigue un token nuevo en @BotFather, y el error desaparece.
- pip: Failed building wheel / failed-wheel-build-for-install — cómo solucionarlopip no encontró una wheel ya compilada de un paquete para tu versión de Python y tu plataforma, intentó compilar una a partir del código fuente y el paso de compilación falló. La solución casi nunca es instalar un compilador: pasa a una versión del paquete que publique una wheel para tu Python, cambia a su variante binaria (psycopg[binary], psycopg2-binary) o fija la versión de Python que el paquete admite.
- ImportError: cannot import name 'url_quote' from 'werkzeug.urls': how to fix itImportError: cannot import name 'url_quote' from 'werkzeug.urls' means a Flask from 2.0 to 2.2.3 was installed next to Werkzeug 3, which removed url_quote and almost all of werkzeug.urls. Flask 2.x asks only for a minimum Werkzeug, so a fresh install on the server picks the newest one while your laptop keeps the old one. Pin the Werkzeug that works (Werkzeug<3), or upgrade to Flask 3 together with your extensions.
- PydanticImportError: BaseSettings has been moved to the pydantic-settings package — how to fix itPydanticImportError: BaseSettings has been moved to the pydantic-settings package means code written for Pydantic 1 is running on Pydantic 2, which moved BaseSettings into a separate package. Add pydantic-settings to requirements.txt, import it with from pydantic_settings import BaseSettings, and move class Config to model_config = SettingsConfigDict(...). Pinning pydantic<2 also gets the app running, but only as a stopgap.
- ImportError: cannot import name 'Markup' from 'jinja2' (or 'escape'): how to fix itImportError: cannot import name 'Markup' from 'jinja2', and the same error for 'escape', means something imported those names from Jinja2 while Jinja2 3.1 or later is installed. Jinja2 3.1.0 removed them; they live in MarkupSafe. The usual culprit is an old Flask 1.x pinned in requirements.txt next to an unpinned Jinja2. Upgrade Flask or the package the traceback names, import Markup and escape from markupsafe in your own code, or pin the old versions as a stopgap.
- ImportError: libGL.so.1: cannot open shared object file (import cv2): how to fix itImportError: libGL.so.1: cannot open shared object file: No such file or directory on import cv2 means the opencv-python package, built for desktops, needs the system OpenGL library and your slim image or server does not have it. On a server, install opencv-python-headless instead, and only that one OpenCV package; if you really need the GUI build, install libgl1 in the Dockerfile.