Python - 异步调用函数()?

时间:2018-03-23 09:14:08

标签: python asynchronous

以最短方式异步调用函数?

用户应始终能够输入新值; 但每个action()必须排队

def action(i):
   #takes a long time to be achieve

while True:
    i = raw_input("Input your value: ")
    action(i)

1 个答案:

答案 0 :(得分:2)

使用多处理模块:

from multiprocessing import Pool

def action(i):
   #takes a long time to be achieve

worker_pool = Pool(processes=1)
while True:
    i = raw_input("Input your value: ")
    result = worker_pool.apply_async(action, [i], callback)

您也可以将celery用于后台任务:

@celery_app.task(bind=True,max_retries=None)
def action(i):
   #takes a long time to be achieve

while True:
    i = raw_input("Input your value: ")
    action.apply_async(args=[i])