Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法从Redis订阅中获取数据?_Python_Redis_Callback_Python Asyncio - Fatal编程技术网

Python 无法从Redis订阅中获取数据?

Python 无法从Redis订阅中获取数据?,python,redis,callback,python-asyncio,Python,Redis,Callback,Python Asyncio,我试图通过在客户端应用程序上使用订阅从redis通道获取数据。为此,我将python与asyncio和aioredis一起使用 我想使用我的订阅在服务器上更改主应用程序时更新主应用程序的变量,但我无法将从订阅接收到的数据传递到我的主线程 根据aioredis,我通过以下方式实现了我的订阅: sub = await aioredis.create_redis( 'redis://localhost') ch1 = await sub.subscribe('channel:1') ass

我试图通过在客户端应用程序上使用订阅从redis通道获取数据。为此,我将python与asyncio和aioredis一起使用

我想使用我的订阅在服务器上更改主应用程序时更新主应用程序的变量,但我无法将从订阅接收到的数据传递到我的主线程

根据aioredis,我通过以下方式实现了我的订阅:

sub = await aioredis.create_redis(
     'redis://localhost')

ch1 = await sub.subscribe('channel:1')
assert isinstance(ch1, aioredis.Channel)

async def async_reader(channel, globarVar):
    while await channel.wait_message():
        msg = await channel.get(encoding='utf-8')
        # ... process message ...
        globarVar = float(msg)
        print("message in {}: {}".format(channel.name, msg))

tsk1 = asyncio.ensure_future(async_reader(ch1, upToDateValue))
但我无法更新全局变量,我猜python只将当前值作为参数传递(我希望如此,但希望如此)


从订阅中获取数据是否有可行的选择?或者要传递对我可以使用的共享变量或队列的引用?

您应该重新设计代码,这样就不需要全局变量。您的所有处理都应该在收到消息时进行。但是,要修改全局变量,需要在函数中用global关键字声明它。你不需要传递全局变量,你只需要使用它们

分:

出版商:

import asyncio
import aioredis

async def main():
    pub = await aioredis.create_redis('redis://localhost')

    res = await pub.publish_json('channel:1', ["Hello", "world"])
    await asyncio.sleep(1)
    res = await pub.publish_json('channel:1', "stop")

    pub.close()


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())

谢谢MarkReedZ,非常好的例子和解释。我还想提醒那些可能尝试您的代码的人,请确保您已安装tornado==4.5.3,而不是它的更新版本,否则您可能会遇到错误:
import asyncio
import aioredis

async def main():
    pub = await aioredis.create_redis('redis://localhost')

    res = await pub.publish_json('channel:1', ["Hello", "world"])
    await asyncio.sleep(1)
    res = await pub.publish_json('channel:1', "stop")

    pub.close()


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(main())