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

时间:2011-03-15 18:26:57

标签: python function background

我有两个功能,draw_ascii_spinnerfindCluster(companyid)

我想:

  1. 在后台运行findCluster(companyid)并进行处理....
  2. 运行draw_ascii_spinner直到findCluster(companyid)完成
  3. 我如何开始尝试解决此问题(Python 2.7)?

6 个答案:

答案 0 :(得分:11)

使用线程:

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]

答案 1 :(得分:7)

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

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

答案 2 :(得分:2)

通常,您将使用线程。这是一个简单的方法,假设只有两个线程: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()

答案 3 :(得分:1)

这可以通过线程来完成。 FindCluster在一个单独的线程中运行,完成后,它可以简单地发信号通知另一个轮询进行回复的线程。

答案 4 :(得分:1)

你想要对线程做一些研究,一般形式就是这个

  • 为findCluster创建一个新线程并为程序创建一些方法以了解该方法正在运行 - Python中最简单的只是一个全局布尔值
  • 在while循环中运行draw_ascii_spinner,条件是它是否仍在运行,你可能希望让这个线程在迭代之间短时间内休眠

这是Python的简短教程 - http://linuxgazette.net/107/pai.html

答案 5 :(得分:0)

在一个线程中运行findCluster()(Threading模块使这很简单),然后draw_ascii_spinner直到满足某些条件。

您可以等待线程的sleep()超时,而不是使用wait()来设置微调器的速度。

相关问题