在python中的任意时间捕获用户输入(Capturing user input at arbitrary times in python)

编程入门 行业动态 更新时间:2024-10-14 08:26:04
在python中的任意时间捕获用户输入(Capturing user input at arbitrary times in python)

当用户在控制台中输入内容时,有没有办法向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.

更多推荐

本文发布于:2023-04-29 02:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   用户   Capturing   python   arbitrary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!