Using Virtual Environment & Requirements.txt with python

Virtual Environment Summary

Virtual Environment makes it easy to make an easily reproducably deployable environment. It keeps the environment separate from the rest of the system, thus also making uninstalling requirements much easier.

Steps

  • General Install
  • Setup
  • Activate
  • (Deactivate)

Install & Setup

If you're using python 3.4+, you can use the built-in "venv" as shown below:
python3 -m venv [my-venv-directory]

Otherwise, install the "virtualenv" package

  • install: pip install virtualenv

  • make env directory: virtualenv [my-venv-directory]

Linux Specific Commands

  1. Activate: source [my-venv-directory]/bin/activate

  2. Deactivate: deactivate

Windows Specific Commands

  1. Activate: [my-venv-directory]\Scripts\activate.bat

  2. Deactivate: [my-venv-directory]\Scripts\deactivate.bat

Deleting an environment

First deactivate the environment, then just delete the directory

Using python scripting

the following code should make a python script use the virutal environment

env_dir = os.path.abspath(env_dir)
context = self.ensure_directories(env_dir)
self.create_configuration(context)
self.setup_python(context)
self.setup_scripts(context)
self.post_setup(context)

Requirements.txt

Make a requirements file

pip freeze > requirements.txt

Using requirements.txt

pip install -r requirements.txt

References

https://python.land/virtual-environments/virtualenv
https://docs.python.org/3/library/venv.html#venv-def
https://pip.pypa.io/en/stable/user_guide/#requirements-files


You'll only receive email when they publish something new.

More from Gunderson Tech blog
All posts