我在python 3中有一个“ while True:”循环,该循环从com端口获取一些串行数据并对其进行处理。如果从端口读取了特定的字节字符串,则数据流需要串行写入才能继续发送数据。找到字节流并执行串行写入后,“ while True:”将停止运行。我认为这与键盘输入有关。
要进行故障排除,我插入了一些代码来手动输入串行写入,它可以工作,然后继续读取和处理数据。有人可以解释为什么“ while True:”循环停止运行以及如何使用不涉及键盘的命令对其进行修复吗?
代码如下:
ser = serial.Serial('/dev/ttyUSB1', 115200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0)
print(ser.name) # check which port was really used
while True:
try:
the_date = str(datetime.datetime.now())
# Read line from serial port in bytes
s = ser.readline()
#convert to utf-8 for use in serial operations
s_text_in = s.decode('utf_8')
if(s_text_in.find(com_strt_string) != -1):
print("found the specific string")
#all_logs_str = input("What is your name? ")
#type(all_logs_str)
all_logs_str = 'Send Data\r'
all_logs_str_bytes = all_logs_str.encode('utf-8', "ignore")
ser.write(all_logs_str.encode())
else:
print("skipped")
continue
info_type = port_interpreter(s_text_in)
print(s_text_in)
if(info_type == 1):
s_text = num_remover(s_text_in)
err_fl.write(the_date + ' ' + s_text + '\n')
print("wrote E")
elif(info_type == 2):
s_text = num_remover(s_text_in)
war_fl.write(the_date + ' ' + s_text + '\n')
print("wrote W")
else:
s_text = num_remover(s_text_in)
info_fl.write(the_date + ' ' + s_text + '\n')
print("wrote I")
except KeyboardInterrupt:
# Stopping flow of infinite loop.
print("[CTRL+C detected]")
err_fl.close()
war_fl.close()
info_fl.close()
谢谢
答案 0 :(得分:0)
使用pyautogui解决了该问题。当线程暂停时,Ubuntu python3.6空闲线程正在寻找一些(任何)键盘输入。一旦检测到键盘输入,它就会恢复。我不确定为什么会发生这种情况,但是可以解决问题。