Python:如何在运行无限循环时从控制台获取输入? [英] Python: How to get input from console while an infinite loop is running?
本文介绍了Python:如何在运行无限循环时从控制台获取输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个简单的Python IRC客户端.到目前为止,我可以读取数据,并且可以自动将数据发送回客户端.我正在while True
中获取数据,这意味着在读取数据的同时无法输入文本.如何在控制台中输入仅在按Enter键时发送的文本,同时运行无限循环?
I'm trying to write a simple Python IRC client. So far I can read data, and I can send data back to the client if it automated. I'm getting the data in a while True
, which means that I cannot enter text while at the same time reading data. How can I enter text in the console, that only gets sent when I press enter, while at the same time running an infinite loop?
基本代码结构:
while True:
read data
#here is where I want to write data only if it contains '/r' in it
推荐答案
另一种实现方法涉及线程.
Another way to do it involves threads.
import threading
# define a thread which takes input
class InputThread(threading.Thread):
def run(self):
self.daemon = True
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:如何在运行无限循环时从控制台获取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文