如果用户按下 while "q",如何立即中断 while 循环



我想在每个循环中从用户那里获取一个整数并将它们相加。如果用户按下q键,我希望循环立即结束,而无需按回车键并打印总计。

!pip install keyboard
import keyboard
total = 0
while True:
if keyboard.is_pressed('q'):
break
x = int(input("Enter a number: "))
total += x
print(total)

我试过这个,但我得到了一个断言错误,详细说明如下:

AssertionError                            
Traceback (most recent call last)
<ipython-input-14-e1e12bbc6dc8> in <module>()
3 total = 0
4 while True:
----> 5   if keyboard.is_pressed('q'):
6     break
7   x = int(input("Enter a number "))
5 frames
/usr/local/lib/python3.7/dist-packages/keyboard/_nixcommon.py in aggregate_devices(type_name)
166 
167     # If no keyboards were found we can only use the fake device to send keys.
--> 168     assert fake_device
169     return fake_device
170 
AssertionError: 

可以用另一种方式完成:

total = 0
while True:
x = input("Bir sayı giriniz: ")
if x == "q":
break
total += int(x)
print(total)
total = 0
running =True
while running:
x = input("Bir sayı giriniz: ")
if x == "q" or x == "Q":
running = False
else:
total += int(x)
print(total)

您可以执行此操作,而无需用户按回车键:

import sys
import termios
import tty
def getchr():
r"""
Get a single key from the terminal without printing it.
Certain special keys return several "characters", all starting with the
escape character 'x1b'. You could react to that by reading two more
characters, but the actual escape key will only make this return a single
escape character, and since it's blocking, that wouldn't be a good solution
either.
"""
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
termios.tcsetattr(fd, termios.TCSADRAIN, old)
if ord(ch) == 3:  # ^C
raise KeyboardInterrupt
return ch

def input_int_except_q(msg):
print(msg, end="", flush=True)
chars = []
while True:
char = getchr()
if char == "q":
return None
elif char == "r":
print()
break
print(char, end="", flush=True)
chars.append(char)
return int("".join(chars))
total = 0
while True:
x = input_int_except_q("Bir sayı giriniz: ")
if not x:
break
total += x
print(total)

getchr将为您提供用户输入的单个字符,而不显示它。input_int_except_q使用它来获取用户输入的整数,或者如果他们按QNone。用户输入的每个字符都会打印回来以模拟"正常"行读取,并且当用户按Ctrl+C时,会像往常一样特别注意引发KeyboardInterrupt

对于 Python3 tty,您可以使用click

pip3 install click

在终端中,然后:

from click import getchar
data = ''
while True:
char = getchar()

if char == 'q':
break
data += char

相关内容

最新更新