When starting a Python 3 project in Linux, it’s essential to follow best practices to ensure a clean and isolated development environment. One of the recommended approaches is to utilize virtual environments. Virtual environments allow you to create an isolated environment for each project, preventing conflicts between different packages and dependencies. In this guide, we’ll walk you through the steps to set up and activate a virtual environment for your Python 3 project.
Step 1: Install python3-venv
First, make sure you have the python3-venv
package installed on your Linux system. This package provides the necessary tools to create and manage virtual environments. Open a terminal and run the following command:
Note: venv (for Python 3) and virtualenv (for Python 2)
sudo apt-get install python3-venv
Step 2: Create a New Virtual Environment
Navigate to the directory where you want to create your project and virtual environment. Once there, run the following command to create a new virtual environment named myenv
:
python3 -m venv myenv
Step 3: Activate the Virtual Environment
To start working within the virtual environment, you need to activate it. Use the following command to activate the myenv
environment:
source myenv/bin/activate
Once activated, you’ll notice that your command prompt changes to reflect the name of the active environment (myenv
in this case). From now on, any Python packages you install or scripts you run will be isolated within this environment.
Step 4: Install Project Dependencies
With the virtual environment active, you can now install the necessary Python packages for your project. It’s recommended to use a requirements file to manage your dependencies. Create a file called requirements.txt
in your project directory and add the required packages with their versions, each on a separate line. For example:
numpy==1.20.3
pandas==1.3.0
To install these dependencies, run the following command:
pip install -r requirements.txt
Now that your virtual environment is set up and dependencies are installed, you’re ready to start developing your Python 3 project!
How to deactivate the Virtual Environment
Once you’re done working on your project, it’s good practice to deactivate the virtual environment. To do this, simply run the following command:
deactivate
Further info go to official page here