Search code examples
pythonenvironment-variablesdevelopment-environmentvirtual-environment

Question about virtual environments, PATH variable and command line


If I install a python package onto my computer globally, and then add that package's location to my PATH variable, then my command line can find it without me typing out the complete path every time I want to execute.

How does this work inside of a virtual environment? For example I just used pip install ffmpeg inside of my project's activated virtual environment. I can see it inside of my venv/Lib/site-packages folder, but my command line cannot find it. How do I do the virtual environment equivalent of adding ffmpeg's location to my PATH variable?


Solution

  • As chepner mentioned in their comment above, this should already work if you have activated your virtual environment. You can convince yourself or double check which location you are running from by looking at __file__ for the module:

    Before activating virtual environment:

    >>> import pip
    >>> print(pip.__file__)
    C:\Users\...\Anaconda3\lib\site-packages\pip\__init__.py
    

    After activating the virtual environment:

    >>> import pip
    >>> print(pip.__file__)
    C:\Users\...\Documents\Research\...\env\lib\site-packages\pip\__init__.py                                                                                                                             
    

    Note that I didn't adjust PATH, and pip is being run from the virtual environment.

    Also note that __file__ is not necessarily defined for every module. For a more complete view of options when __file__ doesn't work for a quick check, see this answer.