venv module allows you to create isolated environments for your Python projects. This ensures that each project can have its own dependencies, regardless of what dependencies every other project has. Here’s a quick cheat sheet of the essential commands you’ll need:
1. Creating a Virtual Environment
python -m venv myenv
- Purpose: This command creates a new virtual environment named
myenv. You can replace
myenvwith any name you prefer for your environment.
2. Activating the Virtual Environment
- On Windows:
- On macOS and Linux:
- Purpose: Activating the virtual environment will change your shell’s prompt to show the name of the activated environment and ensure that any Python commands you use will affect only the current environment.
3. Deactivating the Virtual Environment
- Purpose: This command deactivates the currently active virtual environment, returning you to the global Python environment.
4. Installing Packages
With the virtual environment activated, you can use
pip to install packages:
pip install package-name
- Purpose: This installs the specified package within the virtual environment. Replace
package-namewith the name of the package you want to install.
5. Listing Installed Packages
- Purpose: This command lists all the packages installed in the current virtual environment.
6. Generating a Requirements File
pip freeze > requirements.txt
- Purpose: This command creates a
requirements.txtfile, which contains a list of all the packages and their specific versions installed in the current environment. This is useful for replicating the environment on another machine.
7. Installing Packages from a Requirements File
pip install -r requirements.txt
- Purpose: This command installs all the packages listed in the
requirements.txtfile, ensuring you have the exact versions specified.
8. Deleting a Virtual Environment
Simply delete the environment’s directory to remove it:
rm -rf myenv
- Purpose: This command deletes the
myenvvirtual environment. Replace
myenvwith the name of the environment you wish to delete.
venv allows for better management of project dependencies, ensuring that there are no conflicts between packages. With this cheat sheet, you’ll have a handy reference for the most essential
venv commands. Happy coding!