同时运行两个while循环,同时共享状态。异步还是队列?

2024-05-15 05:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让Python的curses和{}一起工作,但是它们都使用while循环。我不熟悉异步编程,所以很难找到解决这个问题的最佳解决方案。在

我需要这两个while循环同时运行,并且能够彼此共享信息。当slackclient接收到数据时,它需要显示在屏幕上。当用户输入文本时,它需要通过slackclient发送出去。在

我已经能够编写slackclient的测试运行,它使用asyncio来监听stdin,并写出它从stdin听到的内容。但是我被困在这里不知道该怎么做。我的下一步可能是什么?在

以下是slackclient/asyncio测试代码:

import asyncio
import time
import sys
from slackclient import SlackClient

class SlackCLI(object):
    def __init__(self):
        self.token = 'xoxp-TOKEN-HIDDEN'
        self.client = SlackClient(self.token)
        self.channel = '#general'

    def callback(self):
        text = sys.stdin.readline()

        print('[*] sending: {} to channel {}'.format(text, self.channel))
        print(self.client.api_call('chat.postMessage', channel='#general',
                                   text='{}'.format(text),
                                   username='pybot123', icon_emoji=':robot_face:'))

    @asyncio.coroutine
    def run(self):
        if self.client.rtm_connect():
            while True:
                last = self.client.rtm_read()
                if last:
                    try:
                        text = last[0]['text']
                        chan = last[0]['channel']
                        print('[!] {}: {}'.format(chan, text))

                    except:
                        pass

                yield from asyncio.sleep(1)
        else:
            print('connection failed')

    def main(self):
        loop = asyncio.get_event_loop()
        loop.add_reader(sys.stdin, self.callback)
        loop.run_until_complete(self.run())


a = SlackCLI()
a.main()

Tags: textimportselfclientloopasyncioformatdef

热门问题