[英]Python: How to get input from console while an infinite loop is running?
我正在尝试编写一个简单的 Python IRC 客户端。 到目前为止,我可以读取数据,如果自动化,我可以将数据发送回客户端。 我在一段while True
获取数据while True
,这意味着我无法在读取数据的同时输入文本。 如何在控制台中输入文本,只有在我按下 Enter 时才会发送,同时运行无限循环?
基本代码结构:
while True:
read data
#here is where I want to write data only if it contains '/r' in it
另一种方法涉及线程。
import threading
# define a thread which takes input
class InputThread(threading.Thread):
def __init__(self):
super(InputThread, self).__init__()
self.daemon = True
self.last_user_input = None
def run(self):
while True:
self.last_user_input = input('input something: ')
# do something based on the user input here
# alternatively, let main do something with
# self.last_user_input
# main
it = InputThread()
it.start()
while True:
# do something
# do something with it.last_user_input if you feel like it
您需要的是某种事件循环。
在 Python 中,你有几个选项可以做到这一点,选择你喜欢的一个:
等等,为此有数百个框架,您还可以使用任何 GUI 框架(如 tkinter 或 PyQt)来获取主事件循环。
正如上面的评论所说,你可以使用线程和一些队列来处理这个,或者一个基于事件的循环,或者协程或一堆其他架构。 根据您的目标平台,一个或另一个可能是最好的。 例如在 Windows 上,控制台 API 与 unix ptys 完全不同。 特别是如果您以后需要诸如颜色输出之类的东西,您可能想提出更具体的问题。
您可以使用异步库(请参阅 schlenk 的答案)或使用https://docs.python.org/2/library/select.html
该模块提供对大多数操作系统中可用的 select() 和 poll() 函数的访问,Linux 2.5+ 上可用的 epoll() 和大多数 BSD 上可用的 kqueue()。 请注意,在 Windows 上,它仅适用于套接字; 在其他操作系统上,它也适用于其他文件类型(特别是在 Unix 上,它适用于管道)。 它不能用于常规文件以确定自上次读取以来文件是否已增长。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.