user904542
user904542

Reputation: 7075

How to I pass a value from a child script to a parent script that are both running at the same time?

Return a value early to a calling process in Python?

Hello, I want to ask is there a way to have one script call another script, have both those scripts running at the same time, and have the child script send a value to the parent script long before that child script is done running (WITHOUT exiting that child script early)? I'm looking for a solution in Python, but any information or clues would help, thankyou.

I think one way to do this is to print the value that you want to send back to the parent script to the standard output and then have the the parent script redirect it or pick it up some how, but there must be a better solution, because what if the child script prints other things? (then the parent script has to know how to isolate that exact part of the output with something like Unix head and tail commands, and what if you don't want to use the standard output at all?)

I have searched for answers on this, but I cannot find any.

Upvotes: 2

Views: 1702

Answers (2)

unutbu
unutbu

Reputation: 880299

You could use multiprocessing to launch the child script from the parent script. A mp.Queue could be used to communicate output from the child script back to the parent. Here is a simple example:

parent.py:

import multiprocessing as mp
import child

if __name__ == '__main__':
    queue = mp.Queue()
    proc = mp.Process(target=child.main, args=(queue,))
    proc.daemon = True  
    # This launches the child process, calling child.main()
    proc.start()         
    for i in range(10):
        result = queue.get()  # Get results from child.main
        print(result)

child.py:

import time

def main(queue=None):
    for i in range(10):
        # do a computation
        result = i
        if queue:
            # Put a result in the queue for the parent to get
            queue.put(result)   
        time.sleep(.5)

if __name__=='__main__':  
    # We reach here only when child.py is run as a script 
    # (as opposed to child being imported as a module).
    main()  

Note that the result passed through the queue must be picklable.

Upvotes: 4

msw
msw

Reputation: 43507

It is probably best to use the multiprocessing module which is designed for exactly this purpose.

Upvotes: 1

Related Questions