简体   繁体   中英

Continuosly Read/Monitor Serial Port(if port not opened continuously run script) using python

Im newbie for python and serial port. I want to monitor serial port continuously. If port not opened or access denied, need to run the python script without stop. I had done something, But that script has stopped when the PORT not opened or access denied. kindly, help someone to close this issue.

import serial
z1baudrate = 9600
z1port = 'COM4'
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
try:
   if z1serial.is_open:
      while True:           
        size = z1serial.inWaiting()                   
        if size:                
            data = z1serial.read(size)                                                  
            res= data.decode("utf-8")   
            print(res)      
        else:
            print("Data not reading")
       time.sleep(1)
  else:
    z1serial.close()
    print('z1serial not open or Already in use')
except serial.SerialException as e:
  z1serial.close()
  print('COM4 not open')

You need to include the z1serial assignment inside the try block as

import serial
import time
z1baudrate = 9600
z1port = 'COM4'
while True:
    try:
        z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
        if z1serial.is_open:
            while True:           
                size = z1serial.inWaiting()                   
                if size:                
                    data = z1serial.read(size)                                                  
                    res= data.decode("utf-8")   
                    print(res)      
                else:
                    print("Data not reading")
                time.sleep(1)
        else:
            z1serial.close()
            print('z1serial not open or Already in use')
    except serial.SerialException:
        print('COM4 not open')
        time.sleep(1)

This worked for me, running on Python 3.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM