-1

Based on this thread, in Python, one can retrieve the returned value (a variable length string) of a function using a multiprocessing.Queue. But this involve to actually modify the function itself (by returning Q.put(retval) instead of retval).

What if one cannot modify the function (e.g. because it's was design as it is, also for other purposes such as an other usage which doesn't involve a call to a new thread)? Is it still possible to easily get the returned string value from this function when calling it through the multiprocessing library? And if yes, how?

swiss_knight
  • 5,787
  • 8
  • 50
  • 92
  • 1
    wrap the original function (the one you cant modify) with a new func that can put the result in a queue. – balderman Sep 15 '21 at 11:38

1 Answers1

0

Actually, one answer is rather simple. If you cannot modify the function itself, you can wrap it in a new one, e.g.:

def function_wraper(**kwargs):
    Q.put(unmodified_function(**kwargs))

And then, calling it as follows:

import multiprocessing

def unmodified_function(**kwargs):
    return ', '.join([f'{v}' for v in kwargs.values()])+' !'

def run_function_as_new_thread(func=unmodified_function, args=(), kwargs=None):
    procs = []
    p = multiprocessing.Process(
        target=func,
        args=args,
        kwargs=kwargs,
        name = (f"Process")
    )
    procs.append(p)
    p.start()
    for p in procs:
        p.join()

    return True

kwargs = {"hello": "Bonjour", "world": "le monde"}
Q = multiprocessing.Queue() # Q has to be defined before using function_wraper()
_ = run_function_as_new_thread(
    func=function_wraper,
    args = (),
    kwargs=kwargs
)
if not Q.empty():
    resulting_string = Q.get()
    print(resulting_string)
else:
    print('nothing to print...')

This will print Bonjour le monde !.

In my case this is working because my function is accepting kwargs, so you'll probably have to tweak if your function also have args.

swiss_knight
  • 5,787
  • 8
  • 50
  • 92