python subprocess 实现Terminal命令行运行 有点小bug

import serial, threading
import time, sys, subprocess, os
import queue

class auto_run():
# 命令的结束标志
end_sign = 'END'
def __init__(self):
self.flag = True
self.popen = None
self.Retry_num = None
self.Result_Pass = True
self.t = None
self.if_repeat = True
self.recv_pop = False

self.check_print_data = False
self.check_deta = False
self.result = queue.Queue()

def send_cmd(self):
with open("SAV526_Flash - RCY2.txt", "r", encoding="utf8") as f:
send_List = f.readlines()
print(send_List)
max_ = len(send_List) - 1
for index, cmd in enumerate(send_List):
if index == 0: continue
cmd = cmd.strip()
cmd = cmd.replace(r"\u", "")
cmd = cmd.replace(r"\n", "")
print(">>%s:" % cmd)
self.popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if self.check_print_data == False:
self.result.put(True)
threading.Thread(target=self.read_response).start()
self.check_print_data = True
time.sleep(1)
self.exec_command("")

def read_response(self):
while self.Result_Pass: # time out
line = self.popen.stdout.readlines()
if line == []:
time.sleep(0.2)
self.check_deta = False
threading.Thread(target=self.recv_timeout).start()
else:
for linestr in line:
self.check_deta = True
try:
print(linestr.decode("utf8").strip())
time.sleep(0.2)
except UnicodeDecodeError as e:
print(linestr.decode("gb2312").strip())
time.sleep(0.2)
try:
self.Result_Pass = self.result.get()
except:
self.Result_Pass = True

def close(self):
try:
self.popen.kill()
self.popen.stdin.close()
self.popen.stdout.close()
except:
pass

def exec_command(self, comm):
try:
comm += os.linesep
self.popen.stdin.write(comm.encode('utf8'))
self.popen.stdin.write(('echo ' + self.end_sign + os.linesep).encode('utf8'))
self.popen.stdin.flush()
except:
pass

def recv_timeout(self):
try:
print("输出无数据开始计时>>>>>>>>>> ")
t = 0
while t <= 10:
t += 1
time.sleep(1)
if self.check_deta == False:
continue
if self.check_deta == True:
break

if t > 10:
print("超时无信息退出>>>>>>>>>>>>>>> ")
self.result.put(False)
else:
self.result.put(True)
except:
self.close()
return


# strip()
if __name__ == '__main__':
shell = auto_run()
result = shell.send_cmd()















































posted @ 2021-08-30 22:55  九点半Andy  阅读(80)  评论(0)    收藏  举报