gpt4 book ai didi

Python:如何在无限循环运行时从控制台获取输入?

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:47 27 4
gpt4 key购买 nike

我正在尝试编写一个简单的 Python IRC 客户端。到目前为止,我可以读取数据,如果它是自动化的,我可以将数据发送回客户端。我在 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:如何在无限循环运行时从控制台获取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24000455/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com