02eb548d5ac41c57d37af6817c77dfbb57a8d281

Author
Marijan Smetko <msmetko@ZVIJER-PC.localdomain>
Committer
Marc Cornellà <hello@mcornella.com>
Date

Message

feat(python): add utilities to manage simple virtual environments (#9776)

Closes #9776

Diff

 1diff --git a/plugins/python/README.md b/plugins/python/README.md
 2index eeaa1148a3fdc5caccf3c5aaa20cc485b0b7106a..4968cca6da17bb1ccf31473d18579bcacbcea3cb 100644
 3--- a/plugins/python/README.md
 4+++ b/plugins/python/README.md
 5@@ -10,6 +10,7 @@ plugins=(... python)
 6 
 7 ## Aliases
 8 
 9+<<<<<<< HEAD
10 | Command          | Description                                                                           |
11 | ---------------- | ------------------------------------------------------------------------------------- |
12 | `py`             | Runs `python`                                                                         |
13@@ -19,3 +20,11 @@ plugins=(... python)
14 | `pygrep <text>`  | Looks for `text` in .py files                                                         |
15 | `pyuserpaths`    | Add --user site-packages to PYTHONPATH, for all installed python versions.            |
16 | `pyserver`       | Starts an http.server on the current directory. Use `--directory` for a different one |
17+
18+## Virtual environments
19+
20+The plugin provides two utilities to manage Python venvs:
21+
22+- `mkv [name]`: make a new virtual environment called `name` (default: `venv`) in current directory.
23+
24+- `vrun [name]`: activate virtual environment called `name` (default: `venv`) in current directory.
25diff --git a/plugins/python/python.plugin.zsh b/plugins/python/python.plugin.zsh
26index 896fae3ca21d8e3774b8f27cd8fdfe62bca170c2..6c7fc6cbba63c197c8af4d5f0c4b8aa76011fc8f 100644
27--- a/plugins/python/python.plugin.zsh
28+++ b/plugins/python/python.plugin.zsh
29@@ -51,3 +51,36 @@ alias ipython="python -c 'import IPython; IPython.terminal.ipapp.launch_new_inst
30 
31 # Share local directory as a HTTP server
32 alias pyserver="python -m http.server"
33+
34+
35+## venv utilities
36+
37+# Activate a the python virtual environment specified.
38+# If none specified, use 'venv'.
39+function vrun() {
40+  local name="${1:-venv}"
41+  local venvpath="${name:P}"
42+
43+  if [[ ! -d "$venvpath" ]]; then
44+    echo >&2 "Error: no such venv in current directory: $name"
45+    return 1
46+  fi
47+
48+  if [[ ! -f "${venvpath}/bin/activate" ]]; then
49+    echo >&2 "Error: '${name}' is not a proper virtual environment"
50+    return 1
51+  fi
52+
53+  . "${venvpath}/bin/activate" || return $?
54+  echo "Activated virtual environment ${name}"
55+}
56+
57+# Create a new virtual environment, with default name 'venv'.
58+function mkv() {
59+  local name="${1:-venv}"
60+  local venvpath="${name:P}"
61+
62+  python3 -m venv "${name}" || return
63+  echo >&2 "Created venv in '${venvpath}'"
64+  vrun "${name}"
65+}