python read multiple serial ports
<p>I am trying to read from multiple serial ports in python. But contrary to <a href="http://stackoverflow.com/questions/27484250/python-pyserial-read-data-form-multiple-serial-ports-at-same-time">this</a> thread I want to be able to change the number of ports dynamically (reading it via command line option).</p>

<p>My idea was to put the ports into a file "ports", read this file and put the opened serial ports into a list, according to the number of lines in "ports". My minimal example:</p>

<pre><code>import numpy as np
import serial

p = np.genfromtxt('ports',delimiter=',',dtype=None)
nser = p.size

ser = [serial.Serial(port=p[i][0], baudrate=p[i][1]) for i in xrange(nser)]
</code></pre>

<p>"ports" looks the following (at the moment):</p>

<pre><code>'/dev/ttyUSB0',4800
</code></pre>

<p>The error: </p>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: 0-d arrays can't be indexed
</code></pre>

<p>Apparently the file is not correctly read to an array, and I already tried various different methods and ways (using pythons own methods or np.loadtxt).</p>

<p>Does anybody have an idea how to a) read the file correctly and b) solve the multiple port issue in a useful way? Thanks in advance.</p>

<p>I didn't quite clearly understood what you are trying to do, but if 
I had a file like:</p>

<pre><code>'/dev/ttyUSB0',4800
'/dev/ttyUSB1',4801,'/dev/ttyUSB3',4803
</code></pre>

<p>and want to read it and store as a list, a way to go would be:</p>

<pre><code>with open('ports.txt') as f:
    lines = f.read().replace('\n', ',')
print lines 
</code></pre>

<p>which will give you:</p>

<pre><code>&gt;&gt;&gt; lines
'/dev/ttyUSB0',4800,'/dev/ttyUSB1',4801,'/dev/ttyUSB3',4803
</code></pre>

<p>and if you want to split the integers, you could do:</p>

<pre><code>&gt;&gt;&gt; l1 = [lines.pop(i) for i,j in enumerate(lines) if type(j)==int ]
&gt;&gt;&gt; l1
[4800, 4801, 4803]
&gt;&gt;&gt; lines
['/dev/ttyUSB0', '/dev/ttyUSB1', '/dev/ttyUSB3']
</code></pre>

<p>Now because you said that 'np.loadtxt' didn't work, a way to convert a python list to a numpy-array is:</p>

<pre><code>&gt;&gt;&gt; lines = ['/dev/ttyUSB0',4800,'/dev/ttyUSB1',4801,'/dev/ttyUSB3',4803]
&gt;&gt;&gt;
&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; np.asarray(lines)
array(['/dev/ttyUSB0', '4800', '/dev/ttyUSB1', '4801', '/dev/ttyUSB3',
       '4803'],
      dtype='|S12')
</code></pre>

<p>But again I am not sure If that is what you are looking for. </p>

python serial-port readfile