Python:如何在无限循环运行时从控制台获取输入?
我正在尝试写一个简单的Python IRC客户端。到目前为止,我可以读取数据,也可以在自动化的情况下将数据发送回客户端。我是在一个while True
循环中获取数据,这意味着我不能在读取数据的同时输入文本。请问我该如何在控制台中输入文本,只有在我按下回车键时才发送,同时又能持续运行这个无限循环呢?
基本的代码结构:
while True:
read data
#here is where I want to write data only if it contains '/r' in it
3 个回答
0
你可以使用一个异步库(可以看看schlenk的回答),或者使用这个链接。
这个模块可以让你使用大多数操作系统中提供的select()和poll()函数,Linux 2.5及以上版本可以用epoll(),而大多数BSD系统可以用kqueue()。需要注意的是,在Windows系统上,这些函数只能用于套接字;而在其他操作系统上,它们也可以用于其他类型的文件(特别是在Unix系统上,可以用于管道)。不过,它不能用来检查普通文件自上次读取以来是否有增加。
3
你需要的是某种事件循环。
在Python中,有几种选择可以实现这一点,随便选一个你喜欢的:
- Twisted https://twistedmatrix.com/trac/
- Asyncio https://docs.python.org/3/library/asyncio.html
- gevent http://www.gevent.org/
还有很多其他的选择,市面上有成百上千的框架。你也可以使用像tkinter或PyQt这样的图形用户界面框架来获得一个主事件循环。
正如上面的评论所说,你可以使用线程和一些队列来处理这个问题,或者使用基于事件的循环,或者协程,甚至其他很多架构。根据你要支持的平台,某种方式可能更合适。例如,在Windows上,控制台的API和Unix的伪终端是完全不同的。如果你以后需要像彩色输出这样的功能,可能还需要问一些更具体的问题。
5
另一种方法是使用线程。
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