Skip to content

Instantly share code, notes, and snippets.

@danielkelshaw
Last active September 28, 2020 15:16
Show Gist options
  • Save danielkelshaw/6d90689b56f93aecc560cdd9a2e01162 to your computer and use it in GitHub Desktop.
Save danielkelshaw/6d90689b56f93aecc560cdd9a2e01162 to your computer and use it in GitHub Desktop.

Python Virtual Environments

When developing code it is important to know which versions of libraries you are using. This is not only helpful for yourself but ensures that everyone working on a project is working with exactly the same toolset. Although it may seem like a headache at first it saves a lot of pain further down the road so it's good to get accustomed to the process.

As you may have installed Python through Anaconda or PyEnv, I will provide two sets of instructions that will allow you to make an environment for each one.

First of all make a new directory which you can work in:

$ mkdir testing_environments
$ cd testing_environments

Conda Environments

If you installed Python via. Anaconda then you will want to use a conda environment, this can be created with the following command:

$ conda create --name <environment_name>

Activate the environment:

$ conda activate <environment_name>

Now anything you install for Python will be done within this envinroment - this helps keep your system tidy and helps to ensure that everyons is using the same tools.

When installing packages it is easiest to use the python package-manager, pip.

Once you're inside the environment you created you can install pip with:

(<environment_name>)$ conda install pip

To exit the environment you can run the command:

(<environment_name>)$ conda deactivate

Python virtualenv

My preferred way of creating a virtual environment is to do it via. Python directly. This is as simple as running the command:

$ python -m venv <environment_name>

The environment can be activated with:

$ source <environment_name>/bin/activate

This environment will already come with pip installed so there is no additional step.

To exit the environment you can run the command:

(<environment_name>)$ deactivate

Installing Packages

Once you are inside your virtual environment you will now want to install any packages, this will be dependant on the project but the approach is always the same:

(<environment_name>)$ pip install <package_name>

You can give this a try with NumPy:

(<environment_name>)$ pip install numpy

Conclusion

At this point you should have Python set-up properly. This will make it a lot easier to diagnose any problems which arise which would definitely take longer to solve than just setting up Python as described here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment