当用户在控制台中输入内容时,有没有办法向python模块发送中断? 例如,如果我正在运行无限循环,我可以使用try /除了KeyboardInterrupt来包围它,然后在except块中执行我需要做的操作。
有没有办法用任意输入复制此功能? 控制序列还是标准字符?
编辑:对不起,这是在Linux上
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
最满意答案
取决于操作系统和可用的库,有不同的方法来实现这一点。 这个答案提供了其中的一些。
这是从那里复制的Linux / OS X部分,使用转义字符终止无限循环。 对于Windows解决方案,您可以检查答案本身。
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)编辑 :更改字符检测以使用curses.ascii定义的curses.ascii ,这要归功于Daenyth对我所分享的魔法值的不满。
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.
更多推荐
发布评论