Created
December 4, 2021 19:12
-
-
Save PyroAVR/0f7a579b344b407f00df2fab3465b604 to your computer and use it in GitHub Desktop.
Interactive fuzzy select feat. FZF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
from subprocess import Popen, PIPE | |
import sys | |
def select_i(choices: List[str], multi:bool=False) -> (List[int], List[str]): | |
""" | |
Interactively select from a list of choices, returning the selections | |
and their indices in the original list of choices. | |
""" | |
stdin_data = '\n'.join(choices).encode('utf-8') | |
if multi: | |
cmd = ["fzf", "-m"] | |
else: | |
cmd = ["fzf"] | |
fzf = Popen(cmd, stdin=PIPE, stdout=PIPE) | |
stdout, _ = fzf.communicate(input=stdin_data) | |
# wait up to 10 seconds for fzf to close - avoids stdout corruption | |
fzf.wait(timeout=10) | |
selections = stdout.decode('utf-8').split('\n')[:-1] | |
indices = list(map(lambda sel:choices.index(sel), selections)) | |
return selections, indices | |
selections, indices = select_i(["a", "b", "c", "d"], True) | |
print(selections) | |
print(indices) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment