python.plugin.zsh 2.5 KB

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