Python:运行一个函数直到另一个函数完成

2024-05-14 19:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个函数,draw_ascii_spinnerfindCluster(companyid)

我想:

  1. 在后台运行findCluster(companyid),同时处理。。。。
  2. 运行draw_ascii_spinner直到findCluster(companyid)完成

如何开始尝试解决这个问题(Python2.7)?


Tags: 函数ascii后台drawspinnercompanyidfindcluster
3条回答

使用线程:

import threading, time

def wrapper(func, args, res):
    res.append(func(*args))

res = []
t = threading.Thread(target=wrapper, args=(findcluster, (companyid,), res))
t.start()
while t.is_alive():
    # print next iteration of ASCII spinner
    t.join(0.2)
print res[0]

您可以使用multiprocessing。或者,如果findCluster(companyid)有合理的停止点,则可以将其与draw_ascii_spinner一起转换为生成器,以执行以下操作:

for tick in findCluster(companyid):
    ascii_spinner.next()

通常,您将使用线程。这里有一个简单的方法,假设只有两个线程:1)执行task的主线程,2)微调器线程:

#!/usr/bin/env python

import time
import thread

def spinner():
    while True:
        print '.'
        time.sleep(1)

def task():
    time.sleep(5)

if __name__ == '__main__':
    thread.start_new_thread(spinner, ())
    # as soon as task finishes (and so the program)
    # spinner will be gone as well
    task()

相关问题 更多 >

    热门问题