简体   繁体   English

让Python等待函数完成后再继续执行程序

[英]Have Python wait for a function to finish before proceeding with the program

I have a python program that I have written. 我有一个编写的python程序。 This python program calls a function within a module I have also written and passes it some data. 这个python程序在我也写过的模块中调用一个函数,并将一些数据传递给它。

program: 程序:

def Response(Response):
    Resp = Response
def main():
   myModule.process_this("hello") #Send string to myModule Process_this function
   #Should wait around here for Resp to contain the Response
   print Resp

That function processes it and passes it back as a response to function Response in the main program. 该函数对其进行处理,并将其作为对主程序中函数Response的响应传递回去。

myModule: MyModule的:

def process_this(data)
    #process data
    program.Response(data)

I checked and all the data is being passed correctly. 我检查了一下,所有数据都正确传递了。 I have left out all the imports and the data processing to keep this question as concise as possible. 我省略了所有导入和数据处理,以使这个问题尽可能简洁。

I need to find some way of having Python wait for resp to actually contain the response before proceeding with the program. 我需要找到某种方式让Python等待resp实际包含响应,然后再继续执行该程序。 I've been looking threading and using semaphores or using the Queue module, but i'm not 100% sure how I would incorporate either into my program. 我一直在寻找线程和使用信号量或使用Queue模块,但我不确定100%如何将这两种方法都合并到程序中。

Here's a working solution with queues and the threading module. 这是带有队列和线程模块的有效解决方案。 Note: if your tasks are CPU bound rather than IO bound, you should use multiprocessing instead 注意:如果您的任务是CPU约束而不是IO约束,则应改用多处理

import threading
import Queue

def worker(in_q, out_q):
    """ threadsafe worker """
    abort = False
    while not abort:
        try:
            # make sure we don't wait forever
            task = in_q.get(True, .5)
        except Queue.Empty:
            abort = True
        else:
            # process task
            response = task
            # return result 
            out_q.put(response)
            in_q.task_done()
# one queue to pass tasks, one to get results
task_q = Queue.Queue()
result_q = Queue.Queue()
# start threads
t = threading.Thread(target=worker, args=(task_q, result_q))
t.start()
# submit some work
task_q.put("hello")
# wait for results
task_q.join()
print "result", result_q.get()

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

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