Files
TerminalPolyjuice/bash/aliases/python_alias.sh
2026-04-03 16:15:31 +08:00

102 lines
2.7 KiB
Bash

#!/usr/bin/env bash
py() {
if command -v py >/dev/null 2>&1; then
command py "$@"
elif command -v python3 >/dev/null 2>&1; then
command python3 "$@"
else
echo "Error: Python is not installed or could not be found."
return 1
fi
}
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 "{}" +
}
alias pygrep='grep -nr --include="*.py"'
alias pyserver='python3 -m http.server'
py_create_default_venv() {
local venv_parent
venv_parent="$(dirname "$BASH_POLYJUICE_DEFAULT_PYTHON_VENV")"
if ! command -v uv >/dev/null 2>&1; then
echo "uv command not found. Please install uv first."
return 1
fi
mkdir -p "$venv_parent"
if [[ -d "$BASH_POLYJUICE_DEFAULT_PYTHON_VENV" && -f "$BASH_POLYJUICE_DEFAULT_PYTHON_VENV/bin/activate" ]]; then
(
cd "$venv_parent" || exit 1
uv sync
)
else
(
cd "$venv_parent" || exit 1
uv init --name gvenv
uv sync
)
fi
}
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
local venv_name
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
fi
done
current_dir="$(dirname "$current_dir")"
((depth++))
done
if [[ -z "$venv_path" && -d "$BASH_POLYJUICE_DEFAULT_PYTHON_VENV" && -f "$BASH_POLYJUICE_DEFAULT_PYTHON_VENV/bin/activate" ]]; then
venv_path="$BASH_POLYJUICE_DEFAULT_PYTHON_VENV"
found_name="$(basename "$BASH_POLYJUICE_DEFAULT_PYTHON_VENV")"
fi
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 -r -p "Switch to $(basename "$(dirname "$venv_path")")/$found_name? (y/N): " -n 1 reply
echo
if [[ ! "$reply" =~ ^[Yy]$ ]]; then
return 0
fi
deactivate >/dev/null 2>&1 || true
fi
echo "activating virtual environment: $venv_path/bin/activate"
# shellcheck disable=SC1090
source "$venv_path/bin/activate"
return 0
fi
echo "no python virtual environment found."
return 1
}