How to Fix the Python “No Module Named websockets.legacy” Error
Fix Python’s websockets.legacy import error by checking the active interpreter, package version, dependency constraints, and legacy API migration path.

Direct answer: ModuleNotFoundError: No module named 'websockets.legacy' usually means the program is using a websockets release older than 9.0, a different Python environment from the one where websockets was installed, or a dependency whose version constraints do not match your installed package. Check the traceback, interpreter, installed package, and dependency graph before changing versions.
The websockets.legacy package was introduced in websockets 9.0 when several modules moved under that namespace. In websockets 14.0, the newer asyncio implementation became the default, but the legacy implementation remained available and deprecated. The project’s current documentation says legacy support is planned through November 2029. See the official upgrade guide and 9.0 changelog entry.
1. Read the traceback before changing anything
Find the first line that imports websockets.legacy. It may be your code, or it may be a package such as a server framework. The final exception names the missing module; it does not identify which package should be upgraded or downgraded.
Traceback (most recent call last):
...
File ".../some_dependency/...", line 42, in <module>
from websockets.legacy.client import connect
ModuleNotFoundError: No module named 'websockets.legacy'
If the importer is inside a dependency, changing your own imports may not fix the problem. Record the importer and its version before selecting a repair.
2. Verify the Python interpreter and websockets installation together
Run these commands with the same command context that launches your application. Using python -m pip runs pip for the interpreter selected by python, which avoids installing into one Python while running another. The pip user guide documents this interpreter-specific pattern.

python -c "import sys; print(sys.executable); print(sys.version)"
python -m pip show websockets
python -m pip check
Interpret the results as follows:
| Result | Likely meaning | Next step |
|---|---|---|
pip show reports nothing |
websockets is not installed in this interpreter | Install it in this interpreter or follow the project’s lock workflow |
| Version is older than 9.0 | The package predates websockets.legacy |
Choose a release compatible with your application and Python version |
| Version is recent but import still fails | Different interpreter, shadowed package, broken install, or dependency conflict | Check paths, reinstall in the active environment, and inspect the importer |
pip check reports conflicts |
Installed versions violate declared requirements | Resolve project constraints instead of blindly upgrading one package |
3. Confirm which package Python is importing
python -c "import importlib.util; print(importlib.util.find_spec('websockets'))"
python -c "import websockets; print(websockets.__file__); print(getattr(websockets, '__version__', 'unknown'))"
A local file or directory named websockets.py or websockets/ can shadow the third-party package. Rename that local path and remove its __pycache__ if the printed location points into your project unexpectedly.
4. Install or repair websockets in the active environment
If the package is missing or too old, the basic installation command is:
python -m pip install websockets
The current installation guide lists Python 3.11 or newer for current websockets releases; do not apply that requirement to historical releases automatically. Check the release requirements for the Python version used by your project in the official installation guide.
For a virtual environment:
python -m venv .venv
# macOS/Linux
. .venv/bin/activate
# Windows PowerShell
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install websockets
For an existing project, prefer editing requirements.txt, pyproject.toml, or the project’s lock file and then running its normal install command. An unmanaged global install can leave CI, containers, and production using a different dependency set.
5. Choose a compatible version instead of blindly pinning latest
There is no universal version pin for this error. Compare:
- the Python version supported by your runtime;
- the version range declared by the importing package;
- the websockets version in your lock file;
- whether the importing code requires legacy APIs or can migrate;
- whether the failure occurs locally, in CI, or only inside a container.
If a dependency imports websockets.legacy, update that dependency when a compatible release exists. If it explicitly requires an older websockets range, follow that constraint or replace the dependency. A reported server traceback, for example, showed a transitive importer requesting websockets.legacy.handshake; that pattern demonstrates why the dependency owning the import matters. See the dependency-conflict report for an example.
6. Migrate your own code from legacy imports
The websockets upgrade guide maps legacy imports to the current asyncio API. For example:
# Older style
from websockets.legacy.client import connect
from websockets.legacy.server import serve
# Current convenience imports
from websockets import connect, serve
Migration is appropriate when your application owns the import and the current API provides the behavior you need. It does not repair a third-party package that still imports legacy modules internally; upgrade or constrain that package instead.
7. Verify the fix with a minimal import and connection
python - <<'PY'
import asyncio
import websockets
print("websockets:", getattr(websockets, "__version__", "unknown"))
async def main():
async with websockets.connect("wss://echo.websocket.events") as ws:
await ws.send("diagnostic")
print(await ws.recv())
asyncio.run(main())
PY
If your environment cannot reach the public endpoint, test only the import first:
python -c "import websockets; print('import ok')"
8. Common errors and fixes
“I installed websockets, but the error remains”
Cause: pip installed into a different interpreter, often because pip and python resolve to different installations.
Fix: use python -m pip, compare sys.executable with python -m pip show websockets, and restart the process, IDE, notebook kernel, or service.
“It works in a shell but fails in VS Code, Jupyter, or a service”
Cause: the editor, notebook kernel, systemd unit, Docker image, or process manager selected another interpreter.
Fix: print sys.executable from the failing launch context and install dependencies there. Rebuild the image or restart the service after changing dependencies.
“Upgrading websockets breaks another package”
Cause: the other package declares an incompatible version range or depends on legacy behavior.
Fix: run python -m pip check, inspect the dependency metadata and lock file, then upgrade the importer or select a compatible websockets release. Do not remove constraints just to silence the import error.
“The package exists, but Python cannot find websockets.legacy”
Cause: an old release, a partial installation, or a local module shadowing the package.
Fix: inspect websockets.__file__ and its version, remove shadowing names, then reinstall in the active environment if needed.
“The error appears only after upgrading to websockets 14”
Cause: version 14 changed the default implementation behind convenience imports. Legacy modules were still available but deprecated.
Fix: migrate your imports using the official mapping, or update the dependency that owns the legacy import. The change does not mean that every legacy import should be deleted immediately; compatibility depends on the caller.
“Installing the newest release fails on my Python version”
Cause: current websockets releases have newer Python requirements than historical releases.
Fix: upgrade Python if your project allows it, or choose a websockets release supported by your current Python and declared dependency constraints.
9. Reproducible dependency practices
- Declare websockets in the project dependency file instead of relying on a global install.
- Commit the lock file used by your package manager.
- Run
python -m pip checkin CI. - Log
sys.executableand package versions when diagnosing deployment-only failures. - Rebuild containers after dependency changes; an already-built image will retain its old site-packages.
- Test the exact entry point that failed, not only an interactive shell.
10. Performance, reliability, and cost considerations
Installing a compatible package is normally a startup and deployment concern; it should not add measurable work to each WebSocket message. Runtime behavior depends on the websockets API, event loop, network, server, and reconnect strategy. Keep dependency resolution deterministic so a fresh deploy does not silently select a different major version.

The software itself is open source; this error does not require purchasing hardware or a hosted service. Budget for the operational work involved in upgrading Python, rebuilding images, restarting workers, and validating compatibility in CI.
Or skip the browser setup
If the task that led you here is collecting screenshots for documentation, previews, or an AI workflow, ScreenshotNeo provides a single HTTP request instead of maintaining browser automation. Its API removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. It also provides an MCP server for AI agents and supports PNG, JPEG, WebP, and PDF output. See the ScreenshotNeo API documentation.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo includes full-page capture, element selectors, device presets, custom CSS and JavaScript, waits, blocking rules, headers, cookies, geolocation, caching, signed links, asynchronous jobs, bulk capture, usage reporting, and PDF options. Plans include 1,000 free screenshots each month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
FAQ
Was websockets.legacy removed?
No. It was introduced in 9.0, and the current documentation describes it as deprecated with planned maintenance through November 2029.
Should I always downgrade websockets?
No. First identify the importer, Python version, and declared dependency range. Upgrade the importer or migrate your own code when possible.
Why does pip show disagree with my application?
They are using different interpreters or environments. Run both inspection and installation through the same python -m pip executable used to launch the application.
Can I ignore the warning if the application starts?
Do not ignore a missing-module exception. A fallback path may hide the problem until a worker, deployment, or code path imports the missing module.


