Last active
April 1, 2020 15:31
-
-
Save Tadaboody/cdd00414e1f79960bf5efafda1a329a3 to your computer and use it in GitHub Desktop.
Input in a right to left language while correctly displaying the input
This file contains 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
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 | |
This file contains 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 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