I've recently become interested in virtual environments in Python, in order to keep my code more organized and more portable. For this reason, I did a factory reset on my Raspberry Pi and started from scratch, with only the default Python modules. Beforehand I had made a list of all the dependencies for my project and their versions, and I installed them into a newly made virtual environment. Here's an example of how I did that in terminal, beginning in my project directory. (I'm hoping this is relevant to the question).
millertime@raspberrypi:~/Desktop/Project $ python3 -m venv venv
millertime@raspberrypi:~/Desktop/Project $ source venv/bin/activate
(venv) millertime@raspberrypi:~/Desktop/Project $ pip3 install mutagen==1.45.1
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting mutagen==1.45.1
Using cached https://www.piwheels.org/simple/mutagen/mutagen-1.45.1-py3-none-any.whl (218 kB)
Installing collected packages: mutagen
Successfully installed mutagen-1.45.1
(venv) millertime@raspberrypi:~/Desktop/Project $ deactivate
My main.py file and my virtual environment are in the same directory, yet when I try and import one of the modules I installed in my virtual environment, I get an error.
Traceback (most recent call last):
File "/home/millertime/Desktop/Project/test.py", line 1, in <module>
import mutagen
ModuleNotFoundError: No module named 'mutagen'
The same thing happens with all the other libraries I put in the virtual environment, except for Pygame and Pillow. I believe this to be because different versions of these came preinstalled with Python. As well, I can import os, random and anything else installed globally in Python.
This leads me to the question, how do I allow my python program to import modules contained in the virtual environment? I am using Python 3.9 on a Raspberry Pi 4.