703

ユーザーがいずれかのキーを押すまで Python スクリプトを待機させたい。
それ、どうやったら出来るの?

4

13 に答える 13

714

Python 3では次を使用しますinput()

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

Python 2では次を使用します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()

これは、キーが押されるのを待つ必要があります。

追加情報:

Python 3raw_input()には存在しません

Python 2 ではinput(prompt)eval(raw_input(prompt))

于 2009-07-16T01:48:20.217 に答える
323

Python 2 でこれを行う 1 つの方法は、次を使用することraw_input()です。

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

python3ではそれはただですinput()

于 2009-06-11T20:11:59.177 に答える
60

私の Linux ボックスでは、次のコードを使用します。これは、私が他の場所で見たコード (たとえば、古い python 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)
于 2011-07-06T15:58:39.867 に答える
40

システムコマンドに応じて問題がなければ、次を使用できます。

Linux および Mac OS X:

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

ウィンドウズ:

import os
os.system("pause")
于 2013-06-05T06:36:48.553 に答える
38

単に使用する

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

Python 2 を使用すると、次のエラーが発生します。

SyntaxError: 解析中に EOF が予想されます。

コードが Python 2 と Python 3 の両方で動作するように簡単に修正するには、次を使用します。

try:
    input("Press enter to continue")
except SyntaxError:
    pass
于 2014-03-03T16:06:30.717 に答える
23

クロスプラットフォーム、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 のものはIOErrors を与えていたので削除しましたが、私はそれを必要としませんでした。ブロックしたいので、特にこのコードを使用しています。;)

補遺:

これを PyPI のパッケージに実装し、consoleと呼ばれる他の多くの機能を追加しました。

>>> from console.utils import wait_key

>>> wait_key()
'h'
于 2016-01-22T22:10:39.570 に答える
19

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)

ユースケースに組み込むことができます。

于 2011-02-15T13:09:08.223 に答える
14

プラットフォームに依存しない方法はわかりませんが、Windows では msvcrt モジュールを使用すると、その getch 関数を使用できます。

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

mscvcrt には、待機せずにキーが押されたかどうかを確認するためのノンブロッキング kbhit() 関数も含まれています (対応する curses 関数があるかどうかはわかりません)。UNIX には curses パッケージがありますが、すべての画面出力に使用せずに使用できるかどうかはわかりません。このコードは UNIX で動作します。

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

curses.getch() は、押されたキーの序数を返すことに注意してください。これにより、キャストする必要があったのと同じ出力が得られます。

于 2011-05-17T21:42:22.250 に答える
1

os.system は、読み取り用の s および n オプションを認識しない sh を常に呼び出すようです。ただし、読み取りコマンドは bash に渡すことができます。

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")
于 2013-12-18T06:39:33.047 に答える
-2

彼らが正確なキー (「b」など) を押したかどうかを確認したい場合は、次のようにします。

while True:
    choice = raw_input("> ")

    if choice == 'b' :
        print "You win"
        input("yay")
        break
于 2012-06-19T03:42:22.907 に答える