Borislav Hadzhiev
Last updated: Apr 18, 2022
Check out my new book
The Python "ModuleNotFoundError: No module named 'thread'" occurs when we
incorrectly import the _thread
module or shadow it with a thread.py
file. To
solve the error, import the module as import _thread
command.
import _thread a_lock = _thread.allocate_lock() with a_lock: print("a_lock is locked while this runs")
The thread module was renamed to _thread in Python v3.
If you need a universal import that works for both Python 2 and 3, use a
try/except
statement.
try: import _thread as thread # using Python 3 except ImportError: import thread # falls back to import from Python 2 a_lock = thread.allocate_lock() with a_lock: print("a_lock is locked while this runs")
We try to import the _thread
module (Python 3) and if we get an ImportError
,
we know the file is being ran in Python 2, so we import thread
instead.
We aliased the _thread
module to thread
for consistency.
If you meant to use the
threading module import
threading
instead.
import threading print(threading.Thread)
The Python error "ModuleNotFoundError: No module named 'thread'" occurs for multiple reasons:
thread.py
which would shadow the official module.thread
which would shadow the imported variable.If you aren't sure what version of Python you're using, run the
python --version
command.
python --version
If you are in a virtual environment, the version of Python corresponds to the version that was used to create the virtual environment.
For example, In VSCode, you can press CTRL + Shift + P
or (⌘
+ Shift
+ P
on Mac) to open the command palette.
Then type "Python select interpreter" in the field.
Then select the correct python version from the drop down menu.
If you aren't sure whether your virtual environment is created using the correct Python version, try recreating it or creating a new virtual environment if you don't have one.
The _thread
module is from the standard library so it will be available in a
virtual environment.
# 👇️ deactivate deactivate # 👇️ remove the old virtual environment folder rm -rf venv # 👇️ specify correct Python version python3 -m venv venv # 👇️ activate on Unix or MacOS source venv/bin/activate # 👇️ activate on Windows (cmd.exe) venv\Scripts\activate.bat # 👇️ activate on Windows (PowerShell) venv\Scripts\Activate.ps1 # 👇️ install the modules in your requirements.txt file pip install -r requirements.txt
Your virtual environment will use the version of Python that was used to create it.