简体   繁体   English

jupyter notebook 中的 asyncio 运行任务,失败时重试

[英]asyncio run task in jupyter notebook with retries upon failure

I would like to run a script.py file from a jupyter notebook:我想从 jupyter notebook 运行一个 script.py 文件:

%run script.py 

My task is to run a map-reduce on partitions of data on a dask cluster, asynchronously.我的任务是异步地对 dask 集群上的数据分区运行 map-reduce。 The workers sometimes (like 5% of cases) randomly crash, due to a connection error, that we did not figure out yet, what is the reason for it.由于连接错误,工作人员有时(大约 5% 的情况)随机崩溃,我们还没有弄清楚这是什么原因。 So, for now, I wanted to write a small loop around my async loop call that handles retrying up to n_tries_max times upon failure.所以,现在,我想围绕我的异步循环调用编写一个小循环,以在失败时处理重试最多 n_tries_max 次。 The code in script.py looks like this: script.py 中的代码如下所示:

# small wrapper for async stuff
async def my_func(args):
    await ...

# try running the function with retries on failure
n_tries_max = 3
n_try = 1
while n_try<=n_tries_max:
    try:
        loop = asyncio.get_event_loop()
        task = loop.create_task(my_func(args))
        asyncio.wait_for(task,timeout=None)
    except Exception as e:
        print(e)
        n_try += 1
        continue
    break

This works within jupyter notebook, however, I get a warning at the beginning:这在 jupyter notebook 中有效,但是,我在开始时收到警告:

/mt/users/jc/scripts/run_parallel_comp.py:62: RuntimeWarning: coroutine 'wait_for' was never awaited
  asyncio.wait_for(task,timeout=None)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

After the warning, the script keeps running and finishes correctly though.警告后,脚本继续运行并正确完成。 Just wanted to ask for the cause of this warning?只是想问一下这个警告的原因?

Thanks!谢谢!

In my opinion, you should differentiate the meaning of async/await in Javascript and Python.在我看来,你应该区分Javascript和Python中async/await的含义。

  • When you call an awaitable function, you create a new coroutine object in Python.当你调用一个可等待的 function 时,你在 Python 中创建了一个新的协程 object。

  • asyncio.create_task returns coroutine object to be waited using await keyword. asyncio.create_task返回协程 object 以使用await关键字等待。

You should probably call this coroutine object using await keyword.您可能应该使用await关键字将此协同程序称为 object。

# small wrapper for async stuff
async def my_func(args):
    await ...

# try running the function with retries on failure
n_tries_max = 3
n_try = 1
while n_try<=n_tries_max:
    try:
        loop = asyncio.get_event_loop()
        task = loop.create_task(my_func(args))
        await task
    except Exception as e:
        print(e)
        n_try += 1
        continue
    break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM