gpt4 book ai didi

Python 异步等待条件为真

转载 作者:行者123 更新时间:2023-11-28 17:59:29 29 4
gpt4 key购买 nike

我正在尝试编写一个异步方法来在配置单元上运行查询(使用 pyhive)。现在,pyhive 确实支持异步查询,我不知道如何在不阻塞的情况下等待查询完成。

我可以通过反复检查来等待查询完成,但这基本上和阻塞是一样的。

def runQuery():
cursor = hive.connect('localhost').cursor()
cursor.execute('select * from mytable', async_ = True)
status = cursor.poll().operationState
while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
status = cursor.poll().operationState
return cursor.fetchall()

所以我使用异步,但我不知道如何等待。我尝试了下面的代码,但它抛出 TypeError: object int can't be used in 'await' expression

async def runQueryAsync():
cursor = hive.connect('localhost').cursor()
cursor.execute('select * from mytable', async_ = True)
#THIS DOESN'T WORK
await cursor.poll().operationState not in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE)
return cursor.fetchall()

有什么解决方法吗?基本上我想要一种方法,而不是说 await methodCall,我说等待直到这个条件为真

PS:澄清一下,cursor.execute('select * from mytable', async_ = True) 在返回协程/ future 的 python 意义上不是异步的。它只是简单地开始一个查询并立即返回,你必须检查状态才能知道查询是否完成。所以 await cursor.execute('select * from mytable', async_ = True) 将不起作用。

最佳答案

您必须积极等待:

async def runQueryAsync():
cursor = hive.connect('localhost').cursor()
await cursor.execute('select * from mytable', async_ = True)
while cursor.poll().operationState not in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
await asyncio.sleep(1) # try each 1 second
return cursor.fetchall()

我不确定你是否可以 await cursor.execute('select * from mytable', async_ = True),但如果不行就使用 cursor.execute('select * from mytable', async_ = True) ,尽管在那里使用它是有意义的。如果它在执行时与 await 一起工作,您可能不需要使用 while 循环,因为它应该在执行完成后继续:

async def runQueryAsync():
cursor = hive.connect('localhost').cursor()
await cursor.execute('select * from mytable', async_ = True)
return cursor.fetchall()

关于Python 异步等待条件为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442483/

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