python按哪个键运行代码_如何让python等待按下的键

在我的Linux机器上,我使用以下代码。这类似于我在其他地方看到的代码(例如在旧的python常见问题解答中),但是代码在紧密的循环中旋转,而这个代码没有,并且有很多奇怪的角落情况,代码没有考虑到这一点代码呢。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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值