0

I have 2 python scripts. Is it possible to somehow run the second script from the first in parallel?

How to return a value from the second script to the first?

For example:

#script 1

def train():
  .......
return True

and

#script 2 

t = threading.Thread(target=train.train)
t.start()

You must close the process when the function returns true. How to solve this problem?

Nishant
  • 20,354
  • 18
  • 69
  • 101
Alevtina
  • 147
  • 11
  • 1
    Possible duplicate of [Running Python script parallel](https://stackoverflow.com/questions/33518282/running-python-script-parallel) – clubby789 Aug 05 '19 at 12:44
  • 1
    Possible duplicate of [How to do parallel programming in Python](https://stackoverflow.com/questions/20548628/how-to-do-parallel-programming-in-python) – Mark G Aug 05 '19 at 12:46
  • What are you trying to achieve -- can you elaborate? – Nishant Aug 05 '19 at 12:47
  • 1
    Possible duplicate of [Run separate processes in parallel - Python](https://stackoverflow.com/questions/19080792/run-separate-processes-in-parallel-python) – basilisk Aug 05 '19 at 12:48

2 Answers2

0

Is it possible to somehow run the second script from the first in parallel?

Yes we can using multiprocessing module (documentation).

How to return a value from the second script to the first?

In that this section explains far enough Sharing state between processes to deal with above query

You must close the process when the function returns true

Same Section Sharing state between processes to deal with above query

jpganz18
  • 5,508
  • 17
  • 66
  • 115
0

Yes. And to get the return values, use a Queue (which was designed with threads in mind; it is thread-safe).

# script 1
def train(queue, x):
    queue.put(x)

# script 2
import threading
import queue

q = queue.Queue()
t1 = threading.Thread(target=train.train, args=(q, 1))
t2 = threading.Thread(target=train.train, args=(q, 2))

t1.start()
t2.start()

t1.join()
t2.join()

while not q.empty():
    print(q.get())

Prints:

1
2
brentertainer
  • 2,118
  • 1
  • 6
  • 15
  • I do not want to wait for the end of the second process. I want to run this in parallel. Therefore I can not use .join () – Alevtina Aug 06 '19 at 06:09
  • Do you mean you want the threads to run in parallel with each other? Or do they have to run in parallel with something else (e.g. the main thread)? – brentertainer Aug 06 '19 at 06:33
  • @Алевтина Did you try running this without `.join()`? – brentertainer Aug 06 '19 at 06:34
  • yes. In this case, everything works. But I want to run the function every time as soon as my condition is fulfilled, get the True result from it as a confirmation of completion. This is a problem because I cannot use .start () a second time because the process is not completed. – Alevtina Aug 06 '19 at 06:44