itsource

키를 누르려면 어떻게 기다려야 하나요?

mycopycode 2022. 11. 4. 21:35
반응형

키를 누르려면 어떻게 기다려야 하나요?

사용자가 임의의 키를 누를 때까지 python 스크립트를 대기시키려면 어떻게 해야 합니까?

Python 3에서는 다음을 사용합니다.input():

input("Press Enter to continue...")

Python 2에서는 다음을 사용합니다.raw_input():

raw_input("Press Enter to continue...")

단, 사용자가 Enter 키를 누를 때까지 대기할 뿐입니다.


Windows/DOS 에서는, 을 사용하고 싶은 경우가 있습니다.msvcrt.그msvcrt모듈을 사용하면 Microsoft Visual C/C++ Runtime Library(MSVCRT)의 다양한 기능에 액세스할 수 있습니다.

import msvcrt as m
def wait():
    m.getch()

키를 누를 때까지 기다려야 합니다.


주의:

Python 3에서는raw_input()는 존재하지 않습니다.
Python 2에서는input(prompt)와 동등하다eval(raw_input(prompt)).

Python 3에서는 다음을 사용합니다.input():

input("Press Enter to continue...")

Python 2에서는 다음을 사용합니다.raw_input():

raw_input("Press Enter to continue...")

Linux 박스에서는 다음 코드를 사용합니다.이것은 내가 다른 곳에서 본 코드와 유사하지만(예를 들어 오래된 파이썬 FAQ에서), 이 코드는 이 코드가 설명하지 않는 좁은 루프에서 회전하고 이 코드는 설명하지 않는 이상한 코너 케이스가 많이 있습니다.

def read_single_keypress():
    """Waits for a single keypress on stdin.

    This is a silly function to call if you need to do it a lot because it has
    to store stdin's current setup, setup stdin for reading single keystrokes
    then read the single keystroke then revert stdin back after reading the
    keystroke.

    Returns a tuple of characters of the key that was pressed - on Linux, 
    pressing keys like up arrow results in a sequence of characters. Returns 
    ('\x03',) on KeyboardInterrupt which can happen when a signal gets
    handled.

    """
    import termios, fcntl, sys, os
    fd = sys.stdin.fileno()
    # save old state
    flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
    attrs_save = termios.tcgetattr(fd)
    # make raw - the way to do this comes from the termios(3) man page.
    attrs = list(attrs_save) # copy the stored version to update
    # iflag
    attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
                  | termios.ISTRIP | termios.INLCR | termios. IGNCR
                  | termios.ICRNL | termios.IXON )
    # oflag
    attrs[1] &= ~termios.OPOST
    # cflag
    attrs[2] &= ~(termios.CSIZE | termios. PARENB)
    attrs[2] |= termios.CS8
    # lflag
    attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
                  | termios.ISIG | termios.IEXTEN)
    termios.tcsetattr(fd, termios.TCSANOW, attrs)
    # turn off non-blocking
    fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
    # read a single keystroke
    ret = []
    try:
        ret.append(sys.stdin.read(1)) # returns a single character
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK)
        c = sys.stdin.read(1) # returns a single character
        while len(c) > 0:
            ret.append(c)
            c = sys.stdin.read(1)
    except KeyboardInterrupt:
        ret.append('\x03')
    finally:
        # restore old state
        termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
    return tuple(ret)

시스템 명령에 따라 문제가 없는 경우 다음을 사용할 수 있습니다.

from __future__ import print_function
import os
import platform

if platform.system() == "Windows":
    os.system("pause")
else:
    os.system("/bin/bash -c 'read -s -n 1 -p \"Press any key to continue...\"'")
    print()

Windows, Linux 및 Mac OS X에서 Python 2 및 3과 함께 작동하는 것으로 확인되었습니다.

간단하게 사용

input("Press Enter to continue...")

Python 2를 사용하면 다음 오류가 발생합니다.

SyntaxError: 구문 분석 중 EOF가 필요합니다.

Python 2와 Python 3에서 사용할 수 있는 간단한 수정 방법은 다음과 같습니다.

try:
    input("Press enter to continue")
except SyntaxError:
    pass

크로스 플랫폼, Python 2/3 코드:

# import sys, os

def wait_key():
    ''' Wait for a key press on the console and return it. '''
    result = None
    if os.name == 'nt':
        import msvcrt
        result = msvcrt.getch()
    else:
        import termios
        fd = sys.stdin.fileno()

        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)

    return result

fctl/non-blocking을 제거했습니다. 왜냐하면 fctl/non-blocking은IOError그리고 나는 그것이 필요하지 않았다.이 코드를 사용하는 이유는 차단하기 위해서입니다.;)

부록:

PyPI 패키지에는 콘솔이라고 불리는 많은 다른 제품들이 포함되어 있습니다.

>>> from console.utils import wait_key

>>> wait_key()
'h'

python 설명서는 다음을 제공합니다.

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

활용 사례로 활용할 수 있습니다.

플랫폼에 의존하지 않는 방법은 모르겠지만 Windows에서 msvcrt 모듈을 사용하면 getch 기능을 사용할 수 있습니다.

import msvcrt
c = msvcrt.getch()
print 'you entered', c

mscvcrt에는 대기하지 않고 키를 눌렀는지 여부를 확인하기 위한 non-module kbhit() 함수도 포함되어 있습니다(대응하는 저주 함수가 있는지 확인).UNIX 에는 curses 패키지가 있습니다만, 모든 화면 출력에 대해 사용하지 않고 사용할 수 있을지는 확실하지 않습니다.이 코드는 UNIX 로 동작합니다.

import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()

저주에 주의해 주세요.getch()는 키를 눌렀을 때의 서수를 반환하여 키를 캐스팅할 때와 같은 출력을 얻을 수 있도록 합니다.

나는 비단뱀을 처음 접해 본 사람인데, 나는 이미 내가 너무 멍청해서 여기서 나온 가장 간단한 제안들을 재현할 수 없다고 생각하고 있었다.알고 보니 함정이 하나 있습니다.

IDLE에서 python-script가 실행되면 일부 IO 명령어는 완전히 다르게 동작합니다(실제로 터미널 창이 없습니다).

예를 들어 msvcrt.getch는 비블로킹이며 항상 $ff를 반환합니다.이것은 이미 오래 전에 보고되었습니다(예: https://bugs.python.org/issue9290 참조). 이 문제는 해결되었다고 표시되어 있습니다.어떻게든 현재 버전의 python/IDLE에서는 문제가 지속되고 있는 것 같습니다.

따라서 위에 게시된 코드 중 하나라도 제대로 작동하지 않으면 IDLE이 아닌 수동으로 스크립트를 실행해 보십시오.

입력을 기다리는 경우(사용자가 키보드를 두드려서 의도하지 않은 일이 발생하지 않도록 하기 위해)

sys.stdin.readline()

'키보드' 라이브러리를 사용할 수 있습니다...

https://github.com/boppreh/keyboard#api

import keyboard
keyboard.wait('space')
print('space was pressed, continuing...')

os.system은 항상 sh를 호출하는 것 같습니다.이 경우 s와 n의 읽기 옵션이 인식되지 않습니다.단, read 명령어는 bash에 전달할 수 있습니다.

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")

정확한 키(예: 'b')를 눌렀는지 확인하려면 다음을 수행합니다.

while True:
    choice = raw_input("> ")

    if choice == 'b' :
        print "You win"
        input("yay")
        break

언급URL : https://stackoverflow.com/questions/983354/how-do-i-wait-for-a-pressed-key

반응형