Skip to content

Instantly share code, notes, and snippets.

@Tadaboody
Last active April 1, 2020 15:31
Show Gist options
  • Save Tadaboody/cdd00414e1f79960bf5efafda1a329a3 to your computer and use it in GitHub Desktop.
Save Tadaboody/cdd00414e1f79960bf5efafda1a329a3 to your computer and use it in GitHub Desktop.
Input in a right to left language while correctly displaying the input
try:
import msvcrt
def input_char(): # Windows
"""Read a single character from user input"""
return msvcrt.getwch()
except ImportError:
import sys, tty, termios
def input_char():
"""Read a single character from user input"""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
from input_char read input_char
CTRL_C = "\x03"
def rtl_input(prompt=""):
"""Input in a rtl language while correctly displaying the input"""
print(prompt, end="")
word = ""
while (char := input_char()) not in {"\r", "\n", "\r\n", CTRL_C}:
if char == "\b": # Handle backspace
print("\b" * len(word), end="", flush=True)
word = word[:-1]
else:
word += char
print("\b" * len(word), end="", flush=True)
print("".join(reversed(word)), end="", flush=True)
print()
if char == CTRL_C:
raise KeyboardInterrupt()
return word
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment