Using Virtual Environment & Requirements.txt with python
June 22, 2021•169 words
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
Activate:
source [my-venv-directory]/bin/activate
Deactivate:
deactivate
Windows Specific Commands
Activate:
[my-venv-directory]\Scripts\activate.bat
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