Python - Virtual environment creation on MacOS

Python - Virtual environment creation on MacOS

Aito Nakajima ยท March 6, 2025

Mac

Contents

Tools that will be used and needed to be installed on your Mac

  • tox is used for automating the virtual env creation, running commands, linting, etc.
  • poetry is used for Python package management and is used in conjunction with tox.
  • pyenv is used for Python Version Management, to easily switch between different versions of Python, commands that can be used with pyenv.

Files that are needed at the top level of your repository

  • tox.ini is the main file that you edit to make changes.
  • pyproject.toml should be edited using the poetry command but can be edited by hand if needed.
  • poetry.lock should be edited using the poetry command and shouldn't be edited by hand.

Poetry Notes

To first create the pyproject.toml file run

poetry init

If Poetry isn't installing the packages in the current directory

poetry env remove python
poetry config virtualenvs.in-project true

Running tox

To run tox, cd to the folder that has the tox.ini file and run

tox

If you want to activate the virtual environment manually.

source .tox/py31*/bin/activate

Manual process for creating a Virtual Environment

  1. Create a new Virtual Environment (cd to the location that you would like to create your Virtual Enviroment)
python3 -m venv venv
  1. To activate the virtual environment
source venv/bin/activate
  1. Installing required Applications to your virtual environment (cd to the ansible/python project)
pip install -r requirements.txt --upgrade
  1. Check for outdated pip packages
pip list --
  1. Update outdated pip packages
pip install -U package_name
  1. Update the requirements.txt file, make sure you don't have any compatibility issues or dependency conflicts.
pip freeze > requirements.txt
  1. To deactivate the virtual environment
deactivate