Muhc
Muhc

Reputation: 1

Modify a variable in target Subprocess

Have been searching for days and didn't find an answer or it didn't work for me.

I've built home alarm system with Raspberry Pi and PIR sensor. The alarm system consists of control.py and alarm.py scripts. The control.py is simple flask webpage for controlling alarm detection. The alarm.py is basicaly a while loop that checks if the sensor has been trigered.

I'm starting alarm.py with Popen from control.py. Is there a way to modify a variable in alarm.py from control.py (so that the while loop breaks and program exits)?

Line of code in control.py that starts a detection program:

detection = subprocess.Popen(['python', 'alarm.py'], shell=False)

And the loop in alarm.py:

while True:


    CurrentState=GPIO.input(GPIO_PIR)

    if CurrentState==1 and PreviousState==0:
        print "Motion detected!"
        PreviousState=1
    elif CurrentState==1 and PreviousState==1:
        print "Motion detected!"
    elif CurrentState==0 and PreviousState==1:
        PreviousState=0

    time.sleep(0.1)

GPIO.cleanup()

Upvotes: 0

Views: 80

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208475

Since you are starting alarm.py as a separate process, there is no shared variable space for directly setting any variable from control.py that alarm.py can access.

You have a few options here:

  • Use threads instead of subprocessing
  • Use the multiprocessing module which provides mechanisms for communication between two Python processes
  • Attach stdin of your alarm.py subprocess to a pipe and attempt a non-blocking read on each iteration of the loop, write to that pipe from control.py when you are ready to exit
  • Use some OS level modification as the signal for alarm.py to exit (for example, the creation of a file in a specific location)

Upvotes: 1

Related Questions