How To: Setting Up Virtual Environment
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
- Open a terminal on your local machine.
- 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
- Navigate to your project directory
- Create a virtual environment
- Activate the virtual environment
cd /path/to/your/project
python3 -m venv venv_name
Replace venv_name with your preferred name for the virtual environment.
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