Python USB Serial works in IDLE but not when run as a file
<p>I'm currently attempting to write over USB serial to an Arduino Nano of mine using Python. However, what I've discovered is that (using the <em>exact</em> same code), the code works perfectly when I type it into IDLE, but when I save it to a file and attempt to run from there, for some reason the Arduino is never receiving the data. I've checked and in both locations the correct version of Python is being used (2.7.9) (I unfortunately can't use Python 3 due to other libraries I'm using).</p>

<p>The code I'm using:</p>

<pre><code>import serial
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600)
ser.write('0')
print ser.readline()
</code></pre>

<p>When I run it in IDLE just by typing in the lines individually, the correct behavior is seen: the Arduino responds (turning a servo) and echoes back the data it was sent, which is printed correctly. Running from a saved file however, the servo does not respond and no echo is received.</p>

<p>Any ideas?</p>

<p>I somehow missed this answer on SO before (<a href="http://stackoverflow.com/questions/28192190/pyserial-write-works-fine-in-python-interpreter-but-not-python-script?rq=1">pySerial write() works fine in Python interpreter, but not Python script</a>), but it turns out that I needed to add a time.sleep(2) after opening the serial port. My guess is that in IDLE the time it took for me to type the next line accounted for this delay, but it was happening instantly in code.</p>

python arduino raspberry-pi pyserial