简体   繁体   English

Python-异步调用function()吗?

[英]Python - Asynchronously call of a function()?

What's the shortest way to call a function asyncronously? 异步调用函数的最短方法是什么?

The user should always be able to input a new value; 用户应始终能够输入新值; But each action() must be queued 但是每个action()必须排队

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

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

Use Multiprocessing module: 使用多处理模块:

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)

You can also use celery for background tasks: 您也可以将芹菜用于后台任务:

@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])

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

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