acroscene
acroscene

Reputation: 1067

virtual environment - can import package without having it installed in my venv

I have created a virtual environment in python in ubuntu in Raspberry Pi with:

python -m venv ./venv/myname

That gives me folderstructure:

   myFolder
        +-- venv
        +-- myApplication.py

Im activating my virtualenvironment running:

source venv/myname/bin/activate

What I dont understand is when I am running

python myApplication.py

I can run the application using python packages installed globally but not in my virtual environment. For example I can import numpy without having it installed in my virtual environment but globaly. I thought I needed to install everything within my virtual environment no matter if I have it globally or not. Do I misunderstand something here?

Im using python 3.7 This is my output from print(sys.path)

>>> import sys
>>> print(sys.path)
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/pi/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/local/lib/python3.7/dist-packages/Adafruit_PCA9685-1.0.1-py3.7.egg', '/usr/lib/python3/dist-packages']
>>> 

UPDATE The virtual environment seems to be running after all with testing it with os.environ['VIRTUAL_ENV']. Weird enough I can run packages I have not installed in my virtual environment. Here is output from my terminal:

(myenv) pi@raspberrypi:~/Desktop/myproject/myenv$ python
Python 3.7.3 (default, Jan 22 2021, 20:04:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['VIRTUAL_ENV']
'/home/pi/Desktop/myproject/myenv'
>>> exit()
(myenv) pi@raspberrypi:~/Desktop/myproject/myenv$ deactivate
pi@raspberrypi:~/Desktop/myproject/myenv$ pythonPython 3.7.3 (default, Jan 22 2021, 20:04:44)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['VIRTUAL_ENV']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'
>>>

Upvotes: 0

Views: 1658

Answers (1)

Keto
Keto

Reputation: 2186

It is very clear to me your virtual environment (venv) has not been activated (see this SO post for ways to verify).

You can run your programs without activating by running ./venv/myname/bin/python myApplication.py. However, you probably don't want to be using this everytime as it's verbose.

There can be a ton of system-specific reasons why your venv isn't being activated after running source. My recommendation is to first reinstall virtualenv, delete your venv, and recreate.

Upvotes: 3

Related Questions