You must feel strange about my need for this.Because I’m trying to integrate a function provided by a library which all fuction is defind with ‘async’ key word with a GUI interface which is powered by pyqt.
for example,I want use this async fuction in pyqt which is binded to a botton.clicked function.
async def doSomethingSlow():
# do something slow such as HTTP request
# ...
return result
so i just use asyncio.run(doSomethingSlow())
in the slot funciton.
but it doesn’t work.
The solution is below.
1.create a Qthread to run this function to avoid freezing GUI.
2.encapsulate this async fuction in a new async function which assigns return to nonlocal variable.
3.use loop = asyncio.new_event_loop()
to create a new loop and use asyncio.set_event_loop(loop)
to set it.
3.use loop.run_until_complete
to run this new async function
def test(Qthread):
finishSig = pyqtSignal()
def __init__(self):
super().__init__()
self.res = ''
def run(self):
result = ''
async def encapsulate():
nonlocal result
result = await doSomethingSlow()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(encapsulate())
self.res = result
self.finishSig.emit()