Your config file format is very simple and can easily be parsed without numpy. You can use simple string splitting to load each port definition.
serial_ports = []
with open('ports') as f:
for line in f:
port, baud = line.split(',')
serial_ports.append(serial.Serial(port, int(baud)))
Or you could use the csv
module:
import csv
with open('ports') as f:
serial_ports = [serial.Serial(port, int(baud)) for port, baud in csv.reader(f)]
The second part of your question is more difficult because you haven't provided many details about how the serial port readers will process the data received over the ports.
If the application is I/O bound, which is most likely the case, you can asynchronously check when a serial port has some data to read, then read it as required. That can be done with the select()
module, or if you're using Python >= 3.4, the selectors
module. You do not require multiple processes to do this.
If the application is CPU bound then you could use mutiprocessing.Process()
or subprocess.Popen()
. Instead of opening the serial ports in the parent, pass the serial port parameters to the child as arguments/command line arguments to the child function/process and let the child open the port, processes the data, and close the port.
N.B. Untested - don't know if this will work with a serial port. If you must open the ports in the parent, hook the stdin of the subprocess up to the serial port. You'll need to be careful with this as it's easy to deadlock processes where the parent and child are are mutually blocked on each other.
from subprocess import Popen, PIPE
s = serial.Serial(port, baud)
p = Popen(['python', 'port_reader.py'], stdin=s, stdout=PIPE, stderr=PIPE)
p.communicate()
If using multiprocessing
you can pass the open serial port to the child as an argument. This might work... ?
from multiprocessing import Process
def child(port):
while True:
line = port.readline()
if not line:
break
print('child(): read line: {!r}'.format(line))
port = serial.Serial(port, baud)
p = Process(target=child, args=(port,))
p.start()
p.join()