user3754203
user3754203

Reputation: 139

running two subprocesses simultaneously from python module

I am trying to execute two sub-processes at the same time from a python module on a raspberry pi. Currently the second process has to wait for the first one to finish before it starts but I was wondering if there was a way to have both of them be started at the same time. The data that is being read in only gives a line every 5 seconds, and the two .sh programs do not take more than a second each to finish. If you have any suggestions on how to do this properly or if there is a work around it would be greatly appreciated. The code is below:

f = open("testv1.txt", "a")
import serial
import subprocess
ser = serial.Serial('/dev/ttyACM0', 115200)
while 1:
    x= ser.readline()
    subprocess.call(['./camera1.sh'],shell=True)
    subprocess.call(['./camera2.sh'],shell=True)
    print(x)
    f.write(str(x))

So i changed the code so that it now does:

cam1 = subprocess.Popen("./camera1.sh")
cam2 = subprocess.Popen("./camera2.sh")

but now i am getting the following errors:

Traceback (most recent call last):
  File "/home/pi/Desktop/Doyle/CaptureV1/testv1.py", line 7, in <module>
    cam1 = subprocess.Popen("./camera1.sh")
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 8] Exec format error

any other suggestions on how to fix it?

Upvotes: 2

Views: 3672

Answers (1)

GiulioG
GiulioG

Reputation: 81

You need to use the Popen Constructor that execute a child program in a new process. In this way you can actually have two threads doing something at the same time.

try something like:

###someCode

cam1 = subprocess.Popen("./camera1.sh")
cam2 = subprocess.Popen("./camera2.sh")

###othercode

be careful to manage threads correctly. After this call, it's a good thing to check if child processes have terminated whith the method poll() or wait:

cam1.wait() #wait until the child terminates
cam1.poll() #return the status of the child process.

Upvotes: 1

Related Questions