我试图在她的异步函数中运行一些异步函数,问题是,我是如何理解函数不是那样运行的,那么我是如何实现的呢?我不想让maze_move函数异步。
async def no_stop():
#some logic
await asyncio.sleep(4)
async def stop(stop_time):
await asyncio.sleep(stop_time)
#some logic
def maze_move():
no_stop()
stop(1.5)
async def main(websocket):
global data_from_client, data_from_server, power_l, power_r
get_params()
get_data_from_server()
get_data_from_client()
while True:
msg = await websocket.recv()
allow_data(msg)
cheker(data_from_client)
data_from_server['IsBrake'] = data_from_client['IsBrake']
data_from_server['powerL'] = power_l
data_from_server['powerR'] = power_r
await websocket.send(json.dumps(data_from_server))
print(data_from_client['IsBrake'])
start_server = websockets.serve(main, 'localhost', 8080)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()发布于 2022-11-16 12:39:56
不如:
def maze_move():
loop = asyncio.get_event_loop()
loop.run_until_complete(no_stop())
loop.run_until_complete(stop(1.5))如果您想同时运行两个协同机制,那么:
def maze_move():
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(no_stop(), stop(1.5)))基于更新问题的更新
我猜你想做什么(见我对你问题的评论):
首先,您不能直接从maze_move协同器(如stop )调用,因为stop()不会导致调用stop --它只返回一个coroutine对象。因此,必须修改maze_move。我假设您不想让它本身成为一个协同线(既然您已经修改了它,为什么不呢?)此外,假设您希望从希望同时运行其他协同器的协同线程中调用maze_move,那么您可以创建一个新的协同线,例如,将在一个单独线程中运行maze_move的maze_move_runner,这样它就不会阻塞其他并发运行的协同线程:
import asyncio
import concurrent.futures
async def no_stop():
#some logic
print('no stop')
await asyncio.sleep(4)
async def stop(stop_time):
await asyncio.sleep(stop_time)
print('stop')
#some logic
async def some_coroutine():
print('Enter some_coroutine')
await asyncio.sleep(2)
print('Exit some_coroutine')
return 1
def maze_move():
# In case we are being run directly and not in a separate thread:
try:
loop = asyncio.get_running_loop()
except:
# This thread has no current event loop, so:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(no_stop())
loop.run_until_complete(stop(1.5))
return 'Done!'
async def maze_move_runner():
loop = asyncio.get_running_loop()
# Run in another thread:
return await loop.run_in_executor(None, maze_move)
async def main():
loop = asyncio.get_running_loop()
results = await (asyncio.gather(some_coroutine(), maze_move_runner()))
print(results)
asyncio.run(main())指纹:
Enter some_coroutine
no stop
Exit some_coroutine
stop
[1, 'Done!']但这将是最直接的解决方案:
async def maze_move():
await no_stop()
await stop(1.5)
return 'Done!'
async def main():
loop = asyncio.get_running_loop()
results = await (asyncio.gather(some_coroutine(), maze_move()))
print(results)发布于 2022-11-17 02:21:50
如果您有一个已经在运行的事件循环,您可以在同步函数的内部定义一个异步函数,并将其作为任务启动:
def maze_move():
async def amaze_move():
await no_stop()
await stop(1.5)
return asyncio.create_task(amaze_move())此函数返回一个asyncio.Task对象,该对象可以用于等待表达式,也可以用于等待表达式,具体取决于需求。这样,您就不必让maze_move本身成为一个异步函数,尽管我不知道这是一个目标。只有异步函数才能运行no_stop和stop,所以您必须在某个地方有一个异步函数。
https://stackoverflow.com/questions/74460454
复制相似问题