Is there a way to detect when a user enters for example
Input: users input here
to detect what they have wrote, users input here. Before they press enter?
Is there a way to detect when a user enters for example
Input: users input here
to detect what they have wrote, users input here. Before they press enter?
The "prompt_toolkit" package might be what you're looking for. This package allows for auto completion while typing from inside a python script. You can configure the words that you want to autocomplete, but here is an example given on their docs (this package is very feature-rich, so be sure to check out the other many examples on their Github page):
import time
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.shortcuts import CompleteStyle, prompt
WORDS = [
"alligator",
"ant",
"ape",
"bat",
"bear",
"beaver",
"bee",
"bison",
"butterfly",
"cat",
"chicken",
"crocodile",
"dinosaur",
"dog",
"dolphin",
"dove",
"duck",
"eagle",
"elephant",
"fish",
"goat",
"gorilla",
"kangaroo",
"leopard",
"lion",
"mouse",
"rabbit",
"rat",
"snake",
"spider",
"turkey",
"turtle",
]
class SlowCompleter(Completer):
"""
This is a completer that's very slow.
"""
def __init__(self):
self.loading = 0
def get_completions(self, document, complete_event):
# Keep count of how many completion generators are running.
self.loading += 1
word_before_cursor = document.get_word_before_cursor()
try:
for word in WORDS:
if word.startswith(word_before_cursor):
time.sleep(0.2) # Simulate slowness.
yield Completion(word, -len(word_before_cursor))
finally:
# We use try/finally because this generator can be closed if the
# input text changes before all completions are generated.
self.loading -= 1
def main():
# We wrap it in a ThreadedCompleter, to make sure it runs in a different
# thread. That way, we don't block the UI while running the completions.
slow_completer = SlowCompleter()
# Add a bottom toolbar that display when completions are loading.
def bottom_toolbar():
return " Loading completions... " if slow_completer.loading > 0 else ""
# Display prompt.
text = prompt(
"Give some animals: ",
completer=slow_completer,
complete_in_thread=True,
complete_while_typing=True,
bottom_toolbar=bottom_toolbar,
complete_style=CompleteStyle.MULTI_COLUMN,
)
print("You said: %s" % text)
if __name__ == "__main__":
main()
The above code works like this:
Docs: https://python-prompt-toolkit.readthedocs.io/en/stable/
Autocompletion examples: https://github.com/prompt-toolkit/python-prompt-toolkit/tree/master/examples/prompts/auto-completion