-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"
drobot
  • 23
  • 5
  • Does this answer your question? [Interprocess communication in Python](https://stackoverflow.com/questions/6920858/interprocess-communication-in-python) – tbhaxor Sep 05 '21 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. – Danny Varod Sep 05 '21 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. – drobot Sep 06 '21 at 01:34
  • @drobot the question is ambiguous, clarify in the question, not comments – Danny Varod Sep 09 '21 at 08:16

1 Answers1

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:

Berkay
  • 53
  • 9