我正在命令窗口(Windows 7、Python 3.1)中运行一个进程,我希望用户通过按 Esc 键中止该进程。然而,按 Esc 似乎没有执行任何操作,循环永远不会中断。我还尝试从 IDE (Wing) 中运行脚本,但同样,循环无法中断。
以下是我的概念验证测试的精简版本...
import msvcrt
import time
aborted = False
for time_remaining in range(10,0,-1):
# First of all, check if ESCape was pressed
if msvcrt.kbhit() and msvcrt.getch()==chr(27):
aborted = True
break
print(str(time_remaining)) # so I can see loop is working
time.sleep(1) # delay for 1 second
#endfor timing loop
if aborted:
print("Program was aborted")
else:
print("Program was not aborted")
time.sleep(5) # to see result in command window before it disappears!
如果有人能告诉我哪里可能出错,我将不胜感激。
Python 3 字符串是 unicode,因此必须编码为字节以进行比较。试试这个测试:
if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
aborted = True
break
或者这个测试:
if msvcrt.kbhit() and msvcrt.getch().decode() == chr(27):
aborted = True
break
或者这个测试:
if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
aborted = True
break
你真的应该脱得更多,就像下面这个:
>>> import msvcrt
>>> ch = msvcrt.getch()
# Press esc
>>> ch
b'\x1b'
>>> chr(27)
'\x1b'
>>> ch == chr(27)
False
所以问题是:
msvcrt.getch()
返回bytes
,chr(27)
返回string
。在 Python 3 中,它们是两种不同的类型,因此“==
”部分永远不会起作用,并且 if
语句将始终被评估为 False
。
解决方案对您来说应该是显而易见的。
有关字符串与字节的更多,来自《深入 Python 3》一书。
交互式控制台对于调试非常有用,请尝试更多地使用它:)
你不需要编码、解码、字符、排序……
if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':
或者如果您想在代码中的某处看到“27”:
if msvcrt.kbhit() and msvcrt.getch()[0] == 27:
Python 2/3 兼容代码:
import time, sys
ESC = '\x1b'
PY3K = sys.version_info >= (3,)
if PY3K:
from msvcrt import kbhit, getwch as _getch
else:
from msvcrt import kbhit, getch as _getch
while not kbhit() or _getch() != ESC:
print(time.asctime())
time.sleep(1)
pager
模块,里面有更多内容。
您是否尝试过使用不同的键来测试它是否不仅仅是那个键?
您是否也尝试过此处的示例来看看它们是否有效?
将 cv2 导入为 cv
a = cv.waitkey(0)
if (a == 27 或 ord('esc') == 27): 中止=真 打破