我正在尝试创建一个递增并打印值的循环。当它运行时,我想按下一个键(例如空格或shift)并让它打印出该键被按下。下面是我想要的示例代码。
def space():
print 'You pressed space'
def shift():
print 'You pressed shift'
x = 0
while True:
print(x)
#if space is pressed
space()
#if shift is pressed
shift()
x = x + 1;
time.sleep(1)
编辑:这是一个示例输出
0
1
2
You pressed shift
3
4
5
You pressed space
6
7
.
.
.
最佳答案
我可以在这里帮助您修改答案表:
https://stackoverflow.com/questions/11918999/key-listeners-in-python
只为空格输入:
import contextlib
import sys
import termios
import time
@contextlib.contextmanager
def raw_mode(file):
old_attrs = termios.tcgetattr(file.fileno())
new_attrs = old_attrs[:]
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
try:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
yield
finally:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)
def space(ch):
if ord(ch) == 32:
print 'You pressed space'
def enter(ch):
if ord(ch) == 10:
print 'You pressed enter'
def main():
print 'exit with ^C or ^D'
with raw_mode(sys.stdin):
try:
x = 0
while True:
print(x)
ch = sys.stdin.read(1)
space(ch)
enter(ch)
x = x + 1;
time.sleep(1)
except (KeyboardInterrupt, EOFError):
pass
if __name__ == '__main__':
main()
关于python - 在 Linux 上使用特定键中断 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39085169/