コード例 #1
0
ファイル: console.py プロジェクト: FedeG/autopython
 def _getch():
     a = msvcrt.getwch()
     if a == '\x00' or a == '\xe0':
         b = msvcrt.getwch()
         return [a, b]
     else:
         return a
コード例 #2
0
ファイル: Play.py プロジェクト: jaminthorns/ascii-snake
def processKey():
	"""Process the user input for menu navigation."""
	global option, size, difficulty, placeObstacles, play, quit

	key = msvcrt.getwch()

	if key == "\xe0":
		key = msvcrt.getwch()

		if key == Direction.UP and option > 0:
			option -= 1
		elif key == Direction.DOWN and option < 4:
			option += 1
		elif key == Direction.LEFT:
			if option == 1 and size > 0 and size <= 2:
				size -= 1
			elif option == 2 and difficulty > 0 and difficulty <= 2:
				difficulty -= 1
			elif option == 3:
				placeObstacles = not placeObstacles
		elif key == Direction.RIGHT:
			if option == 1 and size >= 0 and size < 2:
				size += 1
			elif option == 2 and difficulty >= 0 and difficulty < 2:
				difficulty += 1
			elif option == 3:
				placeObstacles = not placeObstacles
	elif key == "\r":
		if option == 0:
			play = True
		elif option == 4:
			quit = True
コード例 #3
0
ファイル: miniterm.py プロジェクト: hardkrash/pyserial
 def getkey(self):
     while True:
         z = msvcrt.getwch()
         if z == '\r':
             return '\n'
         elif z in '\x00\x0e':    # functions keys, ignore
             msvcrt.getwch()
         else:
             return z
コード例 #4
0
 def getkey(self):
     while True:
         z = msvcrt.getwch()
         if z == unichr(13):
             return unichr(10)
         elif z in (unichr(0), unichr(0x0e)):  # functions keys, ignore
             msvcrt.getwch()
         else:
             return z
コード例 #5
0
ファイル: miniterm.py プロジェクト: bq/witbox-updater
 def getkey(self):
     while True:
         z = msvcrt.getwch()
         if z == unichr(13):
             return unichr(10)
         elif z in (unichr(0), unichr(0x0e)):    # functions keys, ignore
             msvcrt.getwch()
         else:
             return z
コード例 #6
0
ファイル: main.py プロジェクト: eyenpi/Trie
def searchStudent():
    """
    search for a student in Trie and show student's dialog
    :return: Nothing
    """
    os.system("cls")
    print("Input Number: ")
    print("Press q to abort\nPress enter if you done typing")
    keyin = msvcrt.getwch()
    if keyin == 'q':
        print("Searching Aborted.")
        return
    state, s, hashID = t.search(keyin)
    os.system("cls")
    for k in s:
        print(k)
    while 1:
        print("Input Number:", keyin)
        print("Press q to abort\nPress enter if you done typing")
        keyinnow = msvcrt.getwch()
        if keyinnow == 'q':
            print("Searching Aborted.")
            return
        elif keyinnow == '\x08':
            keyin = keyin[:-1]
        elif keyinnow == '\r':
            break
        else:
            keyin += keyinnow
        os.system("cls")
        state, s, hashID = t.search(keyin)
        for j in s:
            print(j)
    number = keyin
    state, s, hashID = t.search(number)
    if state == 1:
        student = ht.getIndex(hashID, number)
        inp1 = 0
        while inp1 != 4:
            inp1 = int(
                input(
                    "1. View Student\n2. Delete Student\n3. Edit Student\n4. Exit\n"
                ))
            if inp1 == 1:
                print("Name:", student.data.name)
                print("Number:", student.data.number)
                print("GPA:", student.data.gpa)
                print("Field:", student.data.field)
            if inp1 == 2:
                deleteStudent(hashID, number)
                break
            if inp1 == 3:
                editStudent(hashID, number)
                break
    else:
        print("student doesn't exist.")
コード例 #7
0
 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
コード例 #8
0
ファイル: getkey.py プロジェクト: dmf24/pyscripting
 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
コード例 #9
0
    def collect_trajectory(self):
        print('STARTING A NEW {} STEP TRAJECTORY. TERMINATE EARLY BY PRESSING t'.format(self.steps_per_epoch))
        step = 0
        self.env.reset()
        while True:
            key = msvcrt.getwch()
            action = None
            if key == 'w':
                action = 1
            elif key == 'a':
                action = 2
            elif key == 'd':
                action = 3
            elif key == 'z':
                action = 5
            elif key == 'x':
                action = 4
            elif key == 's':
                action = 0
            elif key == 'r':
                print("ENVIRONMENT RESET BY PLAYER")
                self.env.reset()
            elif key == 'b' or key == 't':
                print('TRAJECTORY TERMINATED BY PLAYER')
                break

            if action is not None:
                obs, reward, done, info = self.env.step(action)
                if done:
                    self.env.reset()
                else:
                    value = torch.tensor([20], dtype=torch.float32)
                    log_prob = torch.tensor([0], dtype=torch.float32)
                    obs_vector, obs_visual = self.env_utils.process_obs(obs)
                    self.buffer.store(obs_vector, obs_visual, action, reward, value, log_prob)
                    step += 1
                    print('\rStep: {}'.format(step), end='\r')
                    if step == self.steps_per_epoch:
                        print('TRAJECTORY FINISHED')
                        self.buffer.finish_path(value)
                        data = self.buffer.get()
                        self.save_data(data)
                        break
        while True:
            print('COLLECT NEW TRAJECTORY? y = yes, n = no')
            key = msvcrt.getwch()
            if key == 'y':
                self.data_count += 1
                self.collect_trajectory()
            if key == 'n':
                return
            else:
                print("Enter valid answer!")
コード例 #10
0
def get_key():
    check = ord(msvcrt.getwch())

    if check == 224:
        key = msvcrt.getwch()

        try:
            return directions[key]
        except KeyError:
            return None
    else:
        return False
コード例 #11
0
ファイル: miniterm.py プロジェクト: RoderickJDunn/miniterm_py
 def getkey(self):
     while True:
         key = ord(msvcrt.getch())
         # print(key)
         if key == unichr(13):
             return unichr(10)
         elif key in (unichr(0),
                      unichr(0x0e)):  # functions keys, ignore
             msvcrt.getwch()
         elif key == 224:
             return key
         else:
             return unichr(key)
コード例 #12
0
ファイル: env.py プロジェクト: WYVERN2742/Central
def pause() -> None:
    """Pauses the application until a user enters a keypress.

	On windows this will be when any character is entered, on other machines
	Enter needs to be pressed."""
    if windows:
        # Windows
        msvcrt.getwch()
        print()
        return

    # Other Os
    input()
コード例 #13
0
def get_key():
    ch = msvcrt.getwch()
    if ch in ('\x00', '\xe0'):  # arrow or function key prefix?
        ch = msvcrt.getwch()  # second call returns the actual key code

    if ch in const.KEY_MAPPING:
        return const.KEY_MAPPING[ch]
    if ch == 'H':
        return const.KEY_UP
    if ch == 'P':
        return const.KEY_DOWN

    return ch
コード例 #14
0
def outer_question(clue = '1+1',  answer = '2'):
  ans=[]
  i=0
  while ans != answer:
    while i<len(answer):
        system('cls')
        print(clue)
        print("Enter Answer")
        answer1=answer.split()
        for i in range(0,len(answer1)):
          ans.append(single_ans(answer1[i]))
        print (ans)
        getwch()
コード例 #15
0
ファイル: win32.py プロジェクト: RogueScholar/thefuck-termux
def get_key():
    ch = msvcrt.getwch()
    if ch in ("\x00", "\xe0"):  # arrow or function key prefix?
        ch = msvcrt.getwch()  # second call returns the actual key code

    if ch in const.KEY_MAPPING:
        return const.KEY_MAPPING[ch]
    if ch == "H":
        return const.KEY_UP
    if ch == "P":
        return const.KEY_DOWN

    return ch
コード例 #16
0
 def getkey(self):
     while True:
         z = msvcrt.getwch()
         if z is unichr(0) or z is unichr(0xe0):
             try:
                 code = msvcrt.getwch()
                 if z is unichr(0):
                     return self.fncodes[code]
                 else:
                     return self.navcodes[code]
             except KeyError:
                 pass
         else:
             return z
コード例 #17
0
ファイル: bot.py プロジェクト: bzl3/Project_RAC
def get_point():
    ret = True
    while ret:
        c = msvcrt.getwch()
        if "c" == c:
            ret = False
    return pyautogui.position()
コード例 #18
0
ファイル: inputPass.py プロジェクト: iaz3/RbxAPI
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
コード例 #19
0
ファイル: tcpserv.py プロジェクト: Mixfair/Mail-Tester
    def command_worker_windows(self):
        cmd = b''
        c = b''
        self.info_msg(platform)
        while 1:

            if msvcrt.kbhit():

                cr = msvcrt.getwch()
                c = cr.encode('utf-8')
                try:
                    msvcrt.putch(c)
                except TypeError:
                    continue

                if c != b'\r' and c != b'\x08':
                    cmd += c
                    c = b''
                elif c == b'\x08':
                    cmd = cmd[:len(cmd) - 1]
                    msvcrt.putch(b' ')
                    msvcrt.putch(b'\x08')
                elif c == b'\r':
                    os.write(1, b'\n')
                    try:
                        self.call_cmd(cmd.decode("UTF-8"))
                    except UnicodeDecodeError:
                        self.info_msg('Неверный формат')

                    cmd = b''
            gevent.sleep(0.1)
コード例 #20
0
 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)
コード例 #21
0
ファイル: ezportify.py プロジェクト: essoen/ezportify
def win_getpass(prompt='Password: '******'\r' or c == '\n':
			break
		if c == '\003':
			raise KeyboardInterrupt
		if c == '\b':
			if pw == '':
				pass
			else:
				pw = pw[:-1]
				msvcrt.putch('\b')
				msvcrt.putch(" ")
				msvcrt.putch('\b')
		else:
			pw = pw + c
			msvcrt.putch("*")
	msvcrt.putch('\r')
	msvcrt.putch('\n')
	return pw
コード例 #22
0
 def getkey(self) -> str:
     while True:
         z = msvcrt.getwch()
         if z == chr(13):
             return chr(10)
         elif z is chr(0) or z is chr(0xe0):
             try:
                 code = msvcrt.getwch()
                 if z is chr(0):
                     return self.fncodes[code]
                 else:
                     return self.navcodes[code]
             except KeyError:
                 pass
         else:
             return z
コード例 #23
0
ファイル: unicode_getpass.py プロジェクト: JimmXinu/calibre
 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)
コード例 #24
0
def win_terminal(input_buffer_number, device_buffer_number, input_device):
    if msvcrt.kbhit():
        # for test purposes!!
        # this is the keyboard interface not according to MYC specification:
        # a numeric input as ascii (decimal 0... 255) values is converted to one byte
        # after each space the sub for checking the v_kbd_input.a is called
        # str
        t = msvcrt.getwch()
        if ord(t) == 32:
            if v_kbd_input.a != "":
                i = (int(v_kbd_input.a))
                if i < 256:
                    # 0: buffer for input, 1: buffer for device
                    if input_device == 0:
                        # start timeout
                        if v_input_buffer.starttime[input_buffer_number] == 0:
                            v_input_buffer.starttime[input_buffer_number] = int(time.time())
                            # input buffer
                            v_input_buffer.inputline[input_buffer_number] += int_to_bytes(i, 1)
                            if input_device == 0:
                                print("HI_in", input_buffer_number, v_kbd_input.a)
                            else:
                                print("device_in", device_buffer_number, v_kbd_input.a)
                    else:
                        v_device_buffer.data_to_CR[device_buffer_number] += int_to_bytes(i, 1)
                    v_kbd_input.a = ""
        else:
            if str.isnumeric(t) == 1:
                v_kbd_input.a += t
    return
コード例 #25
0
def input_events():
    choice = ord(m.getwch())
    dirt = False
    if choice == LEFT_ARROW:
        move(WEST)
        dirt = True
    elif choice == UP_ARROW:
        move(NORTH)
        dirt = True
    elif choice == DOWN_ARROW:
        move(SOUTH)
        dirt = True
    elif choice == RIGHT_ARROW:
        move(EAST)
        dirt = True
    elif choice == ESC:
        dirt = True
        quit_choice = input("Do you really want to quit?\n")
        if quit_choice[0].upper() == "Y":
            quit()
        else:
            print("I'm taking that as a no...")
            time.sleep(0.5)
    if (not dirt) and choice != 224:
        first_char = chr(choice)
        print(first_char, end="")
        actual_choice = input()
        actual_choice = first_char + actual_choice
        process_text(actual_choice)
コード例 #26
0
def getchar():
    """
    Returns a single character from standard input
    
    Returns:
        ch (str): Character corresponding to pressed key
    """

    ch = ''
    if os.name == 'nt':
        #Windows
        import msvcrt
        ch = msvcrt.getwch()
    else:
        #Linux
        import tty, termios, sys
        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)

    if ord(ch) == 3:
        raise KeyboardInterrupt  # handle ctrl+C

    return ch
コード例 #27
0
    def clickComRetorno(self, processe=True):  #{

        from msvcrt import getwch

        # Se alguma tecla for pressionada
        if self.clickEsperando:  #{

            self.click = getwch()

            # Se quiser que retorne a string com o comando
            if processe:  #{

                return self.listaDeComandos[self.click]

            #}

            else:  #{

                return self.click

            #}

        #}

        else:  #{

            return None

        #}

    #}


#}
コード例 #28
0
def main():
    size = input("Choose the size of your board.\n")
    b = Board(int(size),int(size))
    b.generateNewBlock()
    win = graphics.GraphWin("TheBoard", b.cols*cellSize, b.rows*cellSize)
    gameOver = False
    for i in b.board:
        b.board[i].visual.draw(win)
        b.board[i].text.draw(win)
    while not gameOver:
        for i in b.board:
            b.board[i].setColor()
            if b.board[i].number != 0:
                b.board[i].text.setText(str(b.board[i].number))
            else:
                b.board[i].text.setText("")
        char = msvcrt.getwch()
        move = None
        if char == 'a':
            move = 'left'
        if char == 's':
            move = 'down'
        if char == 'd':
            move = 'right'
        if char == 'w':
            move = 'up'
        if char == 'q':
            print("Bye!")
            time.sleep(1)
            return
        if type(move) == type(''):
            b.push(move)
            gameOver = b.generateNewBlock()
    return "GAME OVER"
コード例 #29
0
ファイル: interpreter.py プロジェクト: NilSet/whitespacers
 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)
コード例 #30
0
 def get_key(self):
     key = msvcrt.getwch()
     if ord(key) == 224:
         second = msvcrt.getwch()
         if ord(second) == 72:
             return 'KEY_UP'
         elif ord(second) == 80:
             return 'KEY_DOWN'
         elif ord(second) == 75:
             return 'KEY_LEFT'
         elif ord(second) == 77:
             return 'KEY_RIGHT'
         else:
             return ord(second)
     else:
         return key
コード例 #31
0
def main():
    while True:
        key = ord(ms.getwch())
        if key == 27:  # ESC
            break
        else:
            print key
コード例 #32
0
def win_getpass(prompt='Password: '******'\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            if pw == '':
                pass
            else:
                pw = pw[:-1]
                msvcrt.putwch('\b')
                msvcrt.putwch(" ")
                msvcrt.putwch('\b')
        else:
            pw = pw + c
            msvcrt.putwch("*")
    msvcrt.putwch('\r')
    msvcrt.putwch('\n')
    return pw
コード例 #33
0
    def timed_input(prompt='', timeout=None):
        """
        timed_input([prompt], [timeout]) -> string

        Read a string from standard input. The trailing newline is stripped.
        If the user does not press return in :timeout: seconds, None is returned.

        The Windows version does not support arrow keys
        """
        if timeout is None:
            return input(prompt)
        _print_flush(prompt)
        start = time.time()
        response = ''
        while time.time() - start < timeout:
            if kbhit():
                char = getwch()
                if char == '\r':
                    break
                elif char == '\x08':  # backspace
                    if response:
                        _print_flush(char, char)
                        response = response[:-1]
                else:
                    _print_flush(char)
                    response += char
            time.sleep(0.01)
        else:
            response = None
        print()
        return response
コード例 #34
0
ファイル: cxConsoleThread.py プロジェクト: ClarkOh/MyWork
    def readInput(self, prompt, timeout = 10 ) :
        start_time = time.time()
        sys.stdout.write(u'%s'%prompt)
        inputString = u''
        while True :
            if (time.time() - start_time) > timeout :
                return None
            if msvcrt.kbhit() :
                start_time = time.time()
                ch = msvcrt.getwch()

                if ord(ch) == 13 : # enter key
                    if inputString == 'q' :
                        return None
                    elif len(inputString) == 0 :
                        return None
                    elif len(inputString) > 0 :
                        return inputString
                elif ord(ch) == 8 : # back space
                    inputString = inputString[0:-1]
                else : inputString += ch
                
                try : inputString = unicode(inputString)
                except : 
                    sys.stdout.write(u'\r%s%s'%(prompt,
                                     u'unicode converting error for inputString'))
                    sys.stdout.flush()
                    continue
                
                sys.stdout.write(u'\r%s%s'%(prompt,' '*(len(inputString)*2+1)))
                sys.stdout.write(u'\r%s%s'%(prompt, inputString))
                sys.stdout.flush()
        return None
コード例 #35
0
 def rd(self):
     from msvcrt import getwch
     c = getwch()
     if ord(c) == 224 or c == '\x00':
         return '\x1b['
     else:
         return c
コード例 #36
0
ファイル: getch.py プロジェクト: tylercrompton/getch
def getch(prompt=''):

	"""Reads a character from standard input.

	If the user enters a newline, an empty string is returned. For the most
	part, this behaves just like input().  An optional prompt can be
	provided.

	"""

	print(prompt, end='')
	sys.stdout.flush()

	# Windows
	try:
		char = msvcrt.getwch()
	except NameError:
		pass
	else:
		if char == '\r' or char == '\n':
			char = ''

		print(char, end='')
		sys.stdout.flush()

		return char

	# Unix
	file_number = sys.stdin.fileno()
	try:
		old_settings = termios.tcgetattr(file_number)
	except NameError:
		pass
	except termios.error:
		pass
	else:
		tty.setcbreak(file_number)

	try:
		char = chr(27)
		if sys.stdin.isatty():
			# avoid escape sequences and other undesired characters
			while ord(char[0]) in (8, 27, 127):
				char = sys.stdin.read(len(sys.stdin.buffer.peek(1)))
		else:
			char = sys.stdin.read(1)

		if char == '\r' or char == '\n':
			char = ''

		if 'old_settings' in locals():
			print(char, end='')
			sys.stdout.flush()
	finally:
		try:
			termios.tcsetattr(file_number, termios.TCSADRAIN, old_settings)
		except NameError:
			pass

	return char
コード例 #37
0
ファイル: Controls.py プロジェクト: mkrooted/TankBattle
def normal(world: World, pl: Character):
    os.system('setterm -cursor off')
    print()
    direction = "down"
    flag = "none"
    while flag == "none":
        os.system('cls')
        pl.update()
        show_world(world, pl)
        print(statusbar_generate(pl))
        print(itembar_generate(pl, world))
        ch = getwch()
        if ch == "w" or ch == "W":
            world.player_shift(pl, "up")
        elif ch == "a" or ch == "A":
            world.player_shift(pl, "left")
        elif ch == "s" or ch == "S":
            world.player_shift(pl, "down")
        elif ch == "d" or ch == "D":
            world.player_shift(pl, "right")
        elif ch == "e" or ch == "E":
            if pl.item_available(world):
                pl.take(world)
            elif pl.nearest(pl.fov(direction, pl.Current_Gun.Range, world), world.Entity_list):
                attack(pl, world, pl.nearest(pl.fov(direction, pl.Current_Gun.Range, world), world.Entity_list,
                                             ["Hostile", "Tile"]))
        elif ch == "`":
            print("GoodBye!")
            flag = "ExitKey"
コード例 #38
0
    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
コード例 #39
0
ファイル: term.py プロジェクト: wendlers/mpfshell
 def getkey(self):
     while True:
         z = msvcrt.getwch()
         if z == unichr(13):
             return unichr(10)
         elif z is unichr(0) or z is unichr(0xe0):
             try:
                 code = msvcrt.getwch()
                 if z is unichr(0):
                     return self.fncodes[code]
                 else:
                     return self.navcodes[code]
             except KeyError:
                 pass
         else:
             return z
コード例 #40
0
ファイル: key_press.py プロジェクト: Mimino666/tc-marathoner
def _windows_key_press(wanted_key, stop_event, received_cb):
    '''Check for key presses from stdin in non-blocking way. Check until either
    `wanted_key` was pressed or `stop_event` has been set.
    If we detect `wanted_key` before `stop_event` is set, call `received_cb`
    callback and return.

    @param wanted_key: key to be pressed (in our case "q")
    @type wanted_key: one-letter str

    @param stop_event: indicate to stop reading and return
    @type stop_event: threading.Event

    @param received_cb: called when `wanted_key` was read
    @type received_cb: empty-argument callable
    '''
    import msvcrt
    import sys
    import time

    # skip if input is received from file or pipe redirection
    if not sys.stdin.isatty():
        return

    wanted_key = wanted_key.lower()
    while not stop_event.is_set():
        if msvcrt.kbhit():
            c = msvcrt.getwch()
            if c.lower() == wanted_key:
                received_cb()
                break
        else:
            time.sleep(0.5)
コード例 #41
0
def listen_for_keypress():
    global current_line
    global allow_keypress
    ignore_next = False
    while True:
        c = msvcrt.getwch()
        if not allow_keypress:
            continue
        if ignore_next:
            ignore_next = False
            continue
        current_line_lock.acquire()
        if ord(c) >= 32 and ord(c) <= 126:
            current_line += c
            need_redraw.set()
        elif ord(c) in (0, 224):
            ignore_next = True
        elif ord(c) in (8, 127):
            if (len(current_line) > 0):
                current_line = current_line[:-1]
                need_redraw.set()
        elif ord(c) in (13, ):
            line_queue.put(current_line)
            current_line = ""
            need_redraw.set()
        elif ord(c) in (3, ):
            exit()
        current_line_lock.release()
コード例 #42
0
def main():

    my_port = serial.Serial(port='COM1',
                            baudrate=BR,
                            bytesize=serial.EIGHTBITS,
                            parity=serial.PARITY_NONE,
                            stopbits=serial.STOPBITS_ONE,
                            xonxoff=0,
                            rtscts=0,
                            timeout=0)

    print("Port open is " + str(my_port.isOpen()))

    while True:
        try:
            char = msvcrt.getch()
        except:
            char = msvcrt.getwch()  # second call returns the actual key code
            continue

        print("Char is " + char)
        if (char == 'q'):
            break
        else:
            my_port.write(char)

        print("Sent command")

    print("Terminating program")
    my_port.close()
コード例 #43
0
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
コード例 #44
0
    def getch(self):
        ''' Returns a keyboard character after kbhit() has been called.
            Should not be called in the same program as getarrow().
        '''

        s = ''

        if os.name == 'nt':
            c = msvcrt.getwch()
            if c == '\x00' or c == '\xe0':  #special char
                c += msvcrt.getwch()
            return c
        else:
            return sys.stdin.buffer.read1(5).decode(
                "utf-8"
            )  # This works as long as only one char has been inputed.
コード例 #45
0
 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)
コード例 #46
0
 def mContinuar(self):
     print("")
     print("")
     print("Presiones 'C' para volver al menú del sistema.")
     key = None
     while key != 'C':  #Hasta que no se presione 'C' no permite la entrada de datos
         key = msvcrt.getwch()  #como un HANDLE de .Net
コード例 #47
0
ファイル: ui.py プロジェクト: 47-/Cyprium
 def _getch_win(cl, echo=False):
     import msvcrt
     import time
     while not msvcrt.kbhit():
         time.sleep(0.1)
     if echo:
         return msvcrt.getwche()
     return msvcrt.getwch()
コード例 #48
0
ファイル: term_winconsole.py プロジェクト: jtruscott/pytality
def raw_getkey():
    key = msvcrt.getwch()
    log.debug("key: %r", key)
    nkey = ord(key)

    if nkey in (0, 224):
        key2 = msvcrt.getwch()
        nkey2 = ord(key2)
        log.debug("key2: %r nkey2: %r", key2, nkey2)
        if nkey2 in key_map:
            return key_map[nkey2]
        return "key%s" % key

    if key in ("\r", "\n"):
        key = "enter"

    return key
コード例 #49
0
ファイル: modify.py プロジェクト: Kristof95/GoodLuckHaveFun
def donor_data_modifier():
    lista=[]
    found=0
    os.system('cls')
    change_according_ID=input("What ID you search for: ").lower()
    read_line=open("Data/donor.csv", "r+")
    read_the_list=csv.reader(read_line,delimiter=',',quotechar='"')
    for row in read_the_list:
        if row[7]==change_according_ID:
            found+=1
            lista=row
            print('-'*40)
            name=row[0].split(" ")
            if len(name)==2:
                print("\t "+name[1]+ ", "+ name[0])
            elif len(name)==3:
                print("\t "+name[2]+", "+name[1]+", "+name[0])
            print("\t "+str(row[1])+"kg")
            print("\t "+row[2][0:4]+"."+row[2][5:7]+"."+row[2][8:10]+"  -  "+str(row[3])+" years old")
            print("\t "+row[9])
            print("\t "+row[10])
            print("\t "+"ID: "+row[7])
            print('-'*40)
            print('\n')
    read_line.close()
    if found==0:
        print("This ID not found!")
        msvcrt.getwch()
    else:
        delete_from_csv = open("Data/donor.csv", "r+")
        read_csv_line=delete_from_csv.readlines()
        delete_from_csv.seek(0)
        for i in read_csv_line:
            splitted=i.split(',')
            if change_according_ID!=splitted[7]:
                delete_from_csv.write(i)
        delete_from_csv.truncate()
        delete_from_csv.close()
        write_rows=open("Data/donor.csv", 'a', newline='\n')
        writter=csv.writer(write_rows)
        lista=donor_data_manager(lista)
        writter.writerow(lista)
        write_rows.close()
        msvcrt.getwch()
    main.creat_menu()
コード例 #50
0
ファイル: piano.py プロジェクト: ikkebr/playerpiano
def eat_key():
    """consume a key.  Exit on ^C"""
    if 'tty' in globals():
        c = sys.stdin.read(1)
    else:
        c = msvcrt.getwch()
    if c == '\x03': # ^C
        raise SystemExit(1)
    return c
コード例 #51
0
ファイル: ui.py プロジェクト: gaoyunzhi/gchat
 def __arrow_pressed(self):
     arrow_key = ord(msvcrt.getwch())
     key = None
     if arrow_key == UP_KEY:
         key = UP
     elif arrow_key == DOWN_KEY:
         key = DOWN
     if key != None:
         self.__set_receiver(key)
コード例 #52
0
ファイル: console.py プロジェクト: Boblepointu/cuwo
 def get_input(self):
     while msvcrt.kbhit():
         c = msvcrt.getwch()
         if c == u'\r':  # new line
             c = u'\n'
             stdout.write(c)
             self.input += c
             self.protocol.dataReceived(self.input)
             self.input = ''
         elif c in (u'\xE0', u'\x00'):
             # ignore special characters
             msvcrt.getwch()
         elif c == u'\x08':  # delete
             self.input = self.input[:-1]
             stdout.write('\x08 \x08')
         else:
             self.input += c
             stdout.write(c)
コード例 #53
0
ファイル: search.py プロジェクト: Kristof95/GoodLuckHaveFun
def search_donor():
    print("You want to search in Donors")
    searching_string=input("What are you looking for?")
    hit=0
    counter=0
    row_number=0
    hits=[]
    global size
    rows=size[1]
    with open(os.path.join(os.path.dirname(sys.argv[0]), "Data\donor.csv"), newline='') as csvfile:
        search_file = csv.reader(csvfile, delimiter=',',quotechar='"')
        for row in search_file:
            row_number+=1
            found=0
            for coll in row:
                if searching_string in coll:
                    found=1
                    hit=1
            if found ==1:
                if row_number==1:
                    hit=0
                else:
                    counter+=1
                    hits.append('-'*40)
                    name=row[0].split(" ")
                    if len(name)==2:
                        hits.append(str(counter)+"."+"\t "+name[1]+ ", "+ name[0])
                    elif len(name)==3:
                        hits.append(str(counter)+"."+"\t "+name[2]+", "+name[1]+", "+name[0])
                    hits.append("\t "+row[1]+"kg")
                    hits.append("\t "+row[2][0:4]+"."+row[2][5:7]+"."+row[2][8:10]+"  -  "+row[3]+" years old")
                    hits.append("\t "+row[9])
                    hits.append("\t "+row[10])
                    hits.append("\t "+"ID: "+row[7])
        if hit==0:
            print("There is no things like this!")
        elif hit!=0:
            os.system('cls')
            page_row=(rows-1)//7
            page=0
            length=len(hits)
            while page<length:
                os.system('cls')
                for i in range(0+page,page_row*7+page):
                    if i<length:
                        print(hits[i])
                    else:
                        break
                key=msvcrt.getwch()
                if key=='s':
                    page+=page_row*7
                if key=='w':
                    page-=page_row*7
                    if page<0:
                        page=0

    end_of_search()
コード例 #54
0
	def run(self):
		self.active = True

		while self.active:
			key = msvcrt.getwch()

			# Get a direction
			if key == "\xe0":
				key = msvcrt.getwch()

				if key in Direction.DIRECTIONS:
					self.direction = key
			# Flip the pause toggle
			elif key == " ":
				self.paused = not self.paused
			# Flip the quit toggle
			elif key == "q":
				self.quit = True
コード例 #55
0
ファイル: ui.py プロジェクト: gaoyunzhi/gchat
 def __change_receiver(self):
     # get control detail, which of F1-F10
     control_key = ord(msvcrt.getwch()) - 58
     if 0 < control_key < 9: 
         self.bufferMessage.set_receiver(self.model.get_email_from_number(control_key)) 
     elif control_key == 9:
         self.receiver_editing_mode = True
         self.bufferMessage.empty_receiver()
     elif control_key == 10:
         self.model.show_help_message()
コード例 #56
0
ファイル: exitcontrol.py プロジェクト: takluyver/latus
 def run(self):
     this_char = ''
     while this_char != self.exit_criteria:
         # print("waiting for", self.exit_criteria)
         msvcrt.kbhit() # waits for the keyboard hit
         this_char = msvcrt.getwch() # eats the character just hit
         if this_char == self.exit_criteria:
             self.trigger_all_events()
         else:
             print("waiting for '%s' : got '%s'" % (str(self.exit_criteria), this_char))
コード例 #57
0
ファイル: Donor.py プロジェクト: Kristof95/GoodLuckHaveFun
 def bad_input(self):
     print("Choose from above!")
     number=msvcrt.getwch()
     if number=="1":
         self.get_unique_id()
     elif number=="2":
         donor_main()
     elif number=="3":
         main.creat_menu()
     else:
         self.bad_input()
コード例 #58
0
ファイル: search.py プロジェクト: Kristof95/GoodLuckHaveFun
def end_of_search():
    print('1. New search')
    print('2. Back')
    get=msvcrt.getwch()
    if get=='1':
        main.search_menu()
    elif get=='2':
        main.creat_menu()
    else:
        print('Choose one!')
        end_of_search()
コード例 #59
0
ファイル: dGame.py プロジェクト: CunningDJ/DungeonGame
def playerInput(drawThread):

    
    while True:
        key = ord(getwch())
        if key == 27: #ESC
            killQ.put(endProgram)
            break
            
        if key == 224: # Special keys (arrows, f keys, ins, del, etc.)
            key = ord(getwch())
            if key == 80: #Down arrow
                players[0]['y'] -= 1
            elif key == 72: #Up arrow
                players[0]['y'] += 1
            elif key == 77: #right arrow
                players[0]['x'] += 1
            elif key == 75: #left arrow
                players[0]['x'] -= 1
        
        if len(players) >= 2:
            #P2 CONTROLS
            if key == 119: # W (p2 up)
                players[1]['y'] += 1
            elif key == 115: # S (p2 down)
                players[1]['y'] -= 1
            elif key == 100: # D (p2 right)
                players[1]['x'] += 1
            elif key == 97: # A (p2 left)
                players[1]['x'] -= 1
                
        if len(players) == 3:
            # P3 CONTROLS
            if key == 105: # I (p3 up)
                players[2]['y'] += 1
            elif key == 107: # K (p3 down)
                players[2]['y'] -= 1
            elif key == 108: # L (p3 right)
                players[2]['x'] += 1
            elif key == 106: # J (p3 left)
                players[2]['x'] -= 1