💻/프로그래밍

파이썬 venv를 conda 처럼 사용

ruhz 2024. 7. 1. 21:37

TL;DR

Ubuntu 기준 venv를 conda와 비슷하게 쓰는 스크립트를 작성.
$HOME/~.venvs에 환경을 모아서 관리.

venv_create <환경 이름> <파이썬 버전>
venv_activate <환경 이름>
venv_deactivate < 환경 이름>

 

배경

개인은 상관없지만, conda가 유료화되었다. 

 

Pricing | Anaconda

Anaconda is the birthplace of Python data science. We are a movement of data scientists, data-driven enterprises, and open source communities.

www.anaconda.com

이 참에 venv를 써보기로 하였으나, 왠지 불편해 conda처럼 사용하도록 스크립트를 생성(GPT)했다.

 

스크립트

$HOME/.venvs/venv_functions.sh 작성

# venv_functions.sh

# Set the VENV_HOME directory
export VENV_HOME="$HOME/venvs"

# Function to create a new virtual environment
venv_create() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        echo "Usage: venv_create <env_name> <python_version>"
        return 1
    fi

    env_name=$1
    python_version=$2

    # Ensure VENV_HOME directory exists
    mkdir -p $VENV_HOME

    # Create the virtual environment
    python$python_version -m venv $VENV_HOME/$env_name

    if [ $? -eq 0 ]; then
        echo "Virtual environment '$env_name' created with Python $python_version in $VENV_HOME."
    else
        echo "Failed to create virtual environment."
    fi
}

# Function to activate a virtual environment
venv_activate() {
    if [ -z "$1" ]; then
        echo "Usage: venv_activate <env_name>"
        return 1
    fi

    env_name=$1

    if [ -d "$VENV_HOME/$env_name" ]; then
        source $VENV_HOME/$env_name/bin/activate
        echo "Virtual environment '$env_name' activated."
    else
        echo "Virtual environment '$env_name' does not exist in $VENV_HOME."
    fi
}

# Function to deactivate the current virtual environment
venv_deactivate() {
    if [[ "$VIRTUAL_ENV" != "" ]]; then
        deactivate
        echo "Virtual environment deactivated."
    else
        echo "No virtual environment is currently activated."
    fi
}

$HOME/.bashrc 에 추가

# .bashrc

# Source the venv_functions.sh file to import the virtual environment functions
if [ -f "$HOME/venv_functions.sh" ]; then
    source "$HOME/venv_functions.sh"
fi

# Other .bashrc content...

적용 후 테스트

source ~/.bashrc

echo $VENV_HOME
venv_create playground 3.10
venv_activate playground
venv_deactivate