私は、押されたキーを待つためのpythonを作るにはどうすればよいです

StackOverflow https://stackoverflow.com/questions/983354

  •  13-09-2019
  •  | 
  •  

質問

私は、ユーザーが任意のキーを押すまで、私のスクリプトを待ちたい。

どのように私はそれを行うのですか?

役に立ちましたか?

解決

のPython 3では、何raw_input()は存在しません。だから、ちょうど使用します:

input("Press Enter to continue...")
raw_input()input(prompt)と同等であるとして

のPython 2では、あなたは、eval(raw_input(prompt))を使用する必要があります:

raw_input("Press Enter to continue...")
MSVCRTモジュールを使用すると、ビジュアル、マイクロソフトでは、多数の機能にアクセスすることができますユーザーは、のMSVCRTのを使用する場合がありますので、しかしEnterキーを押す((Windowsの/ DOSのみ)のための

このだけ待機C / C ++ランタイムライブラリ(MSVCRT)):

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

このキーを押して待つ必要があります。

他のヒント

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

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

のpython3ではそれだけでinput()です。

私のLinuxボックスで、私は次のコードを使用します。これは、コード、私が(例えば、古いPythonのよくある質問に)他の場所で見てきたに似ていますが、そのコードは、このコードにはないタイトなループ内で回転し、そのコードは、このために考慮していない奇妙なコーナーケースがたくさんありますコードはありません。

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)

あなたが使用できるコマンドシステムに依存してOKであれば、以下:

Linuxの場合:

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

のWindowsます:

os.system("pause")

単に使用して

input("Press Enter to continue...")
解析中に予想されるEOF

にSyntaxErrorが発生します。

簡単な修正の使用:

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

の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)

ご利用の場合にロールバックすることができます。

私はそれを行うためのプラットフォームに依存しない方法を知っていませんが、あなたはMSVCRTモジュールを使用する場合、Windowsの下で、あなたはそのgetchは機能を使用することができます:

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

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

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

そのcurses.getchに注意してください()それは私がそれをキャストしていた同じ出力を持たせるので、押されたキーの順序を返します。

クロスプラットフォーム、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

それはIOErrorsを与えていたので、私はFCTL /非ブロックのものを削除し、私はそれを必要としませんでした。私はそれをブロックしたいので、私は特にこのコードを使用しています。 ;)

あなたが入るのを待つしたい場合は(そう、キーボードをノックし、ユーザーが非意図が起こるために何かを引き起こすことはありません)。

を使用
sys.stdin.readline()

私のpythonに新しいですし、私はすでに私がここで行わ最も簡単な提案を再現するにはあまりにも愚かだ考えていました。 それは1つが知っておくべき落とし穴があります、判明します:

Pythonスクリプトは、IDLEから実行されると

、いくつかのIO-コマンドは、(実際には端末のウィンドウが存在しないように)完全に異なる振る舞いをするように見える。

例:。 msvcrt.getchは、非ブロッキングであり、常に$ FFを返します。 これは、すでに(例えば https://bugs.python.org/issue9290 のを参照してください)ずっと前に報告されています - 固定として、それがマークされていますと、何とか問題は、Python / IDLEの現在のバージョンに固執しているようだ。

上記掲載のコードのいずれかがあなたのために動作しないのであれば、手動でスクリプトを実行してみてください、との、NOT IDLEからの。

彼らは(のような「b」を言う)の正確なキーを押したかどうかを確認したい場合は、これを行います:

while True:
    choice = raw_input("> ")

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

os.systemは常に読み取りのためのS及びNのオプションを認識しない、SHを呼び出しているようです。しかし、リードコマンドは、bashのに渡すことができます:

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top