pySerial very strange behaviour ... Code works when executed in shell but not in a script
Question: I'm struggling with pySerial. To be brief ... The code below works great when
executed in the Python Shell ...

    
    
    >>> import serial
    >>> s=serial.Serial("COM5", 9600)
    >>> while(1):
           s.write("#")
           s.readline()
    

Produces the output below in the shell:

    
    
    1L
    '56.73\r\n'
    1L
    '56.73\r\n'
    

When the same code is written in a script say "readSerial.py" the script will
either not transmit the hashtag that triggers the serial device to transmit
the data, or will not receive the replied data.

I'm using pySerial 3, but have noticed the same behavior with 2.7. Using
Python 2.7.10 64 bit on Win10. But also noticed this behavior on Raspberry Pi
with /dev/ttyACM0. I would really like to have this solved. I'm not that
experienced in Python so this might be an oversight.

Hardware is checked and double checked.

Thanks,

KK

* * *

Thanks, but I really know how to print data from Python. The problem is really
with pySerial. Here is the complete code, please don't discus errors in
commented out code. These are of no concern here.

    
    
    #from numpy import array
    #import matplotlib.animation as animation
    import time
    import serial as s
    
    #data = array([])
    
    Arduino = s.Serial("COM5", 9600)
    i = 0
    
    while (1):
        try:
             Arduino.write("#")
             time.sleep(.1)
             inString = Arduino.readline()
             data = float(inString)
    
             print i, ":", data
             i += 1
    
             time.sleep(1)
    
        except KeyboardInterrupt:
            break
    
    Arduino.close()
    

But like said this doesn't work. As far as I can tell the readline() function
does not return. And ... there 's really no point in making it return by
setting the tx timeout. To add to the mistery; When the code is debugged (i.e.
stepped trough) it does work.

Thanks in advance,

KK


Answer: From the [FAQ ](https://pythonhosted.org/pyserial/appendix.html#how-to):

> **Example works in serial.tools.miniterm but not in script.**
>
> **The RTS and DTR lines are switched when the port is opened.** This may
> cause some processing or reset on the connected device. In such a cases an
> immediately following call to write() may not be received by the device.
>
> A **delay after opening the port, before the first write()** , is
> recommended in this situation. E.g. a time.sleep(1)

