我写了一个方法,用While True无限循环实现远程实时读取服务器的打印内容
def read_until(tn): # 子线程方法
buff = ''
while True:
resp = tn.recv(9999)
buff += resp.decode('utf-8')
time.sleep(3)
print(buff)
# ssh远程连接服务器
ssh = paramiko.SSHClient()
know_host = paramiko.AutoAddPolicy()
ssh.set_missing_host_key_policy(know_host)
ssh.connect(ip,port,'root','123456',timeout=5)
channel = ssh.invoke_shell()
#主线程开启子线程执行read_until方法
tn = threading.Thread(target=read_until(channel))
tn.start()
print("主线程继续运行")
运行发现窗口一直在打印服务器的输出,走不到最后的print,看起来像是子线程阻塞了主线程一样
debug发现是在子线程 tn 定义时传入了完整的方法调用语句 read_until(channel),直接导致主线程先去执行 read_until(channel) ,从而陷入了死循环,子线程初始化也无法完成
改为使用args传递参数
tn = threading.Thread(target=read_until, args=(channel,))
子线程正确运行,并且主线程不再阻塞