[python] 파이썬이 키를 누를 때까지 어떻게 기다리나요?

사용자가 키를 누를 때까지 스크립트가 대기하기를 원합니다.

어떻게합니까?



답변

에서 파이썬 3 를 사용 input():

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

에서 파이썬이 사용 raw_input():

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

사용자가 Enter 키를 누를 때까지만 기다립니다.

msvcrt 를 사용하고 싶을 수도 있습니다 ((Windows / DOS에만 해당) msvcrt 모듈을 사용하면 Microsoft Visual C / C ++ 런타임 라이브러리 (MSVCRT)의 ​​여러 기능에 액세스 할 수 있습니다).

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

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

추가 정보:

파이썬 3 raw_input()에는 존재하지 않습니다

파이썬에서 2 input(prompt)에 해당eval(raw_input(prompt))


답변

Python 2에서이를 수행하는 한 가지 방법은 다음을 사용하는 것입니다 raw_input().

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

python3에서 그것은 단지 input()


답변

내 리눅스 상자에서 다음 코드를 사용합니다. 이것은 다른 곳에서 보았던 코드와 비슷하지만 (예를 들어 오래된 파이썬 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)


답변

시스템 명령에 따라 괜찮다면 다음을 사용할 수 있습니다.

리눅스 :

import os
os.system('read -sn 1 -p "Press any key to continue..."')
print

윈도우 :

import os
os.system("pause")


답변

간단히 사용

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

구문 분석하는 동안 SyntaxError : EOF가 예상됩니다.

간단한 수정 사용 :

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


답변

파이썬 매뉴얼 은 다음을 제공합니다.

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)

유스 케이스에 넣을 수 있습니다.


답변

크로스 플랫폼, 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 항목을 제공했기 때문에 제거 IOError했지만 필요하지 않았습니다. 차단하기를 원하기 때문에이 코드를 사용하고 있습니다. 😉

추가:

나는 이것을 PyPI의 패키지에서 console 이라는 다른 많은 것들과 함께 구현했습니다 .

>>> from console.utils import wait_key

>>> wait_key()
'h'