Reputation: 3
A python script that uses cv2 runs fine from command line once the virtual environment is activated ((venv) pi@raspberrypi:~/test $ python3 openCV_motion_detection_cam1.py
). But when run from normal command line (pi@raspberrypi:~/test $ python3 openCV_motion_detection_cam1.py
) , it outputs error - "No module named 'cv2'", which is already inside /home/pi/test/venv/lib/python3.7/site-packages.I am a newbie and expecting your comments to be 'Noob' friendly . Please help.
Upvotes: 0
Views: 2910
Reputation: 17267
If you want to directly run a script in a virtual env, edit the shebang line to include the Python interpreter from that env:
#!/path/to/env/bin/python3
That interpreter will find the pyvenv.cfg
file at its parent directory and will adjust all paths accordingly. That is an equivalent of activating the environmnet.
The process can be automated. Create a package with a setup.py
and declare which files are scripts. When the package is installed, the scripts will be installed in the <venv>/bin
subdirectory with correct shebang lines.
You may want to create a symlink from /usr/bin
to have the script in the path.
Upvotes: 2
Reputation: 1083
Virtual environments exist to isolate the modules needed for individual python programs from each other. When you installed cv2 you installed it within your currently active venv. When the venv is not active it's modules will not be available on. Simple solution is to run your program within the venv.
You can tell that the module exists within a venv by the /venv/lib/python37/site-packages
portion of the modules path.
Upvotes: 1