0

I have two python script, script1.py and script2.py. One is a counter which increment int x independently, and script2.py is to fetch the value of int x every 5 seconds, inputted into script2.py. I have tried doing this with multiprocessing verbatim from the following post,

Passing data between separately running Python scripts

and i applied While True function for script1. Here is my attempt, but i dont think i understand the general thought and i am getting various errors, since i am new to python and i miss some details.

script1.py:

from multiprocessing import Process, Pipe
x = 0

def function(child_conn):
    global x
    while True:
         x += 1
         print(x)
         child_conn.send(x)
         child_conn.close()

script2.py:

from multiprocessing import Proces,Queue,Pipe
from script1 import function
from time import sleep

if __name__=='__main__':
    parent_conn,child_conn = Pipe()
    p = Process(target=function, args=(child_conn,))
    p.start()
    print(parent_conn.recv())
    time.sleep(5)

thanks in Advance!

Lactobacillus
  • 27
  • 1
  • 1
  • 7
  • The post you're referencing only has partial code. Try this post instead: https://stackoverflow.com/questions/7749341/basic-python-client-socket-example – Mike67 Sep 12 '20 at 05:19
  • @Mike67 that post is about sockets. Am I missing something? – Algebra8 Sep 12 '20 at 05:27
  • @Lactobacillus can you be more explicit with your errors so we can help you better. – Algebra8 Sep 12 '20 at 05:28

1 Answers1

0

You have a loop in the child process but no loop in the parent process. With no loop, the child can only send a single message then throws an error.

Try this code. Run script2.py to start the process.

script1.py

from multiprocessing import Process, Pipe
from time import sleep
x = 0

def function(child_conn):
    global x
    while True:
         x += 1
         print(x)
         child_conn.send(x)
         #child_conn.close()
         sleep(1)

script2.py

from multiprocessing import Process,Queue,Pipe
from script1 import function
from time import sleep

if __name__=='__main__':
    parent_conn,child_conn = Pipe()
    p = Process(target=function, args=(child_conn,))
    p.start()
    while True:
        print(parent_conn.recv())
    sleep(1)
Mike67
  • 11,175
  • 2
  • 7
  • 15