How to create a Virtual Environment in Python?

A virtual environment isolates your Python dependencies, ensuring that your project’s requirements do not conflict with system-wide packages or other projects. This is particularly useful when working on multiple projects with different dependencies.

Step 1: Access the Server via SSH

  1. Open a terminal on your local machine.
  2. Connect to the server using:

ssh username@server_address

Step 2: Install Python and Virtual Environment Tools

Ensure Python is installed on the server:

python3 --version   
If Python isn’t installed, use:

sudo apt update
sudo apt install python3 python3-pip python3-venv

Step 3: Create and Activate a Virtual Environment

  1. Navigate to your project directory
  2. 
    cd /path/to/your/project
        
  3. Create a virtual environment
  4. 
    python3 -m venv venv_name
    

    Replace venv_name with your preferred name for the virtual environment.

  5. Activate the virtual environment
  6. 
    source venv_name/bin/activate  
    

    You’ll see the virtual environment’s name in your terminal prompt, indicating it’s active.

Step 4: Install Libraries for Data Analysis and Machine Learning

Once the virtual environment is activated, use pip to install libraries like pandas, NumPy, and scikit-learn:

pip install pandas numpy scikit-learn   
You can also save your dependencies to a requirements.txt file:

pip freeze > requirements.txt    
To reinstall dependencies later, use:

pip install -r requirements.txt  

Step 5: Verify the Installation

Confirm that the libraries are installed:

python -c "import pandas, numpy, sklearn; print('Libraries imported successfully')"

Step 6: Deactivate the Virtual Environment

When you’re done, deactivate the virtual environment:

  deactivate  

Step 7: Automating Activation

If you frequently work in the same environment, add the activation command to your .bashrc or .zshrc:

echo "source /path/to/your/project/venv_name/bin/activate" >> ~/.bashrc
source ~/.bashrc   
If you frequently work in the same environment, add the activation command to your .bashrc or .zshrc:

echo "source /path/to/your/project/venv_name/bin/activate" >> ~/.bashrc
source ~/.bashrc