2

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?

user3754203
  • 139
  • 4
  • 8

1 Answers1

1

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.
GiulioG
  • 81
  • 5
  • I tired that and it still is not working i am getting the following error messages – user3754203 Jun 19 '14 at 19:28
  • If this command does not work and raises OSError, try with the option shell=True inside the Popen function. If doesn't work, what python version are you using and, is your bash script correct? – GiulioG Jun 19 '14 at 20:23
  • having the shell=True solved the problem, thanks a ton for your help with my problem – user3754203 Jun 20 '14 at 18:58
  • 1
    i'm happy it works, but it should work also without it, if your bash script is correct. I suggest you look for something in it, in example, does it have #!/bin/bash at the top? In this case the script works if called within a shell, but it doesn't if called outside. shell=True shoud be avoided because it could be a security risk. – GiulioG Jun 20 '14 at 19:16