python接收用户输入的任意一个数_在python中的任意时间捕获用户输入

Is there a way to send an interrupt to a python module when the user inputs something in the console? For example, if I'm running an infinite while loop, i can surround it with a try/except for KeyboardInterrupt and then do what I need to do in the except block.

Is there a way to duplicate this functionality with any arbitrary input? Either a control sequence or a standard character?

Edit: Sorry, this is on linux

解决方案

Dependent on the operating system and the libraries available, there are different ways of achieving that. This answer provides a few of them.

Here is the Linux/OS X part copied from there, with in infinite loop terminated using the escape character. For the Windows solution you can check the answer itself.

import sys

import select

import tty

import termios

from curses import ascii

def isData():

return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)

try:

tty.setcbreak(sys.stdin.fileno())

i = 0

while 1:

print i

i += 1

if isData():

c = sys.stdin.read(1)

if c == chr(ascii.ESC):

break

finally:

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

Edit: Changed the character detection to use characters as defined by curses.ascii, thanks to Daenyth's unhappiness with magic values which I share.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值