我如何使用python中的ESCape键与串行端口进行交互?

问题描述 投票:0回答:1

我正在尝试使用ESCape键返回“菜单”页面,但似乎无法在if语句中实现它。按下ESCape键后,返回主菜单。我正在使用Python 3.7

import serial
import Keyboard
ser = serial.Serial ('COM18', baudrate = 115200, timeout = 1) #USB Serial Device

def getMenuData():
    PhoenixMainMenu = ser.readline().decode('ascii')
    return PhoenixMainMenu   

def printScreen():
    n=20
    while n <= 20: #as long as 
        print(getMenuData()) 
        n-=1 
        if n >= 0: 
            print (getMenuData())
            n-=1 
        else:
            break     

while True:
    print (printScreen())
    print ('Escape Key brings you back to main menu')
    UserInput = input('To access option type its coresponding number: ')
    if UserInput == '1':
        ser.write(b'1') #HW test
        print ('first is the worst')
        secondInput = input('To access the function type letter: ')
        if secondInput == 'a':
            ser.write(b'a') 
        else:   
            print ('Invalid entry. Please Try again.')
        break

    elif UserInput == keyboard.wait('esc')
        ser.write(b'0x1b') 
        print ('Main MEnu')
        print (printScreen())        
        break

    else:
        print ('Invalid entry. Please Try again.')
python-3.x keyboard pyserial
1个回答
0
投票

Python 3字符串是Unicode,因此您可以完成此任务,但是由于转义键被认为是字符,因此您无法像现在那样完成它。试试这个:

if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
aborted = True
break
© www.soinside.com 2019 - 2024. All rights reserved.