加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:35:45 所属栏目:Python 来源:网络整理
导读:我正在尝试编写一个简单的 Python IRC客户端.到目前为止,我可以读取数据,如果自动化,我可以将数据发送回客户端.我在一段时间内得到数据为True,这意味着我无法在读取数据的同时输入文本.如何在控制台中输入文本,只有在按Enter键时才会发送文本,同时运行无限循
我正在尝试编写一个简单的 Python IRC客户端.到目前为止,我可以读取数据,如果自动化,我可以将数据发送回客户端.我在一段时间内得到数据为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 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读