user1721451 user1721451 - 26 days ago 11
Python Question

Raspberry Pi Model B Threading. Run 2 python scripts concurrently

I'm hoping you can help (as always). I'm making a photobooth and in short have a Python script to control the light (switches on for 30 seconds) and another to take 4 photos for the photobooth.
I need to run the light script followed by the camera script 5 seconds later. I'm sure this is easy, but can't work it out. Here's what I've tried:

I'm not even sure if this is correct for the Raspberry Pi, but this is what I've tried inc. variations:

import threading
import time
def light():
while time.time() <= start_time:
pass
threading.Thread(target="sudo python /home/pi/python/light30.py").start()
def camera():
while time.time() <= start_time:
pass
threading.Thread(target="sudo python /home/pi/python/camtest.py").start()
start_time=time.time()+5
threading.Thread(target=light).start()
threading.Thread(target=camera).start()


Any help you can provide would be great, as I'm sure im being an idiot.

Answer

as mentioned in the comments threading expects to run python code ... not a python file ... you can just use subprocess to accomplish that you want

import subprocess
import time

lights_proc = subprocess.Popen(["/usr/bin/python","/home/pi/python/light30.py"])
time.sleep(5) # sleep for 5 seconds
print subprocess.Popen(["/usr/bin/python","/home/pi/python/camtest.py"],stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()

the communicate call at the end just makes it block and wait for camtest.py to complete before exiting this script (as well as getting the output from the script)

Comments