【问题标题】:Python async await on condition being truePython异步等待条件为真
【发布时间】:2019-06-04 10:56:27
【问题描述】:

我正在尝试编写一个异步方法来在 hive 上运行查询(使用 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()

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

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

【问题讨论】:

    标签: python python-3.x python-asyncio


    【解决方案1】:

    您必须积极等待

    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()
    

    【讨论】:

    • 为什么要每秒重新执行一次查询?这与查询最多执行一次的 OP 代码不同
    • asyncio.sleep 与常规 time.sleep 相比是非阻塞的吗?
    • @hoodakaushal,确实,它是非阻塞的。通常你会想要使用 asyncio.sleep 而不是 time.sleep 来处理协程
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多