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!

3
  • The post you're referencing only has partial code. Try this post instead: stackoverflow.com/questions/7749341/… Commented Sep 12, 2020 at 5:19
  • @Mike67 that post is about sockets. Am I missing something? Commented Sep 12, 2020 at 5:27
  • @Lactobacillus can you be more explicit with your errors so we can help you better. Commented Sep 12, 2020 at 5:28

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.