pythonserial-portteraterm

Serial Comunication via Python


I'm trying to write a command and read how the system reply to it. The code I've done is the following:

import serial
import time
import sys

ser = serial.Serial('COM5', 38400, timeout=1)
print(ser.name)  
msg = 'show interfaces status ethernet 0/1'
ser.write((msg.encode()))

time.sleep(0.5)
res=ser.read(ser.inWaiting())
print ((res.decode()))
ser.close()

doing so I have no error but the output I see is this:

COM5 show interfaces status ethernet 0/1

Using TeraTerm and with the same setup and the same command I see instead the reply of the system which show the status of the ethernet port.

The only difference I could notice is that in Teraterm the command line is with "Console#".


Solution

  • Basically there were two errors in my previous attempt: 1- I was missing the "enter" once I've written the command (so the +'\r') 2- I need also a loop in order to read all the information

    this is how I've done in the end:

    import serial
    import time
    
    
    
    #ser = serial.Serial('COM5', 38400, timeout=1)
    ser = serial.Serial()
    #ser.port = "/dev/ttyUSB0"
    ser.port = "COM5"
    ser.baudrate = 38400
    
    
    
    
    
    try: 
        ser.open()
        print(ser.name) 
    except:
        print ("Errore apertura porta seriale" )
        exit()
    
    
    if ser.isOpen():
             ser.flushInput()
             ser.flushOutput()
             msg = 'show interfaces status ethernet 0/1'+'\r'
             ser.write((msg.encode()))
             time.sleep(0.5)
             while 1:
                bytesToRead = ser.inWaiting()
                print (bytesToRead)
                out=ser.read(bytesToRead)
                time.sleep(1)
                print(out.decode())
                if bytesToRead>=255:
                    break
               
        
    ser.close()
    

    as I said I'm not a programmer...so I'm 100% this can be done better...but it worked for me.