[英]Have Python wait for a function to finish before proceeding with the program
我有一個編寫的python程序。 這個python程序在我也寫過的模塊中調用一個函數,並將一些數據傳遞給它。
程序:
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
該函數對其進行處理,並將其作為對主程序中函數Response的響應傳遞回去。
MyModule的:
def process_this(data)
#process data
program.Response(data)
我檢查了一下,所有數據都正確傳遞了。 我省略了所有導入和數據處理,以使這個問題盡可能簡潔。
我需要找到某種方式讓Python等待resp實際包含響應,然后再繼續執行該程序。 我一直在尋找線程和使用信號量或使用Queue模塊,但我不確定100%如何將這兩種方法都合並到程序中。
這是帶有隊列和線程模塊的有效解決方案。 注意:如果您的任務是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.