5 alias pyfind='find . -name "*.py"'
7 # Remove python compiled byte-code and mypy/pytest cache in either the current
8 # directory or in a list of specified directories (including sub directories).
10 find "${@:-.}" -type f -name "*.py[co]" -delete
11 find "${@:-.}" -type d -name "__pycache__" -delete
12 find "${@:-.}" -depth -type d -name ".mypy_cache" -exec rm -r "{}" +
13 find "${@:-.}" -depth -type d -name ".pytest_cache" -exec rm -r "{}" +
16 # Add the user installed site-packages paths to PYTHONPATH, only if the
17 # directory exists. Also preserve the current PYTHONPATH value.
18 # Feel free to autorun this when .zshrc loads.
19 function pyuserpaths() {
20 setopt localoptions extendedglob
22 # Check for a non-standard install directory.
23 local user_base="${PYTHONUSERBASE:-"${HOME}/.local"}"
25 local python version site_pkgs
26 for python in python2 python3; do
27 # Check if command exists
28 (( ${+commands[$python]} )) || continue
30 # Get minor release version.
31 # The patch version is variable length, truncate it.
32 version=${(M)${"$($python -V 2>&1)":7}#[^.]##.[^.]##}
34 # Add version specific path, if:
35 # - it exists in the filesystem
36 # - it isn't in $PYTHONPATH already.
37 site_pkgs="${user_base}/lib/python${version}/site-packages"
38 [[ -d "$site_pkgs" && ! "$PYTHONPATH" =~ (^|:)"$site_pkgs"(:|$) ]] || continue
39 export PYTHONPATH="${site_pkgs}${PYTHONPATH+":${PYTHONPATH}"}"
43 # Grep among .py files
44 alias pygrep='grep -nr --include="*.py"'
46 # Run proper IPython regarding current virtualenv (if any)
47 alias ipython="python3 -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'"
49 # Share local directory as a HTTP server
50 alias pyserver="python3 -m http.server"
55 # Activate a the python virtual environment specified.
56 # If none specified, use 'venv'.
58 local name="${1:-venv}"
59 local venvpath="${name:P}"
61 if [[ ! -d "$venvpath" ]]; then
62 echo >&2 "Error: no such venv in current directory: $name"
66 if [[ ! -f "${venvpath}/bin/activate" ]]; then
67 echo >&2 "Error: '${name}' is not a proper virtual environment"
71 . "${venvpath}/bin/activate" || return $?
72 echo "Activated virtual environment ${name}"
75 # Create a new virtual environment, with default name 'venv'.
77 local name="${1:-venv}"
78 local venvpath="${name:P}"
80 python3 -m venv "${name}" || return
81 echo >&2 "Created venv in '${venvpath}'"