-1

For a Raspberry Pi-based project I'm working on, I want to have a main program and a "status checker" secondary script. In other words, when the first program is started, I want it to start as a background service and kick me back out to Terminal, and then the secondary program can be used to check the first program's status/progress.

I need the main program to send variable values to the status checking script, which will then print them to Terminal. I found this old post, but it doesn't seem to work.

I modified the code a bit from the old post, but here it is. The import main doesn't import the function, it seems to just run main.py. I added the for loop in main.py as a placeholder for the stuff I would be doing in the main script.

#main.py

from multiprocessing import Process,Pipe
import time

def f(child_conn):
    msg = "Hello"
    child_conn.send(msg)
    child_conn.close()

for i in range(1000000):
    print(i)
    time.sleep(0.05)
#second.py

from multiprocessing import Process,Queue,Pipe
from main import f

if __name__ == '__main__':
    parent_conn,child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())   # prints "Hello"
4
  • Does this answer your question? Interprocess communication in Python Commented Sep 5, 2021 at 20:43
  • It is unclear from the title and the content of the question if you are running two applications on the same OS, two threads in the same application or two applications or two devices (this one seems less likely from the content). The first is inter-process communication the second if multithreading (or multiprocessing) the third is distributed processing. There are a variety of solutions for each. Please correct the title, tags and content. Commented Sep 5, 2021 at 20:48
  • Berkay's answer below works, so why is all of the multiprocessing stuff required? To prevent the scripts from trying to modify a variable at the same time? @DannyVarod - The two scripts are running on the same Raspberry Pi, and they are different applications. Commented Sep 6, 2021 at 1:34
  • @drobot the question is ambiguous, clarify in the question, not comments Commented Sep 9, 2021 at 8:16

1 Answer 1

0

The problem is that when second.py imports f from main.py, it runs everything on the global scope. If you remove them, you can see that your process and pipe do work. If you want to keep that part as well you can do something like:

if __name__ == '__main__':
    for i in range(1000000):
        print(i)
        time.sleep(0.05)

Refer to this answer why this is the case:

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.