Files
TerminalPolyjuice/zsh/alias/python_alias.sh
2026-01-25 11:55:19 +08:00

95 lines
3.3 KiB
Bash

alias py='python3'
function pyclean() {
find "${@:-.}" -type f -name "*.py[co]" -delete
find "${@:-.}" -type d -name "__pycache__" -delete
find "${@:-.}" -depth -type d -name ".mypy_cache" -exec rm -r "{}" +
find "${@:-.}" -depth -type d -name ".pytest_cache" -exec rm -r "{}" +
}
# Grep among .py files
alias pygrep='grep -nr --include="*.py"'
# Share local directory as a HTTP server
alias pyserver="python3 -m http.server"
# Functions to python virtual environment -----------
export ZSH_POLYJUICE_DEFAULT_PYTHON_VENV=$HOME/.default_pyvenv/.venv
# create or sync the default python virtual environment
function py_create_default_venv() {
if (( ! $+commands[uv] )); then
echo "❌ uv command not found. Please install uv first."
return 1
fi
if [[ -d "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV" && -f "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV/bin/activate" ]]; then
cd $(dirname "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV")
uv sync
cd -
else
cd $(dirname "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV") || {
mkdir -p "$(dirname "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV")"
cd "$(dirname "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV")"
}
uv init --name gvenv
uv sync
cd -
fi
}
# activate a python virtual environment
function py_vrun() {
local current_dir="$PWD"
local venv_names=(".venv" "venv" ".virtualenv" "env")
local venv_path=""
local found_name=""
local max_depth=20
local depth=0
echo "🔍 searching nearest python virtual environment..."
while [[ "$current_dir" != "/" && "$current_dir" != "$HOME" && "$depth" -lt "$max_depth" ]]; do
for venv_name in "${venv_names[@]}"; do
if [[ -d "$current_dir/$venv_name" && -f "$current_dir/$venv_name/bin/activate" ]]; then
venv_path="$current_dir/$venv_name"
found_name="$venv_name"
break 2 # break 2 levels of loops
fi
done
current_dir=$(dirname "$current_dir")
((depth++))
done
# if not found in parent dirs, check $ZSH_POLYJUICE_DEFAULT_PYTHON_VENV
if [[ -z "$venv_path" && -d "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV" && -f "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV/bin/activate" ]]; then
venv_path="$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV"
found_name=$(basename "$ZSH_POLYJUICE_DEFAULT_PYTHON_VENV")
fi
# activate the found virtual environment
if [[ -n "$venv_path" ]]; then
# 如果已经激活了虚拟环境,询问是否切换
if [[ -n "$VIRTUAL_ENV" ]]; then
if [[ "$VIRTUAL_ENV" == "$venv_path" ]]; then
echo "✅ already activated: $venv_path"
return 0
fi
echo "⚠️ another virtual environment is already activated: $(basename "$VIRTUAL_ENV")"
read -p "Switch to $(basename "$(dirname "$venv_path")")/$found_name? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
return 0
fi
deactivate 2>/dev/null || true
fi
echo " ⚡ activating virtual environment: $venv_path/bin/activate"
source "$venv_path/bin/activate"
return 0
else
echo "❌ no python virtual environment found."
return 1
fi
}