Python Noob - stupid question? Works in Python Interpreter, not in CLI

I hope this is a simple stupid noob bug that can be fixed by adding one line of code somewhere.

I use pySerial to read in serial data from a USB port and print it to standard output. I am running Mac OSX 10.6. I open a terminal and write "python", and then the following:

>>> import serial;
>>> ser = serial.Serial('/dev/tty.usbserial-XXX', 9600, timeout=1);
>>> while True:
>>>      if ser.inWaiting() > 0:
>>>            ser.readline();
>>> [done, I hit enter...]

It works great. He begins to issue my serial data beautifully, exactly as I expected. Great, I think, let me put this in my own script with command line arguments, and then I can call it anytime I want:

import sys;
import serial;

serialPort = sys.argv[1]
baudRate = sys.argv[2]

ser = serial.Serial(serialPort, baudRate, timeout=1)

while True:
    if ser.inWaiting() > 0:
        ser.readline()

"python myScript.py [ ] 9600" , . , .

, , , - - . while, :

 while True:
    print("looping...")
    print(ser.inWaiting());
    if ser.inWaiting() > 0:
        ser.readline()

, "Looping..." "0". , , , - , script, .

, ? True: - script ? ?

Python noob. script, Adobe AIR Arduino. , , - ?

+3
3

-? , :

looping...
<ser.inWaiting() val>

. ,

print ser.readline()

, . , , , script readline() .

+1

- , , sys.argv[2] . ser = serial.Serial(serialPort, int(baudRate), timeout=1).

+1

True: script ?

Nope. This is a very standard practice and does not affect I / O. while Truevery strongly equivalent while 1in C.

Is there a better way to do this?

I am worried about your arguments, like others. This should be more reliable:

from sys import argv
from serial import Serial

try:
    baudRate = int(argv[-1])
    serialPort = argv[1:-1]
except ValueError:
    #some nice default
    baudRate = 9600
    serialPort = argv[1:]

#support paths with spaces. Windows maybe?
serialPort = ' '.join(serialPort)
if not serialPort:
    exit("Please specify a serial port")

print( "reading from %r@%i ..." % (serialPort, baudRate) )
ser = Serial(serialPort, baudRate, timeout=1)    
while True:
    if ser.inWaiting() > 0:
        print( ser.readline() )

If this does not help you, make sure that you use the same interpreter by running these lines in the script and in the CLI.

import sys
print("Executable: " + sys.executable)
print("Version: " + sys.version)
0
source

Source: https://habr.com/ru/post/1771947/


All Articles