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.
-
1That's the concept of virtual environments: you activate them to work.Klaus D.– Klaus D.2021-10-08 17:30:16 +00:00Commented Oct 8, 2021 at 17:30
-
Your script runs fine, then what do you need help with?chickity china chinese chicken– chickity china chinese chicken2021-10-08 17:33:51 +00:00Commented Oct 8, 2021 at 17:33
2 Answers
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.
4 Comments
chmod 755 ...) and run directly /path/to/script, NOT with python3 /path/to/script or else the shebang line is not evaluated by the shell.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.