ユーザーが何かキーを押すまで待機するスクリプトを作りたい。
どうすればいいんだろう?
Python 3では、raw_input()
は存在しません。だから、ただ使うだけでいい。
input("Press Enter to continue...")
Python 2では、input(prompt)
は eval(raw_input(prompt))
と等価なので、raw_input()
を使用する必要があります。
raw_input("Press Enter to continue...")
しかし、これはユーザーがエンターキーを押すのを待つだけなので、msvcrt ((Windows/DOSのみ) msvcrtモジュールは、Microsoft Visual C/C++ Runtime Library (MSVCRT) の多くの関数へのアクセスを提供します) を使用したい場合があります。
import msvcrt as m
def wait():
m.getch()
これは、キーが押されるのを待つ必要があります。
Python 2でこれを行う方法の一つは、raw_input()
を使用することです。
raw_input("Press Enter to continue...")
python3ではinput()
だけです。
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)
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には、非ブロッキング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
fctl /非ブロッキングのものは IOError
sを提供していて、必要なかったので削除しました。 このコードをブロックしたいので、このコードを具体的に使用しています。 ;)。
私はpythonに慣れていないので、ここで行われた最も簡単な提案を再現するには愚かすぎるとはすでに考えていました。 結局のところ、知っておくべき落とし穴があります。
IDLEからpythonスクリプトが実行されると、一部のIOコマンドは完全に異なる動作をするように見えます(実際には端末ウィンドウがないため)。
例えば。 msvcrt.getchは非ブロック化であり、常に$ ffを返します。 これはすでにずっと前に報告されています(例:. https://bugs.python.org/issue9290)-固定としてマークされていますが、どういうわけか問題は現在のバージョンのpython / IDLEに残っているようです。
したがって、上記の投稿されたコードのいずれかが機能しない場合は、スクリプトを手動で実行してみてください。 IDLEからではありません。
os.systemは常にshを呼び出すようですが、shとnのオプションが読み取られないためです。 ただし、readコマンドはbash :に渡すことができます。
os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")