只要同步代码继续运行,我就打算运行一个异步函数(它执行与程序其他部分相关的操作,但不返回任何内容)。但是,在我运行asyncio.run()
命令之后,程序就永远只执行异步命令。你知道吗
我尝试过一些基本的线程和多进程池方法,但我发现这是我尝试过的最成功的方法:
# There's some code up here (A), and it runs synchronously and fine.
# Here's the asynchronous code (B).
pauseAsynchronousFunction = False
async def asynchronousFunction():
global pauseAsynchronousFunction
# Do stuff before hitting the while loop.
while True:
if pauseAsynchronousFunction == False:
# Do some stuff.
else:
# Do some other stuff.
asyncio.run(pauseAsynchronousFunction())
# More synchronous code is down here (C), which it never reaches.
我可以看出它没有像我期望的那样工作,因为下面的另一个函数(在C中)调用相同的全局变量pauseAsynchronousFunction
,并将其从False
切换到True
,然后在运行完成后再次返回False
。这种切换从未发生过。你知道吗
我猜问题要么与while True
有关,我不明白为什么它是异步的,要么与不包含await
语句有关。我还缺什么?你知道吗
更新:
我在pypy的帮助下进行了一些调试尝试,得到了这个结果。你知道吗
pauseAsynchronousFunction = False
async def fun2():
global pauseAsynchronousFunction
while True:
if pauseAsynchronousFunction == False:
#do stuff
else:
#do other stuff
async def fun1():
global pauseAsynchronousFunction
pauseAsynchronousFunction = True
#do stuff here that you wanted to do after the `asyncio.run` above
pauseAsynchronousFunction = False
return stuff
async def main():
await asyncio.gather(
fun1(),
fun2(),
)
asyncio.run(main)
问题似乎是:
pauseAsynchronousFunction
切换到True
,但不会切换回fun(1)
末尾的False
。你知道吗
asyncio.run
将阻塞,直到异步函数全部返回。因此,在asyncio.run()
之后的代码应该转换为异步函数,即下面是一个使用线程和事件的替代答案:
相关问题 更多 >
编程相关推荐