我如何让我的python脚本等待,直到用户按下任何键?
当前回答
如果你可以依赖于系统命令,你可以使用:
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一起工作。
其他回答
如果你可以依赖于系统命令,你可以使用:
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一起工作。
在Python 3中,使用input():
input("Press Enter to continue...")
在Python 2中,使用raw_input():
raw_input("Press Enter to continue...")
跨平台,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.getwch()
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/非阻塞的东西,因为它给IOErrors,我不需要它。我使用这段代码是因为我想让它阻塞。;)
附录:
我在PyPI上的一个包中实现了这个功能,还有很多其他叫做console的东西:
>>> from console.utils import wait_key
>>> wait_key()
'h'
如果您想等待输入(这样用户敲击键盘不会导致一些意想不到的事情发生),请使用
sys.stdin.readline()
简单的使用
input("Press Enter to continue...")
将在使用Python 2时导致以下错误:
SyntaxError:解析时预期的EOF。
让代码在Python 2和Python 3上都能工作的简单修复是使用:
try:
input("Press enter to continue")
except SyntaxError:
pass