esp32 python上位机(命令行)

import os
import sys
import tty
import termios
import serial
import serial.tools.list_ports

class ser_conf:
        
    def port_choose(self):
        port_list = list(serial.tools.list_ports.comports())
        if len(port_list)!=0:
            print(type(port_list))
            print(len(port_list))
            for p in port_list:
                print(p.device)
            port = input("please choose which port to open:
")
            print(port)
           # port = int(port)
            print(port_list[int(port)].device)
            print(type(port_list[int(port)].device))
            return port_list[int(port)].device
                #return p.device
        print("can't find port!
")
        return False
    

class str_conf:
    
    def get_str(self): # 类里的函数不加self会报错
        cmd = input("please input cmd:
")
        len_str = len(cmd)
        return cmd,len_str
    
    def which_str(self):
        tuple = self.get_str() 
        print("string is %s,len is %d
" %(tuple[0],tuple[1]))  # 输出字符串和格式化字符串之间不能有逗号
            
if __name__ == '__main__':  #sudo chmod 666 /dev/ttyUSB0
    
    ser_conf = ser_conf()
    ser = serial.Serial(ser_conf.port_choose(),115200)
    str_conf=str_conf()
    if (ser.isOpen):
        print(ser.port)
        
    string=""
    while True:
        #string=string.join(str(ser.read()))
        string=string.join('%s' %ser.readline())
        print(string)
        if "which ssid choose" in string:
            cmd = input("please choose ssid:
")
            ser.write(cmd.encode())
        elif "print password" in string:
            cmd = input("please input password
")
            ser.write(cmd.encode())
        elif "got ip" in string:
            ser.close()
            print("serial has closed
")
        string=''
        
    #str_conf.which_str()
    

原文地址:https://www.cnblogs.com/ligei/p/15425661.html