[英]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.