def inputLoop(): global userInput global sendThis global continueRunning while continueRunning: try: newChar = msvcrt.getche() # get and echo whatever key the user pressed. #TODO: Disallow backspace, delete, etc. if newChar==chr(8): #backspace if len(userInput)>0: #if there is something to erase.... userInput = userInput[:-1] sys.stdout.write(chr(0)) sys.stdout.write(chr(8)) elif newChar=='\r': # is enter sys.stdout.write(chr(13)) # Bring to front for pos in range(len(userInput)): sys.stdout.write(chr(0)) #Erase all chars written sys.stdout.write(chr(13)) # bring to front sys.stdout.write('\r') # enterrrr sendThis = userInput userInput = '' elif (ord(newChar)>=32 and ord(newChar)<=126): #alpha numerics userInput = userInput + newChar else:# Erase the echo. sys.stdout.write(chr(8)) sys.stdout.write(chr(0)) sys.stdout.write(chr(8)) newChar = '' except: 'Input error.'
def main(): time_start=time.time() ser = serial.Serial(1) # open first serial port ser.baudrate =115200 print (ser.name) # check which port was really used try: sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % ( ser.portstr, ser.baudrate, ser.bytesize, ser.parity, ser.stopbits, )) except serial.SerialException as e: sys.stderr.write("could not open port %r: %s\n" % (port, e)) sys.exit(1) cmd_en = 0 Packet_class = Packet() packet = list(range(0,200)) log = open('log.log','w') ptr_packet = 0 time_packet = time.time() count = 0 while 1: hello = ser.readline(ser.inWaiting()) if (((time.time()-time_packet)>1.0)and cmd_en): cmd_en=0 j=0 while(j<len(hello)): if (hello[j] == '~'): if (cmd_en == 0): time_packet = time.time() cmd_en = 1 count = 0 packet[count] = hello[j] count = 1 else: time_packet = time.time() packet[count] = hello[j] cmd_en = 0 count += 1 ptr_packet+=1 log = open('log.log','a') packet_temp = char_to_int(packet,count) print(time.time()-time_start) log.write(str(time.time()-time_start)+'\t') Packet_class.parser(packet_temp,count,ptr_packet) Packet_class.packet_print(log) log.close() elif (hello != '' and cmd_en == 1): packet[count] = hello[j] # print_hex(char_to_int(hello,1),1) if (count == len(packet)-1): count =0 else: count += 1 j+=1 if m.kbhit() == 1: q = m.getche() if q == 'q': log.close() sys.exit(1)
def userinput_with_timeout_windows(timeout, default=''): """Read user input. Return default value given after timeout. This function is used when running on windows-based systems. :param timeout: Number of seconds till timeout :param default: Default string to be returned after timeout :type default: String :returns: String """ start_time = time.time() sys.stdout.flush() userinput = '' while True: if msvcrt.kbhit(): readchar = msvcrt.getche() if ord(readchar) == 13: # enter_key break elif ord(readchar) >= 32: # space_char userinput += readchar if len(userinput) == 0 and (time.time() - start_time) > timeout: break if len(userinput) > 0: return userinput else: return default
def run(self): """ """ global _Server_Queue while True: # What would cause this to stop? Only the program ending. line = "" while 1: char = msvcrt.getche() if char == "\r": # enter break elif char == "\x08": # backspace # Remove a character from the screen msvcrt.putch(" ") msvcrt.putch(char) # Remove a character from the string line = line[:-1] elif char in string.printable: line += char time.sleep(0.01) try: _Server_Queue.put(line) if line != "": _Logger.debug("Input from server console: %s" % line) except: pass
def CheckFiles(infilename, outfilename, forceoverwrite=False): print('Source file: %s' % infilename) print('Destination file: %s' % outfilename) if not os.path.exists(infilename): print('Source file doesn\'t exist!') return False if os.path.exists(outfilename): if forceoverwrite: print('Destination file already exists! Overwriting.' ) else: print('Destination file already exists! Overwrite the existing file? (y/n) ' ) sys.stdout.flush() answer = msvcrt.getche() print('') if answer != b'y' : return False try: os.remove(outfilename); except: print('Error while trying to delete file: %s' % sys.exc_info()[1]) return False return True
def input_with_timeout(timeout): if platform.system() == 'Windows': start_time = time.time() s = '' while True: while msvcrt.kbhit(): c = msvcrt.getche() if ord(c) == 13: # enter_key break elif ord(c) >= 32: #space_char s += c if time.time() - start_time > timeout: return None return s else: while True: try: rlist, _, _ = select.select([sys.stdin], [], [], timeout) break except (OSError, select.error) as e: if e.args[0] != errno.EINTR: raise e if rlist: return sys.stdin.readline() else: return None
def inline_menu(reload = "None"): """ Test for in-line menu commands while waiting. """ # enter timer loop # start_time = time.time() while True: # check for keyboard events if msvcrt.kbhit(): key = msvcrt.getche() try: option = key.decode() except: option = "" # capture menu presses if option in ['E', 'e'] : email() if option in ['Q', 'q'] : sys.exit() if option in ['L', 'l'] : load_lusas(True) if reload == "Reload": if option in ['Y', 'y'] : return if option in ['N', 'n'] : sys.exit() # break timer if reload == "None": time.sleep(MEN_WAIT) break
def get_ui_to(prompt, toSec=None, tSleepSec=None): # import sys from time import time, sleep from msvcrt import getch, getche, kbhit if toSec==None: # wait forever userKey = raw_input(prompt) return userKey tElapsed = 0 t0 = time() if tSleepSec == None: tSleep = 0.1*toSec else: tSleep = tSleepSec while True: if tElapsed > toSec: print "Timeout after tElapsed secs...%.3f"%tElapsed userKey = '' break print "\n", prompt, if kbhit(): userKey = getche() while kbhit(): # flush input getch() # sys.stdin.flush() # userKey = raw_input(prompt) break # print "sleep tSleep secs...%.3f"%tSleep sleep(tSleep) tNow = time() tElapsed = tNow - t0 return userKey
def getResponse(self): try: if sys.stdin.isatty(): return raw_input(">") else: if sys.platform[:3] == "win": import msvcrt msvcrt.putch(">") key = msvcrt.getche() msvcrt.putch("\n") return key elif sys.platform[:5] == "linux": print ">" console = open("/dev/tty") line = console.readline()[:-1] return line else: print "[pause]" import time time.sleep(5) return "y" except: return "done"
def getkey(): while 1: if echo: z = msvcrt.getche() else: z = msvcrt.getch() if z == '\0' or z == '\xe0': #functions keys msvcrt.getch() else: return z
def getReply(): if sys.stdin.isatty(): return input("?") if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not supported'
def getreply(): if sys.stdin.isatty(): return sys.stdin.read(1) else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() return key else: return open('/dev/tty').readline()[:-1]
def readInput( caption, default, timeout = 15): start_time = time.time() sys.stdout.write('%s[Default=%s]:'%(caption, default)); print("") input = '' while True: if msvcrt.kbhit(): #kbhit functuion returns true if a key is hit chr = msvcrt.getche() #reads the key pressed on keyboard and stores it as chr if ord(chr) == 13: # enter_key break elif ord(chr) == 8: # backspace input = input[0:-1] elif ord(chr) == 224: #Special Characters like arrows, ins, delete, etc. chr = msvcrt.getche() if ord(chr) == 72: # Up Arrow pass elif ord(chr) == 75: # Left Arrow pass elif ord(chr) == 77: # Right Arrow pass elif ord(chr) == 80: # Down Arrow pass elif ord(chr) == 83: # Delete Key pass else: pass elif chr.isalnum(): #>= 32: #Any other characters input += chr elif chr == " ": input += chr print("\r"+" "*70+"\r" + input), if len(input) == 0 and (time.time() - start_time) > timeout: break print '' # needed to move to next line if len(input) > 0: return input else: return default #this returns default value for weapon if the user can't select in the appropriate time.
def getkey(): while True: if echo: z = msvcrt.getche() else: z = msvcrt.getch() if z == "\0" or z == "\xe0": # functions keys msvcrt.getch() else: if z == "\r": return "\n" return z
def raw_input_with_timeout(prompt,t,ch): print "--->"+prompt finishat = time.time() + t result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': # or \n, whatever Win returns;-) return ''.join(result) time.sleep(0.1) # just to yield to other processes/threads else: if time.time() > finishat: return ch
def keyboardTimeOut(timeout = 50): now = time.time() inp = '' chr = '\0' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) >= 32: #space_char inp += chr chr = '\0' if (time.time()-now)>(0.001*timeout): break return inp
def poll(self): """Poll for data on msvcrt (Windows only)""" completeLineRead = False while msvcrt.kbhit(): nextChar = msvcrt.getche() if nextChar == "\r": completeLineRead = True print("") break self.inputLine += nextChar if completeLineRead: self.processBuffer(self.inputLine) self.inputLine = ""
def getreply(): if sys.stdin.isatty(): return raw_input("?") else: if sys.platform[:3] == "lin": import msvcrt msvcrt.putch(b"?") key = msvcrt.getche() msvcrt.putch(b"\n") return key else: assert False, "platform not supported"
def escapableSleep(timeout,verbose=True): start_time = time.time() if verbose: sys.stdout.write("Waiting %d s (press Q to cancel)"%(timeout)) userStop = False while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 113: # q_key userStop = True break if (time.time() - start_time) > timeout: break print '' # needed to move to next line return userStop
def getreply(): ''' 读取交互式用户的回复键,即使stdin重定向到某个文件或者管道 ''' if sys.stdin.isatty(): return input('?') # 如果stdin 是控制台 从stdin 读取回复行数据 else : if sys.platform[:3] == 'win': # 如果stdin 重定向,不能用于询问用户 import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() # 使用windows 控制台工具 getch()方法不能回应键 return key else: assert False,'platform not supported'
def timeoutInput(prompt, timeout=30.0): sys.stdout.write(prompt) finishat = time.time() + timeout result = [] while True: if msvcrt.kbhit(): result.append(msvcrt.getche()) if result[-1] == '\r': # or \n, whatever Win returns;-) print('') return 'input' time.sleep(0.1) # just to yield to other processes/threads else: if time.time() > finishat: print('') return 'no_input'
def readInput( default, timeout = .01): start_time = time.time() input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 46: # \n break elif ord(chr) >= 32: #space_char input += chr if len(input) == 0 and (time.time() - start_time) > timeout: break if len(input) > 0: return input else: return default
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): return input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not supported'
def getreply(): """ читает клавишу, нажатую пользователем, даже если stdin перенаправлен в файл или канал """ if sys.stdin.isatty(): # если stdin связан с консолью, return input('?') # читать ответ из stdin else: if sys.platform[:3] == 'win': # если stdin был перенаправлен, import msvcrt # его нельзя использовать для чтения msvcrt.putch(b'?') # ответа пользователя key = msvcrt.getche() # использовать инструмент консоли msvcrt.putch(b'\n') # getch(), которая не выводит символ return key # для нажатой клавиши else: assert False, 'platform not supported'
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): # if stdin is console return input('?') # read reply line from stdin else: if sys.platform[:3] == 'win': # if stdin was redirected import msvcrt # can't use to ask a user msvcrt.putch(b'?') key = msvcrt.getche() # use windows console tools msvcrt.putch(b'\n') # getch() does not echo key return key else: assert False, 'platform not supported'
def readInput( caption, default, timeout = 5): start_time = time() inputS = '' while True: if msvcrt.kbhit(): chrS = msvcrt.getche() if ord(chrS) == 13: # enter_key break elif ord(chrS) >= 32: #space_char inputS += chrS if len(inputS) == 0 and (time() - start_time) > timeout: break if len(inputS) > 0: return inputS else: return default
def nonstoppinginput(word, prompt, next_best): global need_new_order os.system("cls") print(prompt + word, end='\n') need_new_order = True current = word while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13 or chr == b'\n': current = "" break elif chr == b'\x08': # backspace current = current[:len(current)-1] break elif ord(chr) == 9 and best[0]!="": # Tab autocomplete last_space = -1 for i in range(len(current)): if current[i] == ' ': last_space = i current = current[:last_space+1] current += best[0] # Change last word to whatever is currently stored in the word pointer # best contains best 3 break elif chr == b'@' and best[1]!="": # Tab autocomplete last_space = -1 for i in range(len(current)): if current[i] == ' ': last_space = i current = current[:last_space+1] current += best[1] # get second best break elif chr == b'#' and best[2]!="": # Tab autocomplete last_space = -1 for i in range(len(current)): if current[i] == ' ': last_space = i current = current[:last_space+1] current += best[2] # get third best break elif ord(chr) >= 32: current+= chr.decode('utf-8') break print ('') # needed to move to next line return current
def timed_input(self, caption, default=None, timeout=60): start_time = time.time(); sys.stdout.write(caption); input = ''; while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13: # enter_key break; elif ord(chr) == 8: #backspace_key input = input[:-1]; elif ord(chr) >= 32: #space_char + (all keys on keyboard) input += chr; if len(input) == 0 and (time.time() - start_time) > timeout: break; print ''; # needed to move to next line input = input.strip(); if len(input) > 0: return input; else: return default;
def readInput( caption, default, timeout = 0.1): start_time = time.time() sys.stdout.write('%s: '%(caption)); #('%s(%s):'%(caption, default)); input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13: # enter_key break elif ord(chr) >= 32: #space_char input += chr if len(input) == 0 and (time.time() - start_time) > timeout: break print '' # needed to move to next line if len(input) > 0: return input else: return default
def readInput(caption, default, timeout=5): start_time = time.time() sys.stdout.write('%s(%s):' % (caption, default)) sys.stdout.flush() input = '' while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 13: # enter_key break elif ord(byte_arr) >= 32: #space_char input += "".join(map(chr, byte_arr)) if len(input) == 0 and (time.time() - start_time) > timeout: break if len(input) > 0: return input else: return default
def input_with_timeout_windows(prompt, timeout, default): start_time = time.time() print prompt, sys.stdout.flush() input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13: # enter_key break elif ord(chr) >= 32: #space_char input += chr if len(input) == 0 and (time.time() - start_time) > timeout: break if len(input) > 0: return input else: return default
def wait_enter_or_seconds(caption, timeout=5): start_time = time.time() sys.stdout.write('%s' % caption) sys.stdout.flush() input_string = '' while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 13: # enter_key break elif ord(byte_arr) >= 32: # space_char input_string += "".join(map(chr, byte_arr)) if len(input_string) == 0 and (time.time() - start_time) > timeout: break print('') # needed to move to next line return input_string
def input_with_timeout_windows(prompt, timeout, default): start_time = time.time() print(prompt) sys.stdout.flush() input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche().decode('utf-8') if ord(chr) == 13: # enter_key break elif ord(chr) >= 32: #space_char input += chr if len(input) == 0 and (time.time() - start_time) > timeout: break if len(input) > 0: return input else: return default
def read_input(timeout=0.1): if os.name == "nt": import msvcrt import time start_time = time.time() user_input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13: # enter_key break elif ord(chr) >= 32: #space_char user_input += chr.decode() if len(user_input) == 0 and (time.time() - start_time) > timeout: break else: user_input, wlist, xlist = select.select([sys.stdin], [], [], timeout) return user_input
def readInput(caption, queue): sys.stdout.write('%s :' % caption) sys.stdout.flush() input = '' while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 13: # enter_key break elif ord(byte_arr) >= 32: #space_char input += "".join(map(chr, byte_arr)) global shoudExit if shouldExit == True: logging.info("User used the URL. No need for password input") return False queue.put(input) return True
def intake(): readfile = open('persistentinfo', 'r') writefile = open('persistentinfo', 'wb') try: info = pickle.load(readfile) except EOFError: info = {} print 'What is the phone number you would like to store? Press "c" to cancel.\n' keypress = getche() if keypress == 'C' or keypress == 'c': main() elif keypress == '\r': print 'Number not entered! Please try again.\n\n' intake() else: number = raw_input() if number == '': print 'Number not entered! Please try again.\n\n' intake()
def getreply(): """ читает клавишу, нажатую пользователем, даже если stdin перенаправлен в файл или канал :return: """ if sys.stdin.isatty( ): # если stdin связан с консолью, читать ответ из stdin return input('Type \'y\' or \'Y\' to continue, or other to exit>>') else: if sys.platform[:3] == 'win': # если stdin был перенаправлен, import msvcrt # его нельзя использовать для чтения msvcrt.putch(b'?') # ответа пользователя key = msvcrt.getche() # использовать иснтрумент консоли msvcrt.putch(b'\n') # getche(), которая не выводит символ return key # для нажатия клавиши else: assert False, 'Platform not supported'
def read_key_board_input(timeout=5): """ 默认值返回False :param timeout:设置超时 :type timeout:float :return:True or False :rtype:bool """ start_time = time.time() confirm_time = time.time() confirm_text = 0 cancel_text = 0 sys.stdout.write("是否输入用户标识(y or n ,默认值为:n)并按回车键确认") while True: if msvcrt.kbhit(): char = msvcrt.getche() # temp = ord(char) if cancel_text == 0 and (ord(char) == 121 or ord(char) == 89): # y or Y confirm_text = ord(char) confirm_time = time.time() continue if confirm_text == 0 and (ord(char) == 110 or ord(char) == 78): # n or N cancel_text = ord(char) start_time = time.time() continue # 输入y 或者Y 并回车 if confirm_text != 0 and ord(char) == 13: # enter_key return True # 直接回车 if ord(char) == 13: return False # if ord(char) == 27: # ESC # return True # 输入n 或者N后未按回车超时执行 if confirm_text == 0 and (time.time() - start_time > timeout): return False # 输入y 或者Y后未按回车超时执行 if cancel_text == 0 and confirm_text != 0 and ( time.time() - confirm_time > timeout): return True
def timer(timeout = 5): start_time = time.time() print("") print(">>> ") enter = "" while True: if msvcrt.kbhit(): c = msvcrt.getche() if ord(c) == 13: # enter_key break elif ord(c) >= 32: #space_char enter += str(c) if (time.time() - start_time) > timeout: break if len(enter) > 0: return enter.replace("b'", "").replace("'", "") else: return "Stumble"
def readInput( caption, default, timeout = 5): start_time = time.time() sys.stdout.write('%s(%s):'%(caption, default)); input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getche() if ord(chr) == 13: # enter_key break elif ord(chr) >= 32: #space_char input += chr if len(input) == 0 and (time.time() - start_time) > timeout: break print '' # needed to move to next line if len(input) > 0: return input else: return default
def listener(info): import msvcrt chars = [] while True: while not msvcrt.kbhit(): pass letter = msvcrt.getche().decode("utf-8") if letter == "\x03": raise KeyboardInterrupt if letter == "\x08": if len(chars) != 0: del chars[len(chars) - 1] elif letter == "\r": word = "".join(chars) print("\n") info.process_command(word) chars = [] else: chars.append(letter)
def readInput(caption, timeout, keypress_bonus): os.system('clear||cls') sys.stdout.write("\nTime: " + "%.16f" % timeout + "\n" + caption) sys.stdout.flush() start_time = time.time() string = "" err = "" while True: if msvcrt.kbhit(): # Get input data byte_arr = msvcrt.getche() char = ord(byte_arr) # Act accordinly if char == 13: # enter_key out = fixString(string) current_err = checkString(out) if current_err: err = current_err else: if out in used_words: return '-2' + out return out elif char == 8: # backspace string = string[:-1] if bonus_for_backspace: timeout += keypress_bonus elif (char >= 97 and char <= 122) or ( char >= 65 and char <= 90) or char in ignored_characters: string += "".join(map(chr, byte_arr)) timeout += keypress_bonus # Print new string os.system('clear||cls') sys.stdout.write(err + "\nTime: " + "%.16f" % (timeout - (time.time() - start_time)) + "\n" + caption + string) sys.stdout.flush() if (time.time() - start_time) > timeout: # Return nothing for unfinished string return '-1' + string
def getreply(): """ read a reply key from an interative user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): return input('??') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: #assert False, 'platform not supported' print('???') key = open('/dev/tty').readline()[:-1] print(key) return key
def _windows_input(self, text, timeout_s, default): start_time = time.time() sys.stdout.write(text) sys.stdout.flush() current = '' while True: if msvcrt.kbhit(): c = msvcrt.getche() if ord(c) == 13: # Enter break elif ord(c) >= 32: # Character current += c.decode('utf-8') if (time.time() - start_time) > timeout_s: break print() if len(current) > 0: return current else: return default
def readInput(caption='', default=None, timeout=1): start_time = time.time() #sys.stdout.write('%s(%s):'%(caption, default)) #sys.stdout.flush() input = '' while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 13: # enter_key break elif ord(byte_arr) >= 32: #space_char input += "".join(map(chr, byte_arr)) if len(input) == 0 and (time.time() - start_time) > timeout: #print("timing out, using from Rodefault value.") break #print('') # needed to move to next line if len(input) > 0: return input else: return default
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): # if stdin is console return input("More? y/Y") # read reply line from stdin else: if sys.platform[:3] == 'win': # if stdin was redirected import msvcrt # can't use to ask a user msvcrt.putch(b'?') key = msvcrt.getche() # use windows console tools msvcrt.putch(b'\n') # getch() does not echo key return key elif sys.platform == 'darwin': os.system("printf 'More? '") key = open('/dev/tty').readline()[:-1] os.system("printf '\n'") return key else: assert False, 'platform not supported'
def __consoleTask_w(self, Task): '''This task accepts commands for the server in a Windows environment. We use getch as a non-blocking input.''' if msvcrt.kbhit(): c = msvcrt.getche() if (c == '\r'): self._haveCommand = True elif (c == '\b'): # TODO - Also clear the onscreen buffer of the character self._command = self._command[0:len(self._command) - 1] else: self._command += c if self._haveCommand: cmd = self._command[0:len(self._command) - 1] print(cmd) self._commandTok = cmd.split() print("\bpsg: " + self._command) self.__handleCommand() print("psg: "), self._command = [] self._haveCommand = False return Task.cont
def get_reply(): """ :return: """ # 需要在命令行下调试,pycharm的sys.stdin不是控制台。 sys.stdin.isatty() 为false if sys.stdin.isatty(): print("for test") return input("Continue to read? [Y/N]") else: if sys.platform == 'win32': import msvcrt # b'' 代表输入的是bytes而不是str。 # msvcrt.putch:Print the byte string char to the console without buffering. msvcrt.putch(b'Continue ? [Y/N]') # 获取用户输入。 key = msvcrt.getche() msvcrt.putch(b'\n') return key else: # Linux不支持。 assert False, "Platform doesn't support!"
def get_user_input(self, caption, default, hidden_flag=False, timeout=10): # Owner:11602272 # CreateTime:2015年7月3日 # ModifyTime: # 函数参数: 说明标题, 默认值 # 函数方法:获取用户输入的值 # 函数返回值:user_input sys.stdout.write('%s(Default is %s):\n' % (caption, default)) os_platform = self.assert_platform() if os_platform == "Windows": import msvcrt start_time = time.time() user_input = '' while True: if msvcrt.kbhit(): if hidden_flag: user_input_char = msvcrt.getch() else: user_input_char = msvcrt.getche() if ord(user_input_char) == 13: # enter_key break elif ord(user_input_char) >= 32: # space_char user_input += user_input_char if hidden_flag: sys.stdout.write('*') if len(user_input) == 0 and (time.time() - start_time) > timeout: break elif os_platform == "Linux": import select print "You have ten seconds to answer!" i, o, e = select.select([sys.stdin], [], [], timeout) if (i): user_input = sys.stdin.readline().strip() else: user_input = "" if len(user_input) > 0: return user_input else: return default
def wait_player_move(): global player_cpos pmove = msvcrt.getche() cur_x, cur_y = player_cpos if pmove == b"w": cur_y -= 1 if 4 > cur_y: cur_y = 4 elif pmove == b"a": cur_x -= 1 if 10 >= cur_x: cur_x = 10 elif pmove == b"s": cur_y += 1 elif pmove == b"d": cur_x += 1 elif pmove == b"q": print("\n\nThanks for playing. See you next year!!!") sys.exit(-1) else: pass player_cpos = (cur_x, cur_y)
def run(self): while True: if self.readList: # Is the server socket ready for reading or writing? read, write, exception = select.select(self.readList, self.writeList, self.readList, 1) for s in read: if s == self.socket: # A client is trying to connect self.process_server_data() for s in write: if s == self.socket: self.send_outgoing_data() self.writeList.remove(s) for s in exception: if s == self.socket: print( "Server socket encountered exception. Please login again" ) self.readList.remove(self.socket) if self.socket in self.writeList: self.writeList.remove(self.socket) self.socket.close() # Check for keyboard input while msvcrt.kbhit(): newChar = msvcrt.getche() if newChar == '\r': print('') if self.keyboardInput != '': self.process_user_input(self.keyboardInput) self.keyboardInput = '' else: self.keyboardInput = self.keyboardInput + newChar
def run(self): oldRec = "" while True: while msvcrt.kbhit(): key = msvcrt.getche() if key.decode("utf-8").lower( ) in "1234567890!@#$%^&*)-=_+`~qwertyuiopasdfghjklzxcvbnm,./[]{}|'\";:<>? ": self.manualChat = "{}{}".format(self.manualChat, key.decode("utf-8")) if key == b'\x08' and len(self.manualChat) > 0: #backspace self.manualChat = self.manualChat[:-1] if key == b'\r' and len(self.manualChat) > 0: #return self.send(self.manualChat) self.manualChat = "" rec = "{0}{1}".format(oldRec, self.receive()) while "\r\n" in rec: rec2 = rec[:rec.index("\r\n")] if rec2 != "": self.process(rec2) rec = rec[rec.index("\r\n") + 2:] oldRec = rec return
def readInput(caption, default, timeout=10): start_time = time.time() sys.stdout.write('%s(%d秒自动跳过):' % (caption, timeout)) sys.stdout.flush() input = '' while True: ini = msvcrt.kbhit() try: if ini: chr = msvcrt.getche() if ord(chr) == 13: # enter_key break elif ord(chr) >= 32: input += chr.decode() except Exception as e: pass if len(input) == 0 and time.time() - start_time > timeout: break if len(input) > 0: return input + '' else: return default
def readInput(caption, default, timeout=5): if caption != '': print(caption) start_time = time.time() input = '' while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 13: # enter_key break elif ord(byte_arr) >= 32: #space_char input += "".join(map(chr, byte_arr)) if len(input) == 0 or (time.time() - start_time) > timeout: # print("timing out, using default value.") break # print('') # needed to move to next line if len(input) > 0: return input else: return default
def select_reader(): """Select cardreader with console onscreen menu. Returns selected reader object or None if no readers connected or user decided to escape shell. If system has a single reader connected it will be returned without of menu drawing. """ readers_list = readers() if not readers_list: return if len(readers_list) == 1: return readers_list[0] else: print 'Please choose reader number from list or 0 to exit:\n\n' for i, r in enumerate(readers_list): print '[{}] - {}\n'.format(i + 1, r) print '\n[0] - Exit without choosing\n' choice = None while not msvcrt.kbhit(): choice = msvcrt.getche() if not choice.isdigit(): continue if choice == '0': return try: return readers_list[int(choice) - 1] except IndexError: pass
def game_2048(board, n, w, flag): ret = check(board, n, w) if ret != "end": if ret == "zero" and flag != 0: board = new_2(board, n) else: print("Try another move") ret = check(board, n, w) if ret != "end": clr() print_board(board, n) while True: print( '''Enter move:\n\tw for up\n\td for down\n\ta for left\n\td for right\n\tq to forfeit \n ''' ) move = getch.getche().decode("ASCII").lower() if move == 'q': clr() print( "This was the final board, the game was forfeited by user") print_board(board, n) return 0 if move not in ('w', 'a', 's', 'd'): print("Invalid Input") else: break if move == 's': board, flag = moving(rotation(board, n), n) board = rotation_anti(board, n) elif move == 'd': board, flag = moving(rotation(rotation(board, n), n), n) board = rotation(rotation(board, n), n) elif move == 'w': board, flag = moving(rotation_anti(board, n), n) board = rotation(board, n) elif move == 'a': board, flag = moving(board, n) game_2048(board, n, w, flag)
def getChar(numBytes, listOfOneChars): import sys # Flush output sys.stdout.flush() # Important for executing prior print statement # Check for Windows system try: import msvcrt answer = "" for i in range(numBytes): ch = msvcrt.getche().decode() ch = ch.upper() if (ch in listOfOneChars): print('') return ch answer += ch print('') # Starts a new line following function call return answer # Else, POSIX system except ImportError: import tty, sys, termios fd = sys.stdin.fileno() # File descriptor oldSettings = termios.tcgetattr(fd) # tty attributes for fd try: answer = "" tty.setraw(fd) # Change mode to raw for i in range(numBytes): ch = sys.stdin.read(1) # Read in byte(s) print(ch, end='') # Puts the character to the console ch = ch.upper() # Make uppercase sys.stdout.flush() if (ch in listOfOneChars): termios.tcsetattr(fd, termios.TCSADRAIN, oldSettings) print('') return ch answer += ch finally: # Change after discarding queued input termios.tcsetattr(fd, termios.TCSADRAIN, oldSettings) print('') return answer
def read_with_timeout( caption, default, default_prompt = "You did not respond!", timeout = 10): import sys, time, msvcrt start_time = time.time() sys.stdout.write('%s(%s):'%(caption, default)) sys.stdout.flush() input = '' while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 13: # enter_key break elif ord(byte_arr) >= 32: #space_char input += "".join(map(chr,byte_arr)) if len(input) == 0 and (time.time() - start_time) > timeout: desktop_notification(not_tit="You did not respond!",msg='Joining Automatically.') print(default_prompt) break print('') # needed to move to next line if len(input) > 0: return input else: return default
def readInput(default, timeout=0.3): #method to read user input every 0.5 seconds, if no or invalid input it will run the previous direction (default) start_time = time.time() input = 0 while True: if msvcrt.kbhit(): byte_arr = msvcrt.getche() if ord(byte_arr) == 119: input = "w" elif ord(byte_arr) == 115: input = "s" elif ord(byte_arr) == 100: input = "d" elif ord(byte_arr) == 97: input = "a" if (time.time() - start_time) > timeout: break #only allows valid inputs, if not use default print("") if input in inputs[default - 1]: return input else: return default