Using a virtual environment like
venvis a best practice when working with Python-based projects like
Continuing from the blog,
Virtual environments are isolated Python environments that allow you to manage dependencies separately for each project, providing a controlled and reproducible environment for development, testing, and production.
Here are some examples of how to use venv for Ansible, Molecule, and Playbook development:
Creating a virtual environment
You can create a virtual environment using the
venv module that comes with Python. To create a new virtual environment, open your terminal and run the following command:
python3 -m venv myenv
This will create a new virtual environment named
myenv in the current directory.
Activating a virtual environment
Once you have created a virtual environment, you need to activate it before you can use it. To activate the
myenv environment, run the following command:
This will activate the virtual environment and you will see the name of your environment in the terminal prompt.
To install dependencies in the virtual environment, you can use pip. For example, to install the
ansible package, run the following command:
pip install ansible
This will install the
ansible package in the
myenv virtual environment.
To freeze the list of installed packages in your virtual environment, you can use the
pip freeze command. This will generate a list of installed packages and their versions that can be used to recreate the same environment on another machine.
To generate a
requirements.txt file containing the list of installed packages, run the following command:
pip freeze > requirements.txt
This will create a
requirements.txt file in the current directory containing the list of installed packages.
To install the packages listed in a
requirements.txt file, run the following command:
pip install -r requirements.txt
This will install all the packages listed in the
requirements.txt file in the current virtual environment.
By isolating your project’s dependencies, you can ensure that your code works consistently and avoid compatibility issues with different versions of packages. It also makes it easy to manage dependencies and maintain a consistent development environment. Freezing packages and using a
requirements.txt file are useful techniques for recreating the same environment on different machines or sharing the environment with other developers.