wim wim - 1 year ago 300
Python Question

how to get the return value from a thread in python?

How can I access that return value 'foo' from the thread?

def foo(bar):
print 'hello {0}'.format(bar)
return 'foo'

from threading import Thread
t = Thread(target=foo, args=('world!',))
x = t.join()
print x

The one obvious way to do it, above, seems to just return
in x.

Answer Source

FWIW, the multiprocessing module has a nice interface for this using the Pool class. And if you want to stick with threads rather than processes, you can just use the multiprocessing.pool.ThreadPool class as a drop-in replacement.

def foo(bar, baz):
  print 'hello {0}'.format(bar)
  return 'foo' + baz

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)

async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo

# do some other stuff in the main process

return_val = async_result.get()  # get the return value from your function.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download