Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "ModuleNotFoundError: No module named 'Queue'" occurs when we
import the queue
module incorrectly or shadow it with a queue.py
file. To
solve the error, import the module as import queue
and don't name your files
queue.py
.
Here is how you would import and use the queue module.
import threading # 👇️ make sure to import with lowercase q import queue # 👇️ assign to variable q = queue.Queue() def worker(): while True: item = q.get() print(f'Working on {item}') print(f'Finished {item}') q.task_done() # Turn-on the worker thread. threading.Thread(target=worker, daemon=True).start() # Send 15 task requests to the worker. for item in range(15): q.put(item) # Block until all tasks are done. q.join() print('All work completed')
Note that we imported queue
with lowercase q
. The module uses an uppercase
Q
in Python 2.
The Python error "ModuleNotFoundError: No module named 'Queue'" occurs for multiple reasons:
Q
).queue.py
which would shadow the official module.queue
which would shadow the imported variable.If you need a universal import that works for both Python 2 and 3, use a
try/except
statement.
try: import queue # using Python 3 except ImportError: import Queue as queue # falls back to import from Python 2
We try to import the queue
module (Python 3) and if we get an ImportError
,
we know the file is being ran in Python 2, so we import using an uppercase Q
and alias the import to queue
.
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.
# 👇️ 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.