pythonvirtualenvvirtual-environmenthydrogen

Tell Atom+Hydrogen to look in virtual enviromnment for packages


I'm completely new to this. I have set up Python3 and Atom and installed Hydrogen for Atom so I can run each line of my code and see the output.

I have set up a virtual environment and added packages to it.

My problem is that inside my Atom .py file, when I say import numpy as np for example, it tells me that the module is not found. So I think it is looking in some default place and not inside my virtual environment. Which makes sense as I don't know how to tell it to look inside the virtual environment.

I know that inside terminal I can load the virtual environment and then call the .py file from there and it will look in the right place. However that is not what I want to do. I want to be able to tell it to look in the virtual environment in the top line of the code and execute using Hydrogen, and then load the packages I want using Hydrogen, and then carry on with each line of code after that using Hydrogen.

Can someone tell me how to tell python to look in a specific virtual environment for the duration of the .py file that is being developed/executed?


Solution

  • For our purpose here virtual environments are just changing the search path of your interpreter.

    Therefore if we want to search in a given virtual environment we can just add the path of this environment to our search path, which you can do in python by using

    import sys
    sys.path.append('/path/to/virtualenv')
    

    The path to your virtual environment depends on how you configured it, but usually they are stored in a subfolder of your home directory called .virtualenvs, so this would probably look like

    import sys
    sys.path.append('/home/username/.virtualenvs/EnvName/')
    
    # rest of code
    

    Also note that this does not change your system path or pythonpath environment variables, and therefore only lasts for the duration of this python interpreter instance.