Python使用ssh执行命令的时候非阻塞的读取stdout
在使用python远程服务器执行相应的命令的时候,有的时候需要读取studo,例如下面的这个代码ssh = createSsh("x.x.x.x", "22", "username", "password")command = "bash --login -c '" + "sqlplus x/x@/home/oracle/aa.sql" + " '"stdin, stdout, stderr =
·
在使用python远程服务器执行相应的命令的时候,有的时候需要读取studo,例如下面的这个代码
ssh = createSsh("x.x.x.x", "22", "username", "password")
command = "bash --login -c '" + "sqlplus x/x @/home/oracle/aa.sql" + " '"
stdin, stdout, stderr = ssh.exec_command(command)
stdout_readlines = stdout.readlines(100)
但是如果直接通过exec_command命令返回的stdout然后进行读取输出操作的话,如果没有新的输出,就会阻塞当前的线程,如果想要以非阻塞的形式读取输出的话就不能以这种方式进行,需要换成下面这一种,使用通道进行读取,但是通过这个读取的时候 ,如果recv没有返回数据或者没有立即返回数据,这个时候就会抛出个异常,这个时候就需要根据你这边业务场景进行相应的处理
ssh = createSsh("x.x.x.x", "22", "username", "password")
command = "bash --login -c '" + "sqlplus x/x @/home/oracle/aa.sql" + " '"
stdin, stdout, stderr = ssh.exec_command(command)
channel = stdout.channel
channel.setblocking(False)
recv = channel.recv(100)

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)