def win_print(line=None, end='\r\n'): if line is not None: for c in line: msvcrt.putwch(c) for c in end: msvcrt.putwch(c)
def write(ch, fg=None, bg=None): if fg is not None and bg is not None: set_color(fg, bg) if sys.platform == "win32": msvcrt.putwch(ch) else: sys.stdout.write(ch)
def readch(echo=True): "Get a single character on Windows." while msvcrt.kbhit(): # clear out keyboard buffer msvcrt.getwch() ch = msvcrt.getwch() if ch in u'\x00\xe0': # arrow or function key prefix? ch = msvcrt.getwch() # second call returns the actual key code if echo: msvcrt.putwch(ch) return ch
def draw_chat(): print('\n'*25) for log in chat_logs: print(log) tmp = '=============網路聊天程式 (伺服器 {})====ESC 離開==========' print(tmp.format(target_host)) for c in input_chars: putwch(c)
def hidepass(prompt="", replaceChar="*"): password = "" count = 0 backspace = chr(127) for i in prompt: if os.name == "posix": putchar(i) elif os.name == "nt" or os.name == "dos": msvcrt.putwch(i) while True: if os.name == "posix": captureKey = getchar() elif os.name == "nt" or os.name == "dos": captureKey = msvcrt.getwch() if captureKey == "\n" or captureKey == "\r": break if captureKey == "\b" or captureKey == backspace: password = password[:-1] count -= 1 if count >= 0: if os.name == "posix": putchar("\b") putchar(" ") putchar("\b") elif os.name == "nt" or os.name == "dos": msvcrt.putwch("\b") msvcrt.putwch(" ") msvcrt.putwch("\b") else: if count <= 0: count = 0 password += captureKey count += 1 if os.name == "posix": putchar(replaceChar) elif os.name == "nt" or os.name == "dos": msvcrt.putwch(replaceChar) print("\n") return password if password != "" else None
def data_during_message_typing(curr_message, str_data): msvcrt.putwch("\r") # The length difference between the current message and the data. If the message is longer than the data, # spaces are needed to be printed in order to completely "erase" the message in that line. num_spaces_left = 0 if len(curr_message) > len(str_data): num_spaces_left = len(curr_message) - len(str_data) print(str_data + num_spaces_left * " ") # prints the current message for char in curr_message: msvcrt.putwch(char)
def win_getpass(prompt='Password: '******'' for c in prompt: msvcrt.putwch(c) shown_prompt += c pw = "" while 1: c = msvcrt.getwch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] # rewrite the stdout shown_pwd = '*' * len(pw) shown_pwd += ' ' sys.stdout.write('\r' + shown_prompt + shown_pwd + '\b') sys.stdout.flush() else: msvcrt.putwch('*') pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw
def input_with_timeout(prompt='', timeout=DEFAULT_TIMEOUT): begin = time.monotonic() end = begin + timeout for c in prompt: msvcrt.putwch(c) line = '' is_timeout = True while time.monotonic() < end: if msvcrt.kbhit(): c = msvcrt.getwch() msvcrt.putwch(c) if c == '\r' or c == '\n': is_timeout = False break if c == '\003': return 'q' if c == '\b': line = line[:-1] else: line = line + c time.sleep(0.05) if is_timeout: return '' msvcrt.putwch('\r') msvcrt.putwch('\n') return line
def handle_incoming_data(curr_message): data = my_socket.recv(len(str(MAX_BYTES))).decode() if data == "": # When the socket is being closed, an "empty message" is sent. msvcrt.putwch("\r") print(" " * len(curr_message)) return False message_from_data_length = int(data) message_from_data = my_socket.recv(message_from_data_length).decode() if len(curr_message) != 0: data_during_message_typing(curr_message, message_from_data) return True else: msvcrt.putwch("\r") print(message_from_data) return True
def __ichr(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() while True: char = msvcrt.getwch() if char in '\x00\xE0': msvcrt.getwch() elif char in string.printable: char = char.replace('\r', '\n') msvcrt.putwch(char) break item = ord(char) # Storing Number self.__heap.set_(addr, item)
def tick(self): self.clear() input_area = self.showed_awnser + '_' * ( 12 - wcswidth(self.showed_awnser)) + self.last_status for c in input_area: msvcrt.putwch(c) self.showed += input_area prompt = ' ({})'.format(' '.join(cmd.prompt for cmd in self.commands)) for c in prompt: msvcrt.putwch(c) self.showed += prompt c = msvcrt.getwch() if c == '\r': c = '[enter]' if c == '\003': raise KeyboardInterrupt if c == '\b': self.buf = self.buf[:-1] else: self.buf = self.buf + c status = None for cmd in self.commands: result = cmd(self.buf) if isinstance(result, Ratain) and not isinstance(status, Anwser): status = result elif isinstance(result, Anwser): status = result break if isinstance(status, Ratain): self.showed_awnser = self.buf self.last_status = ' ' elif isinstance(status, Anwser): self.showed_awnser = self.buf self.buf = '' self.last_status = '*' return status.value else: self.showed_awnser = '' self.buf = '' self.last_status = '!'
def ime_wprint( u_code , bs=0 ): """화면출력함수 글자(1개)를 화면에 출력한다. 두번째 인자는 백스페이스의 횟수를 지정한다 딜폴트 값은 0으로 이는 이전에 출력되었던 글자를 지우지 않겠다는 뜻이다. gotoxy(x,y)를 사용할 수 없는 환경이기때문에 백스페이스를 이용하여 이전 글자를 지운다. 이전 글자를 지우는 주요한 이유는 한글자를 조립하는 동안에 현재커서의 진행을 막기 위함이다. @파라미터: u_code: 타입은 유니코드,출력하고자 하는 글자(1개) @파라미터: bs: 타입은 정수,백스페이스 횟수 한 글자를 지우기 위해선 2회의 백스페이스를 지정해야 한다. """ for i in range(bs): msvcrt.putwch( u"\b" ) if u_code: msvcrt.putwch(u_code)
def get_password(): """Prompt for password with echo off, using Windows getch(). This shouldn't be called directly- use ``ui.getpass()`` instead, which checks if the session is interactive first. """ pw = u"" while True: c = msvcrt.getwch() # pytype: disable=module-attr if c == u'\r' or c == u'\n': break if c == u'\003': raise KeyboardInterrupt if c == u'\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch(u'\r') # pytype: disable=module-attr msvcrt.putwch(u'\n') # pytype: disable=module-attr return encoding.unitolocal(pw)
def custom_input() -> str: result = '' if os.name == 'nt': import msvcrt while True: entered = msvcrt.getwch() if entered == '\r': break msvcrt.putwch(entered) result += entered else: import curses console = curses.initscr() while True: entered = console.get_wch() if entered == '\n': break result += entered print('\r', flush=False, end='') # print('>', result) return result
def getpass(prompt): if iswindows: # getpass is broken on windows with python 2.x and unicode, the # below implementation is from the python 3 source code import msvcrt for c in prompt: msvcrt.putwch(c) pw = "" while 1: c = msvcrt.getwch() if c == '\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw else: enc = getattr(sys.stdin, 'encoding', preferred_encoding) or preferred_encoding from getpass import getpass return getpass(prompt).decode(enc)
def input_time_out(time_out=10): import time import msvcrt import string begin = time.clock() end = begin + time_out input_string = '' while end >= time.clock(): if Utils.kbhit(): char = msvcrt.getwch() if char in '\x00\xE0': msvcrt.getwch() elif char in string.printable: char = char.replace('\r', '\n') if char != '\n': input_string += char else: input_string += ' ' msvcrt.putwch(char) elif char == '\x08': input_string = input_string[:-1] return input_string
def main(): while(True): #I'm hacking this together to practice my typing. CTRL+C to exit ha #create a sentence to type sentenceArr = [] for i in range(0,random.randint(6,10)): sentenceArr.append(linecache.getline("words.txt", random.randint(0,MAXLINE)).rstrip()) sentenceArr.append(" ") #find number of words numOfWords = len(sentenceArr) #turn array into one string sentence = ''.join(sentenceArr) sentence = sentence.rstrip() # Remove the space at the end print("\n\n") print(sentence) #ask user to type done = False currChar = 0 correct = 0 incorrect = 0 start_time = datetime.datetime.now() while(currChar < len(sentence)): #wait for user input userIn = str(msvcrt.getwch()) #grabs on character and echoes it if ( userIn == '\000' or userIn == '\xe0' ) : continue elif ( userIn == '\x03' ): return elif ( userIn == sentence[currChar] ): #correct msvcrt.putwch(userIn) correct += 1 currChar += 1 else: incorrect += 1 end_time = datetime.datetime.now() print(f"\nCorrect Rate {math.floor(100*correct/(incorrect+correct))}") deltaT = ((end_time-start_time).total_seconds())/60 #in minutes print(f"WPM: {numOfWords/deltaT}")
def LueSanaAjastettu(self, timeout): timer = time.monotonic endtime = timer() + timeout result = [] while timer() < endtime: if msvcrt.kbhit(): nappi = msvcrt.getwch() if nappi == '\b' and len(result) > 0: result = result[:-1] msvcrt.putwch(nappi) else: msvcrt.putwch(nappi) if nappi == '\r': if len(result) > 0: lue = ''.join(result) print() return lue else: result.append(nappi) time.sleep(0.04) return ""
def when_key_pressed(message): char = msvcrt.getwch() # The key pressed on the keyboard if char == "\b": msvcrt.putwch(char) message = message[:-1] msvcrt.putwch(" ") msvcrt.putwch("\b") return message # When the user finished typing the message and pressed enter. # The curser is at the beginning of the line with the typed message if char == "\r": list_to_send.append(message) return "" msvcrt.putwch(char) message += char return message
def main(): user_name = receive_valid_name() my_socket.connect( ('127.0.0.1', 1111)) # Connects to the server (127.0.0.1 is on this machine) print_opening_message() message = "" # the message is of type bytes-string in_chat = True # Messages will be sent only if the last piece of data has been recieved by the server, and a message was sent back, # If not, messages that are sent together, might arrive together, and the message received will be different. can_send_data = True while in_chat: rlist, wlist, xlist = select.select([my_socket], [my_socket], []) # In case the socket is readable if my_socket in rlist: in_chat = handle_incoming_data(message) can_send_data = True # If the user types something if msvcrt.kbhit(): message = when_key_pressed(message) # In case the socket is writeable if my_socket in wlist and len(list_to_send) != 0 and can_send_data: data_to_send = prepare_message_to_send(user_name, list_to_send[0]) if data_to_send is not None: my_socket.send(data_to_send.encode()) can_send_data = False if list_to_send[0] == "quit": msvcrt.putwch("\r") print( time.strftime("%H:%M", time.localtime()) + " You left the chat") in_chat = False list_to_send.remove(list_to_send[0]) my_socket.close()
def clear(self): counts = range(wcswidth(self.showed)) for i in counts: msvcrt.putwch('\b') for i in counts: msvcrt.putwch(' ') for i in counts: msvcrt.putwch('\b') self.showed = ''
def LueNumeroAjastettu(self, timeout, pituus): timer = time.monotonic endtime = timer() + timeout result = [] while timer() < endtime: if msvcrt.kbhit(): nappi = msvcrt.getwch() if nappi == '\b' and len(result) > 0: result = result[:-1] msvcrt.putwch(nappi) elif self.OnkoNumero(nappi) or nappi == '\r' or (len(result) == 0 and nappi == '-'): result.append(nappi) msvcrt.putwch(nappi) if len(result) == pituus: lue = ''.join(result) if self.OnkoNumero(lue) == True: numero = int(lue) print() return numero else: result = [] time.sleep(0.04) return -99999999
def WinPause(): """ Stops the program from exiting immediatly. """ for c in "\nPress any key to exit.": msvcrt.putwch(c) while True: c = msvcrt.getwch() if c: break msvcrt.putwch('\r') msvcrt.putwch('\n')
def win_getpass(prompt='Password: '******'\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch(unicode('*')) msvcrt.putwch(unicode('\r')) msvcrt.putwch(unicode('\n')) return pw
def win_getpass(prompt='Password: '******'\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch(unicode('*')) #<= This line added msvcrt.putwch(unicode('\r')) msvcrt.putwch(unicode('\n')) return pw
def pypsi_win_getpass(prompt='Password: '******'\r', '\n'): break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw
def win_getpass(prompt='Password: '******'' while True: c = msvcrt.getwch() if c == '\r' or c == '\n': break if c == '\x03': raise KeyboardInterrupt if c == '\x08': pw = pw[:-1] else: pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw
def win_getpass(prompt='Password: '******'\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw
def win_getpass(prompt="Password: "******"""Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) import msvcrt for c in prompt: msvcrt.putwch(c) pw = "" while 1: c = msvcrt.getwch() if c == "\r" or c == "\n": break if c == "\003": raise KeyboardInterrupt if c == "\b": pw = pw[:-1] else: pw = pw + c msvcrt.putwch("\r") msvcrt.putwch("\n") return pw
from msvcrt import putwch from msvcrt import getch from msvcrt import getwch from time import sleep #import msvcrt # If successful, we are on Windows while True: # Example of a prompt for one character of input promptStr = "Please give me a character:" responseStr = "Thank you for giving me a {}." print(promptStr, end="\n> ") putwch(' ') answer = getch() print("\n") print(responseStr.format(answer))
def __oint(self): for digit in str(self.__stck.pop()): msvcrt.putwch(digit)
def __iint(self): addr = self.__stck.pop() # Input Routine while msvcrt.kbhit(): msvcrt.getwch() buff = '' char = msvcrt.getwch() while char != '\r' or not buff or len(buff) == 1 and buff in '+-': if char in '\x00\xE0': msvcrt.getwch() elif char in '+-' and not buff: msvcrt.putwch(char) buff += char elif '0' <= char <= '9': msvcrt.putwch(char) buff += char elif char == '\b': if buff: buff = buff[:-1] msvcrt.putwch(char) msvcrt.putwch(' ') msvcrt.putwch(char) char = msvcrt.getwch() msvcrt.putwch(char) msvcrt.putwch('\n') item = int(buff) # Storing Number self.__heap.set_(addr, item)
def __ochr(self): msvcrt.putwch(chr(self.__stck.pop()))
def __ochr(self): for c in repr(chr(self.__stck.pop())): msvcrt.putwch(c)
def WinGetNum(prompt='> ', choices=2): """ Select number choices using prompt, up to a max of choices. This isnt working correctly with large numbers but it's fine trust me. Just fix it later :param choices: How many choices :type choices: int :param prompt: What to prompt user with :type prompt: str """ for c in prompt: msvcrt.putwch(c) num = "" while 1: c = msvcrt.getwch() if c == '\r' or c == '\n': if num: break if c == '\003': raise KeyboardInterrupt if c == '\b': if len(num) > 0: num = num[:-1] msvcrt.putwch('\x08') msvcrt.putwch(' ') msvcrt.putwch('\x08') else: if c.isdigit(): if int(c) <= choices and len(num) <= 0: msvcrt.putwch(c) num = c msvcrt.putwch('\r') msvcrt.putwch('\n') try: return int(num) except ValueError: return None
jm = engkey2kor(c) else: #영문입력으로 판단 jm = None # 한글키 작동되면 비프음 if ord(c) > 127: msvcrt.putch('\x07') continue # 엔터키 입력 받음 if c == '\r' : if state != 0 : input_list.append( asm(cho,jung,jong) ) msvcrt.putch('\r') msvcrt.putch('\n') for uc in input_list: msvcrt.putwch(uc) msvcrt.putch('\r') msvcrt.putch('\n') input_list=[] state = 0 cho=None;jung=None;jong=None continue # 백스페이스 입력받음 if c == '\b' : if state==0 : # 이전글자 삭제 # 상태0 try : last_u = input_list.pop() except IndexError as e : last_u = None
def putChar(self): putwch(chr(self.cells[self.ptr]))
def WinGetPass(prompt='Password: '******'\r' or c == '\n': break if c == '\003': break # raise KeyboardInterrupt if c == '\b': if len(pw) > 0: pw = pw[:-1] msvcrt.putwch('\x08') msvcrt.putwch(' ') msvcrt.putwch('\x08') else: msvcrt.putwch('*') pw = pw + c msvcrt.putwch('\r') msvcrt.putwch('\n') return pw
def _win_newinput(prompt, stream=None, newline=True, clearline=False): if sys.stdin is not sys.__stdin__: return _fallback_newinput(prompt, stream) import msvcrt for c in prompt: msvcrt.putwch(c) pw = "" pwcursor = 0 arrowkey = False while 1: c = msvcrt.getwch() if c == '\r' or c == '\n': if newline: msvcrt.putwch('\n') break if c == '\003': raise KeyboardInterrupt if c == '\b': if len(pw) > 0 and pwcursor > 0: msvcrt.putwch('\b') msvcrt.putwch(' ') msvcrt.putwch('\b') pwcursor -= 1 pw = pw[:pwcursor] + pw[pwcursor+1:] pw += ' ' for ch in pw[pwcursor:]: msvcrt.putwch(' ') for ch in pw[pwcursor:]: msvcrt.putwch('\b') for ch in pw[pwcursor:]: msvcrt.putwch(ch) for ch in pw[pwcursor:]: msvcrt.putwch('\b') pw = pw[:-1] elif c.encode('utf-8') == b'\xc3\xa0': arrowkey = True continue elif arrowkey: if c == 'K': #leftarrow if pwcursor > 0: pwcursor -= 1 msvcrt.putwch('\b') arrowkey = False continue elif c == 'M': #rightarrow if pwcursor < len(pw): pwcursor += 1 msvcrt.putwch(pw[pwcursor-1]) arrowkey = False continue elif c == 'G': #home while pwcursor > 0: pwcursor -= 1 msvcrt.putwch('\b') arrowkey = False continue elif c == 'O': #end while pwcursor < len(pw): pwcursor += 1 msvcrt.putwch(pw[pwcursor-1]) arrowkey = False continue else: arrowkey = False continue else: pw = pw[:pwcursor] + c + pw[pwcursor:] for ch in pw[pwcursor:]: msvcrt.putwch(ch) for ch in pw[pwcursor+1:]: msvcrt.putwch('\b') pwcursor += 1 if clearline: while pwcursor < len(pw): msvcrt.putwch(' ') pwcursor += 1 for c in pw: msvcrt.putwch('\b') msvcrt.putwch(' ') msvcrt.putwch('\b') for c in prompt: msvcrt.putwch('\b') msvcrt.putwch(' ') msvcrt.putwch('\b') return pw
def getPassword(passWord="******", stream=None): for c in passWord: msvcrt.putwch(c) passWord = "" while True: eachVal = msvcrt.getwch() # Press "ENTER" if eachVal == "\r" or eachVal == "\n": break # Press "Ctrl + C" if eachVal == "\003": raise KeyboardInterrupt # Press "BACKSPACE" if eachVal == "\b": # IF Length Longer Than Zero if len(passWord) > 0: passWord = passWord[:-1] msvcrt.putwch("\b") msvcrt.putwch(" ") msvcrt.putwch("\b") # ELSE Other Input else: passWord = passWord + eachVal msvcrt.putwch("*") msvcrt.putwch("\n") return passWord